code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
'use strict'; const express = require('express'); const service = express(); var os = require('os'); var networkInterfaces = os.networkInterfaces(); module.exports = service; module.exports.networkInterfaces = networkInterfaces;
orhaneee/SlackBotHeroku
server/service.js
JavaScript
gpl-3.0
232
<?php /** * The template for displaying search results pages * * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#search-result * * @package ibreatheart */ get_header(); ?> <section id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php if ( have_posts() ) : ?> <header class="page-header"> <h1 class="page-title"><?php printf( esc_html__( 'Search Results for: %s', 'ibreatheart' ), '<span>' . get_search_query() . '</span>' ); ?></h1> </header><!-- .page-header --> <?php /* Start the Loop */ while ( have_posts() ) : the_post(); /** * Run the loop for the search to output the results. * If you want to overload this in a child theme then include a file * called content-search.php and that will be used instead. */ get_template_part( 'template-parts/content', 'search' ); endwhile; the_posts_navigation(); else : get_template_part( 'template-parts/content', 'none' ); endif; ?> </main><!-- #main --> </section><!-- #primary --> <?php get_sidebar(); get_footer();
BracketMonks/hackathon-frontend
wordpress-project/ibreatheart-underscores/search.php
PHP
gpl-3.0
1,111
package bio.singa.simulation.model.modules; import bio.singa.simulation.entities.ChemicalEntity; import bio.singa.features.model.Evidence; import bio.singa.features.model.Feature; import bio.singa.simulation.model.modules.concentration.ModuleState; import bio.singa.simulation.model.simulation.Simulation; import java.util.Collection; import java.util.List; import java.util.Set; /** * @author cl */ public interface UpdateModule extends Runnable { String getIdentifier(); ModuleState getState(); void setSimulation(Simulation simulation); Set<ChemicalEntity> getReferencedChemicalEntities(); Set<Class<? extends Feature>> getRequiredFeatures(); void checkFeatures(); void setFeature(Feature<?> feature); Collection<Feature<?>> getFeatures(); List<Evidence> getEvidence(); void initialize(); void reset(); void onReset(); void onCompletion(); }
cleberecht/singa
singa-simulation/src/main/java/bio/singa/simulation/model/modules/UpdateModule.java
Java
gpl-3.0
906
import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; class Main{ public static class Agency { String name; int A, B; public Agency(String s) { StringTokenizer st=new StringTokenizer(s,":"); this.name=st.nextToken(); st=new StringTokenizer(st.nextToken(),","); this.A=Integer.parseInt(st.nextToken()); this.B=Integer.parseInt(st.nextToken()); } } public static class Result implements Comparable<Result> { Agency a; int cost; public int compareTo(Result r) { return (this.cost!=r.cost) ? this.cost-r.cost : this.a.name.compareTo(r.a.name); } } public static void main (String [] args) throws Exception { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); int testCaseCount=Integer.parseInt(br.readLine()); for (int testCase=1;testCase<=testCaseCount;testCase++) { StringTokenizer st=new StringTokenizer(br.readLine()); int N=Integer.parseInt(st.nextToken()); int M=Integer.parseInt(st.nextToken()); int L=Integer.parseInt(st.nextToken()); Agency [] agencies=new Agency [L]; for (int l=0;l<L;l++) agencies[l]=new Agency(br.readLine()); Result [] results=new Result[L]; for (int l=0;l<L;l++) { Agency agency=agencies[l]; results[l]=new Result(); results[l].a=agency; int curr=N; int cost=0; while (curr>M) { if (curr/2>=M) { int c1=agency.B; int c2=(curr-curr/2)*agency.A; curr/=2; if (c1<c2) cost+=c1; else cost+=c2; } else { cost+=(curr-M)*agency.A; curr=M; } } results[l].cost=cost; } Arrays.sort(results); StringBuilder sb=new StringBuilder(); sb.append("Case "); sb.append(testCase); sb.append('\n'); for (Result r: results) { sb.append(r.a.name); sb.append(' '); sb.append(r.cost); sb.append('\n'); } System.out.print(sb.toString()); } } }
PuzzlesLab/UVA
King/10670 Work Reduction.java
Java
gpl-3.0
1,957
/* * 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/>. */ /* * CleanUpHandler.java * Copyright (C) 2009 University of Waikato, Hamilton, New Zealand */ package adams.core; /** * Interface for classes that support cleaning up of memory. * * @author FracPete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public interface CleanUpHandler { /** * Cleans up data structures, frees up memory. */ public void cleanUp(); }
waikato-datamining/adams-base
adams-core/src/main/java/adams/core/CleanUpHandler.java
Java
gpl-3.0
1,068
/* Copyright (C) 2012 Andrew Cotter 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/>. */ /** \file svm_optimizer_classification_unbiased_perceptron.cpp \brief SVM::Optimizer::Unbiased::Perceptron implementation */ #include "svm_optimizer_classification_unbiased_perceptron.hpp" namespace SVM { namespace Optimizer { namespace Classification { namespace Unbiased { //============================================================================ // Perceptron methods //============================================================================ Perceptron::~Perceptron() { } unsigned int const Perceptron::TrainingSize() const { return m_pKernel->TrainingSize(); } unsigned int const Perceptron::ValidationSize() const { return( m_pKernel->Size() - m_pKernel->TrainingSize() ); } void Perceptron::GetAlphas( double* const begin, double* const end ) const { unsigned int const trainingSize = m_pKernel->TrainingSize(); if ( end != begin + trainingSize ) throw std::runtime_error( "Perceptron::GetAlphas parameter array has incorrect length" ); double const scale = 1 / std::sqrt( m_normSquared ); for ( unsigned int ii = 0; ii < trainingSize; ++ii ) begin[ ii ] = m_alphas[ ii ] * scale; } double const Perceptron::NormSquared() const { return 1; } void Perceptron::GetValidationResponses( double* const begin, double* const end ) const { unsigned int const trainingSize = m_pKernel->TrainingSize(); unsigned int const totalSize = m_pKernel->Size(); BOOST_ASSERT( trainingSize <= totalSize ); if ( trainingSize >= totalSize ) throw std::runtime_error( "Perceptron::GetValidationResponses requires a validation set" ); if ( end != begin + totalSize - trainingSize ) throw std::runtime_error( "Perceptron::GetValidationResponses parameter array has incorrect length" ); { double const scale = 1 / std::sqrt( m_normSquared ); double* pDestination = begin; double* pDestinationEnd = end; double const* pResponse = m_responses.get() + trainingSize; double const* pLabel = m_pKernel->Labels() + trainingSize; for ( ; pDestination != pDestinationEnd; ++pDestination, ++pResponse, ++pLabel ) { double const response = *pResponse * scale; *pDestination = ( ( *pLabel > 0 ) ? response : -response ); } } } double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, SparseVector< float > const& otherVector ) const { return EvaluateHelper( otherVector ); } double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, SparseVector< double > const& otherVector ) const { return EvaluateHelper( otherVector ); } double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, SpanVector< float > const& otherVector ) const { return EvaluateHelper( otherVector ); } double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, SpanVector< double > const& otherVector ) const { return EvaluateHelper( otherVector ); } double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, DenseVector< float > const& otherVector ) const { return EvaluateHelper( otherVector ); } double const Perceptron::Evaluate( Random::Generator::LaggedFibonacci4<>& generator, DenseVector< double > const& otherVector ) const { return EvaluateHelper( otherVector ); } void Perceptron::Iterate( Random::Generator::LaggedFibonacci4<>& generator ) { unsigned int const trainingSize = m_pKernel->TrainingSize(); double const scaledMargin = m_margin * std::sqrt( m_normSquared ); FindKappa(); if ( m_kappa < scaledMargin ) { unsigned int index = m_index; double kappa = scaledMargin; { double const* pAlpha = m_alphas.get(); double const* pAlphaEnd = pAlpha + trainingSize; double const* pResponse = m_responses.get(); double const* pLabel = m_pKernel->Labels(); for ( ; pAlpha != pAlphaEnd; ++pAlpha, ++pResponse, ++pLabel ) { if ( *pAlpha != 0 ) { double const response = ( ( *pLabel > 0 ) ? *pResponse : -*pResponse ); if ( UNLIKELY( response <= kappa ) ) { index = ( pAlpha - m_alphas.get() ); kappa = response; } } } } if ( m_pKernel->Labels()[ index ] > 0 ) { m_normSquared += 2 * m_responses[ index ] + m_normsSquared[ index ]; m_pKernel->SetAlpha( m_alphas.get(), m_responses.get(), index, m_alphas[ index ] + 1 ); } else { m_normSquared += -2 * m_responses[ index ] + m_normsSquared[ index ]; m_pKernel->SetAlpha( m_alphas.get(), m_responses.get(), index, m_alphas[ index ] - 1 ); } m_index = trainingSize; m_kappa = std::numeric_limits< double >::quiet_NaN(); } } void Perceptron::Recalculate() { unsigned int const trainingSize = m_pKernel->TrainingSize(); m_pKernel->RecalculateResponses( m_alphas.get(), m_responses.get() ); { double accumulator = 0; double const* pAlpha = m_alphas.get(); double const* pAlphaEnd = pAlpha + trainingSize; double const* pResponse = m_responses.get(); for ( ; pAlpha != pAlphaEnd; ++pAlpha, ++pResponse ) accumulator += *pAlpha * *pResponse; BOOST_ASSERT( accumulator >= 0 ); m_normSquared = accumulator; } m_index = trainingSize; m_kappa = std::numeric_limits< double >::quiet_NaN(); } void Perceptron::FindKappa() const { if ( boost::math::isnan( m_kappa ) ) { unsigned int const trainingSize = m_pKernel->TrainingSize(); m_index = trainingSize; m_kappa = std::numeric_limits< double >::infinity(); double const* pResponse = m_responses.get(); double const* pResponseEnd = pResponse + trainingSize; double const* pLabel = m_pKernel->Labels(); for ( ; pResponse != pResponseEnd; ++pResponse, ++pLabel ) { double const response = ( ( *pLabel > 0 ) ? *pResponse : -*pResponse ); if ( UNLIKELY( response < m_kappa ) ) { m_index = ( pResponse - m_responses.get() ); m_kappa = response; } } } BOOST_ASSERT( m_index < m_pKernel->TrainingSize() ); BOOST_ASSERT( ! boost::math::isnan( m_kappa ) ); } } // namespace Unbiased } // namespace Classification } // namespace Optimizer } // namespace SVM
maliq/issvm
svm_optimizer_classification_unbiased_perceptron.cpp
C++
gpl-3.0
6,718
<?php /** * Normatividad Torreón - ReglamentoArchivoMunicipal * * Copyright (C) 2017 Guillermo Valdés Lozano <guivaloz@movimientolibre.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @package NormatividadTorreon */ namespace ReglamentosVigentes; /** * Clase ReglamentoArchivoMunicipal */ class ReglamentoArchivoMunicipal extends \Base\PublicacionSchemaArticle { /** * Constructor */ public function __construct() { // Ejecutar constructor en el padre parent::__construct(); // Título, autor y fecha $this->nombre = 'Reglamento del Archivo Municipal de Torreón'; //~ $this->autor = ''; $this->fecha = '2013-01-01T00:00'; // El nombre del archivo a crear $this->archivo = 'reglamento-archivo-municipal'; // La descripción y claves dan información a los buscadores y redes sociales $this->descripcion = 'El presente reglamento tiene por objeto la guarda, preservación, conservación preventiva, restauración, conducción, depuración y aprovechamiento institucional y social del patrimonio archivístico municipal.'; $this->claves = 'Reglamento, Vigente, Archivo, Municipal'; // Ruta al archivo markdown con el contenido $this->contenido_archivo_markdown = 'lib/ReglamentosVigentes/ReglamentoArchivoMunicipal.md'; } // constructor } // Clase ReglamentoArchivoMunicipal ?>
normatividadtorreon/normatividadtorreon.github.io
lib/ReglamentosVigentes/ReglamentoArchivoMunicipal.php
PHP
gpl-3.0
2,138
/************************* Coppermine Photo Gallery ************************ Copyright (c) 2003-2016 Coppermine Dev Team v1.0 originally written by Gregory DEMAR This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 as published by the Free Software Foundation. ******************************************** Coppermine version: 1.6.01 $HeadURL$ $Revision$ **********************************************/ /* * Date prototype extensions. Doesn't depend on any * other code. Doesn't overwrite existing methods. * * Adds dayNames, abbrDayNames, monthNames and abbrMonthNames static properties and isLeapYear, * isWeekend, isWeekDay, getDaysInMonth, getDayName, getMonthName, getDayOfYear, getWeekOfYear, * setDayOfYear, addYears, addMonths, addDays, addHours, addMinutes, addSeconds methods * * Copyright (c) 2006 Jörn Zaefferer and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net) * * Additional methods and properties added by Kelvin Luck: firstDayOfWeek, dateFormat, zeroTime, asString, fromString - * I've added my name to these methods so you know who to blame if they are broken! * * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * */ /** * An Array of day names starting with Sunday. * * @example dayNames[0] * @result 'Sunday' * * @name dayNames * @type Array * @cat Plugins/Methods/Date */ Date.dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; /** * An Array of abbreviated day names starting with Sun. * * @example abbrDayNames[0] * @result 'Sun' * * @name abbrDayNames * @type Array * @cat Plugins/Methods/Date */ Date.abbrDayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; /** * An Array of month names starting with Janurary. * * @example monthNames[0] * @result 'January' * * @name monthNames * @type Array * @cat Plugins/Methods/Date */ Date.monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; /** * An Array of abbreviated month names starting with Jan. * * @example abbrMonthNames[0] * @result 'Jan' * * @name monthNames * @type Array * @cat Plugins/Methods/Date */ Date.abbrMonthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; /** * The first day of the week for this locale. * * @name firstDayOfWeek * @type Number * @cat Plugins/Methods/Date * @author Kelvin Luck */ Date.firstDayOfWeek = 1; /** * The format that string dates should be represented as (e.g. 'dd/mm/yyyy' for UK, 'mm/dd/yyyy' for US, 'yyyy-mm-dd' for Unicode etc). * * @name format * @type String * @cat Plugins/Methods/Date * @author Kelvin Luck */ Date.format = 'dd/mm/yyyy'; //Date.format = 'mm/dd/yyyy'; //Date.format = 'yyyy-mm-dd'; //Date.format = 'dd mmm yy'; /** * The first two numbers in the century to be used when decoding a two digit year. Since a two digit year is ambiguous (and date.setYear * only works with numbers < 99 and so doesn't allow you to set years after 2000) we need to use this to disambiguate the two digit year codes. * * @name format * @type String * @cat Plugins/Methods/Date * @author Kelvin Luck */ Date.fullYearStart = '20'; (function() { /** * Adds a given method under the given name * to the Date prototype if it doesn't * currently exist. * * @private */ function add(name, method) { if( !Date.prototype[name] ) { Date.prototype[name] = method; } }; /** * Checks if the year is a leap year. * * @example var dtm = new Date("01/12/2008"); * dtm.isLeapYear(); * @result true * * @name isLeapYear * @type Boolean * @cat Plugins/Methods/Date */ add("isLeapYear", function() { var y = this.getFullYear(); return (y%4==0 && y%100!=0) || y%400==0; }); /** * Checks if the day is a weekend day (Sat or Sun). * * @example var dtm = new Date("01/12/2008"); * dtm.isWeekend(); * @result false * * @name isWeekend * @type Boolean * @cat Plugins/Methods/Date */ add("isWeekend", function() { return this.getDay()==0 || this.getDay()==6; }); /** * Check if the day is a day of the week (Mon-Fri) * * @example var dtm = new Date("01/12/2008"); * dtm.isWeekDay(); * @result false * * @name isWeekDay * @type Boolean * @cat Plugins/Methods/Date */ add("isWeekDay", function() { return !this.isWeekend(); }); /** * Gets the number of days in the month. * * @example var dtm = new Date("01/12/2008"); * dtm.getDaysInMonth(); * @result 31 * * @name getDaysInMonth * @type Number * @cat Plugins/Methods/Date */ add("getDaysInMonth", function() { return [31,(this.isLeapYear() ? 29:28),31,30,31,30,31,31,30,31,30,31][this.getMonth()]; }); /** * Gets the name of the day. * * @example var dtm = new Date("01/12/2008"); * dtm.getDayName(); * @result 'Saturday' * * @example var dtm = new Date("01/12/2008"); * dtm.getDayName(true); * @result 'Sat' * * @param abbreviated Boolean When set to true the name will be abbreviated. * @name getDayName * @type String * @cat Plugins/Methods/Date */ add("getDayName", function(abbreviated) { return abbreviated ? Date.abbrDayNames[this.getDay()] : Date.dayNames[this.getDay()]; }); /** * Gets the name of the month. * * @example var dtm = new Date("01/12/2008"); * dtm.getMonthName(); * @result 'Janurary' * * @example var dtm = new Date("01/12/2008"); * dtm.getMonthName(true); * @result 'Jan' * * @param abbreviated Boolean When set to true the name will be abbreviated. * @name getDayName * @type String * @cat Plugins/Methods/Date */ add("getMonthName", function(abbreviated) { return abbreviated ? Date.abbrMonthNames[this.getMonth()] : Date.monthNames[this.getMonth()]; }); /** * Get the number of the day of the year. * * @example var dtm = new Date("01/12/2008"); * dtm.getDayOfYear(); * @result 11 * * @name getDayOfYear * @type Number * @cat Plugins/Methods/Date */ add("getDayOfYear", function() { var tmpdtm = new Date("1/1/" + this.getFullYear()); return Math.floor((this.getTime() - tmpdtm.getTime()) / 86400000); }); /** * Get the number of the week of the year. * * @example var dtm = new Date("01/12/2008"); * dtm.getWeekOfYear(); * @result 2 * * @name getWeekOfYear * @type Number * @cat Plugins/Methods/Date */ add("getWeekOfYear", function() { return Math.ceil(this.getDayOfYear() / 7); }); /** * Set the day of the year. * * @example var dtm = new Date("01/12/2008"); * dtm.setDayOfYear(1); * dtm.toString(); * @result 'Tue Jan 01 2008 00:00:00' * * @name setDayOfYear * @type Date * @cat Plugins/Methods/Date */ add("setDayOfYear", function(day) { this.setMonth(0); this.setDate(day); return this; }); /** * Add a number of years to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addYears(1); * dtm.toString(); * @result 'Mon Jan 12 2009 00:00:00' * * @name addYears * @type Date * @cat Plugins/Methods/Date */ add("addYears", function(num) { this.setFullYear(this.getFullYear() + num); return this; }); /** * Add a number of months to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addMonths(1); * dtm.toString(); * @result 'Tue Feb 12 2008 00:00:00' * * @name addMonths * @type Date * @cat Plugins/Methods/Date */ add("addMonths", function(num) { var tmpdtm = this.getDate(); this.setMonth(this.getMonth() + num); if (tmpdtm > this.getDate()) this.addDays(-this.getDate()); return this; }); /** * Add a number of days to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addDays(1); * dtm.toString(); * @result 'Sun Jan 13 2008 00:00:00' * * @name addDays * @type Date * @cat Plugins/Methods/Date */ add("addDays", function(num) { this.setDate(this.getDate() + num); return this; }); /** * Add a number of hours to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addHours(24); * dtm.toString(); * @result 'Sun Jan 13 2008 00:00:00' * * @name addHours * @type Date * @cat Plugins/Methods/Date */ add("addHours", function(num) { this.setHours(this.getHours() + num); return this; }); /** * Add a number of minutes to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addMinutes(60); * dtm.toString(); * @result 'Sat Jan 12 2008 01:00:00' * * @name addMinutes * @type Date * @cat Plugins/Methods/Date */ add("addMinutes", function(num) { this.setMinutes(this.getMinutes() + num); return this; }); /** * Add a number of seconds to the date object. * * @example var dtm = new Date("01/12/2008"); * dtm.addSeconds(60); * dtm.toString(); * @result 'Sat Jan 12 2008 00:01:00' * * @name addSeconds * @type Date * @cat Plugins/Methods/Date */ add("addSeconds", function(num) { this.setSeconds(this.getSeconds() + num); return this; }); /** * Sets the time component of this Date to zero for cleaner, easier comparison of dates where time is not relevant. * * @example var dtm = new Date(); * dtm.zeroTime(); * dtm.toString(); * @result 'Sat Jan 12 2008 00:01:00' * * @name zeroTime * @type Date * @cat Plugins/Methods/Date * @author Kelvin Luck */ add("zeroTime", function() { this.setMilliseconds(0); this.setSeconds(0); this.setMinutes(0); this.setHours(0); return this; }); /** * Returns a string representation of the date object according to Date.format. * (Date.toString may be used in other places so I purposefully didn't overwrite it) * * @example var dtm = new Date("01/12/2008"); * dtm.asString(); * @result '12/01/2008' // (where Date.format == 'dd/mm/yyyy' * * @name asString * @type Date * @cat Plugins/Methods/Date * @author Kelvin Luck */ add("asString", function() { var r = Date.format; return r .split('yyyy').join(this.getFullYear()) .split('yy').join((this.getFullYear() + '').substring(2)) .split('mmm').join(this.getMonthName(true)) .split('mm').join(_zeroPad(this.getMonth()+1)) .split('dd').join(_zeroPad(this.getDate())); }); /** * Returns a new date object created from the passed String according to Date.format or false if the attempt to do this results in an invalid date object * (We can't simple use Date.parse as it's not aware of locale and I chose not to overwrite it incase it's functionality is being relied on elsewhere) * * @example var dtm = Date.fromString("12/01/2008"); * dtm.toString(); * @result 'Sat Jan 12 2008 00:00:00' // (where Date.format == 'dd/mm/yyyy' * * @name fromString * @type Date * @cat Plugins/Methods/Date * @author Kelvin Luck */ Date.fromString = function(s) { var f = Date.format; var d = new Date('01/01/1977'); var iY = f.indexOf('yyyy'); if (iY > -1) { d.setFullYear(Number(s.substr(iY, 4))); } else { // TODO - this doesn't work very well - are there any rules for what is meant by a two digit year? d.setFullYear(Number(Date.fullYearStart + s.substr(f.indexOf('yy'), 2))); } var iM = f.indexOf('mmm'); if (iM > -1) { var mStr = s.substr(iM, 3); for (var i=0; i<Date.abbrMonthNames.length; i++) { if (Date.abbrMonthNames[i] == mStr) break; } d.setMonth(i); } else { d.setMonth(Number(s.substr(f.indexOf('mm'), 2)) - 1); } d.setDate(Number(s.substr(f.indexOf('dd'), 2))); if (isNaN(d.getTime())) { return false; } return d; }; // utility method var _zeroPad = function(num) { var s = '0'+num; return s.substring(s.length-2) //return ('0'+num).substring(-2); // doesn't work on IE :( }; })();
CatBerg-TestOrg/coppermine
js/date.js
JavaScript
gpl-3.0
13,375
from biot import * # display_wires(N_wires=6, r_wires=r_wires) display_quiver() display_particles(mode_name="boris_exact", colormap="Blues") # display_particles(mode_name="RK4_exact", colormap="Reds") print("Finished display") mlab.show()
StanczakDominik/PythonBiotSavart
plot.py
Python
gpl-3.0
240
# This should hold main initialization logic puts "hello world"
benweissmann/rise
src/src/main.rb
Ruby
gpl-3.0
63
package info.jlibrarian.stringutils; /* Original source code (c) 2013 C. Ivan Cooper. Licensed under GPLv3, see file COPYING for terms. */ import java.util.Comparator; /** * Represents a comparable wildcard string, also contains static functions for comparing wildcard strings. * * A wildcard string is any String. If the wildcard string includes an asterisk '*', then for the purpose * of comparison, only the characters before the asterisk need match the other wildcard string. * * if any wildcards are used, this comparison is symmetric and reflexive, but it is NOT transitive - * e.g. a=b and b=c but maybe not a=c * * for example, these pairs of wildcard strings are all considered "equal" * foobar foobar * foo* foobar * foobar foo* * * foobar * foobar foobar* * * @author C. Ivan Cooper (ivan@4levity.net) * */ public class WildcardString implements Comparable<WildcardString>,Comparator<String> { private final String string; /** * Compares two strings with a simple wildcard rule (see WildcardString) * * @param a * @param b * @return comparison result or 0 if equal */ static public int compareWildcardString(String a,String b) { if(a==null && b==null) return 0; //else if(a==null) return -1; //else if(b==null) return 1; int wca=a.indexOf("*"); int wcb=b.indexOf("*"); if(wcb>=0) { b = b.substring(0,wcb); // remove * and trailing chars if(a.length()>wcb) a = a.substring(0,wcb); } if(wca>=0) { a = a.substring(0,wca); // remove * and trailing chars if(b.length()>wca) b = b.substring(0,wca); } return a.compareToIgnoreCase(b); //return a.compareTo(b); } static public String generalizeWildcard(String s) { if (s==null) return "*"; int ix=s.length()-1; if(ix<=1) return "*"; while(ix>0 && s.charAt(ix)=='*') ix--; // skip any * fields starting from the end return s.substring(0, ix)+"*"; } public WildcardString(String s) { if(s==null) string="*"; else string=s; } public WildcardString() { string="*"; } /** * note: violates transitivity of equality * @param arg0 * @param arg1 * @return */ public int compare(String arg0, String arg1) { return compareWildcardString(arg0,arg1); } /** * note: violates transitivity of equality * @param arg0 * @return */ public int compareTo(WildcardString arg0) { if(arg0==null) throw new NullPointerException("cannot compare WildcardString to null"); return compareWildcardString(string,arg0.toString()); } @Override public String toString() { return string; } /** * note: violates transitivity of equality * @param obj * @return */ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final WildcardString other = (WildcardString) obj; return (0==compareTo(other)); } @Override public int hashCode() { int hash = 3; hash = 79 * hash + (this.string != null ? this.string.hashCode() : 0); return hash; } }
4levity/Conan
src/main/java/info/jlibrarian/stringutils/WildcardString.java
Java
gpl-3.0
3,562
<?php /** * acm : Algae Culture Management (https://github.com/singularfactory/ACM) * Copyright 2012, Singular Factory <info@singularfactory.com> * * This file is part of ACM * * ACM 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. * * ACM 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 ACM. If not, see <http://www.gnu.org/licenses/>. * * @copyright Copyright 2012, Singular Factory <info@singularfactory.com> * @package ACM.Frontend * @since 1.0 * @link https://github.com/singularfactory/ACM * @license GPLv3 License (http://www.gnu.org/licenses/gpl.txt) */ ?> <?php use_helper('BarCode'); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="title" content="Algae culture management | Banco Español de Algas" /> <meta name="description" content="Algae culture management of Banco Español de Algas" /> <meta name="keywords" content="bea, banco, español, algas, marine, biotechnology, spanish, banl, algae" /> <meta name="language" content="en" /> <meta name="robots" content="index, follow" /> <title>Algae culture management | Banco Español de Algas</title> <link rel="shortcut icon" href="/favicon.ico" /> <link rel="stylesheet" type="text/css" media="screen" href="/css/labels.css" /> </head> <body> <?php foreach ($strains as $strain):?> <table width="100%"> <tr> <th width="25%" style="text-align:right;">BEA Number</th> <td style="text-align:left;"><?php echo $strain->getFullCode();?></td> </tr> <tr> <th width="25%" style="text-align:right;">Genus</th> <td style="text-align:left;"><?php echo $strain->getGenus();?></td> </tr> <tr> <th width="25%" style="text-align:right;">Species</th> <td style="text-align:left;"><?php echo $strain->getSpecies();?></td> </tr> <tr> <th width="25%" style="text-align:right;">Class</th> <td style="text-align:left;"><?php echo $strain->getTaxonomicClass();?></td> </tr> <tr> <th width="25%" style="text-align:right;">Public</th> <td style="text-align:left;"><?php echo $strain->getIsPublic();?></td> </tr> <tr> <th width="25%" style="text-align:right;">Internal Code</th> <td style="text-align:left;"><?php echo $strain->getInternalCode();?></td> </tr> <tr> <th width="25%" style="text-align:right;">Remarks</th> <td style="text-align:left;"><?php echo $strain->getRemarks();?></td> </tr> </table> <hr/> <?php endforeach; ?> </body> </html>
singularfactory/ACM
apps/frontend/modules/report/templates/_maintenance_pdf.php
PHP
gpl-3.0
3,157
package TFC.Handlers.Client; import org.lwjgl.opengl.GL11; import TFC.*; import TFC.Core.TFC_Core; import TFC.Core.TFC_Settings; import TFC.Core.TFC_Time; import TFC.Core.Player.PlayerInfo; import TFC.Core.Player.PlayerManagerTFC; import TFC.Items.*; import TFC.TileEntities.TileEntityWoodConstruct; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.entity.*; import net.minecraft.client.gui.inventory.*; import net.minecraft.client.renderer.Tessellator; import net.minecraft.block.*; import net.minecraft.block.material.*; import net.minecraft.crash.*; import net.minecraft.creativetab.*; import net.minecraft.entity.*; import net.minecraft.entity.ai.*; import net.minecraft.entity.effect.*; import net.minecraft.entity.item.*; import net.minecraft.entity.monster.*; import net.minecraft.entity.player.*; import net.minecraft.entity.projectile.*; import net.minecraft.inventory.*; import net.minecraft.item.*; import net.minecraft.nbt.*; import net.minecraft.network.*; import net.minecraft.network.packet.*; import net.minecraft.pathfinding.*; import net.minecraft.potion.*; import net.minecraft.server.*; import net.minecraft.stats.*; import net.minecraft.tileentity.*; import net.minecraft.util.*; import net.minecraft.village.*; import net.minecraft.world.*; import net.minecraft.world.biome.*; import net.minecraft.world.chunk.*; import net.minecraft.world.gen.feature.*; import net.minecraftforge.client.ForgeHooksClient; import net.minecraftforge.client.event.DrawBlockHighlightEvent; import net.minecraftforge.event.ForgeSubscribe; public class PlankHighlightHandler{ @ForgeSubscribe public void DrawBlockHighlightEvent(DrawBlockHighlightEvent evt) { World world = evt.player.worldObj; double var8 = evt.player.lastTickPosX + (evt.player.posX - evt.player.lastTickPosX) * (double)evt.partialTicks; double var10 = evt.player.lastTickPosY + (evt.player.posY - evt.player.lastTickPosY) * (double)evt.partialTicks; double var12 = evt.player.lastTickPosZ + (evt.player.posZ - evt.player.lastTickPosZ) * (double)evt.partialTicks; if(evt.currentItem != null && evt.currentItem.getItem() instanceof ItemPlank) { //Setup GL for the depthbox //GL11.glEnable(GL11.GL_BLEND); //GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); //GL11.glColor3f(1,1,1); //GL11.glDisable(GL11.GL_CULL_FACE); //GL11.glDepthMask(false); //ForgeHooksClient.bindTexture("/bioxx/woodoverlay.png", ModLoader.getMinecraftInstance().renderEngine.getTexture("/bioxx/woodoverlay.png")); // double blockMinX = evt.target.blockX; // double blockMinY = evt.target.blockY; // double blockMinZ = evt.target.blockZ; // double blockMaxX = evt.target.blockX+1; // double blockMaxY = evt.target.blockY+1; // double blockMaxZ = evt.target.blockZ+1; // drawFaceUV(AxisAlignedBB.getAABBPool().addOrModifyAABBInPool( // blockMinX, // blockMinY, // blockMinZ, // blockMaxX, // blockMaxY, // blockMaxZ // ).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12), evt.target.sideHit); GL11.glDisable(GL11.GL_TEXTURE_2D); boolean isConstruct = world.getBlockId(evt.target.blockX, evt.target.blockY, evt.target.blockZ) == TFCBlocks.WoodConstruct.blockID; float div = 1f / TileEntityWoodConstruct.PlankDetailLevel; //Get the hit location in local box coords double hitX = Math.round((evt.target.hitVec.xCoord - evt.target.blockX)*100)/100.0d; double hitY = Math.round((evt.target.hitVec.yCoord - evt.target.blockY)*100)/100.0d; double hitZ = Math.round((evt.target.hitVec.zCoord - evt.target.blockZ)*100)/100.0d; //get the targeted sub block coords double subX = (double)((int)((hitX)*8))/8; double subY = (double)((int)((hitY)*8))/8; double subZ = (double)((int)((hitZ)*8))/8; //create the box size double minX = evt.target.blockX + subX; double minY = evt.target.blockY + subY; double minZ = evt.target.blockZ + subZ; double maxX = minX + 0.125; double maxY = minY + 0.125; double maxZ = minZ + 0.125; if(isConstruct && hitY != 0 && hitY != 1 && hitZ != 0 && hitZ != 1 && hitX != 0 && hitX != 1) { if(evt.target.sideHit == 0) { minY = evt.target.blockY; maxY = evt.target.blockY + 1; } else if(evt.target.sideHit == 1) { minY = evt.target.blockY; maxY = evt.target.blockY + 1; } else if(evt.target.sideHit == 2) { minZ = evt.target.blockZ; maxZ = evt.target.blockZ+1; } else if(evt.target.sideHit == 3) { minZ = evt.target.blockZ; maxZ = evt.target.blockZ+1; } else if(evt.target.sideHit == 4) { minX = evt.target.blockX; maxX = evt.target.blockX+1; } else if(evt.target.sideHit == 5) { minX = evt.target.blockX; maxX = evt.target.blockX+1; } } else { if(evt.target.sideHit == 0) { maxY = minY; minY = minY - 1; } else if(evt.target.sideHit == 1) { maxY = minY + 1; } else if(evt.target.sideHit == 2) { maxZ = minZ; minZ = minZ - 1; } else if(evt.target.sideHit == 3) { maxZ = minZ + 1; } else if(evt.target.sideHit == 4) { maxX = minX; minX = minX - 1; } else if(evt.target.sideHit == 5) { maxX = minX + 1; } } //Setup GL for the depthbox GL11.glEnable(GL11.GL_BLEND); //Setup the GL stuff for the outline GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glColor4f(1.0F, 1.0F, 1.0F, 0.4F); GL11.glDisable(GL11.GL_CULL_FACE); GL11.glDepthMask(false); //Draw the mini Box drawBox(AxisAlignedBB.getAABBPool().getAABB(minX,minY,minZ,maxX,maxY,maxZ).expand(0.002F, 0.002F, 0.002F).getOffsetBoundingBox(-var8, -var10, -var12)); GL11.glDepthMask(true); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glDisable(GL11.GL_BLEND); } } void drawFaceUV(AxisAlignedBB par1AxisAlignedBB, int side) { Tessellator var2 = Tessellator.instance; var2.setColorRGBA_F(1, 1, 1, 1); //Top var2.startDrawing(GL11.GL_QUADS); if(side == 0) { var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 0, 0); var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 1, 0); var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 1, 1); var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 0, 1); } else if(side == 1) { var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 0, 0); var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 1, 0); var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 1, 1); var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 0, 1); } else if(side == 2) { var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 0, 0); var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 1, 0); var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 1, 1); var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 0, 1); } else if(side == 3) { var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 0, 0); var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 1, 0); var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 1, 1); var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 0, 1); } else if(side == 4 ) { var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 0, 0); var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 1, 0); var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 1, 1); var2.addVertexWithUV(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 0, 1); } else if( side == 5) { var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ, 0, 0); var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ, 1, 0); var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ, 1, 1); var2.addVertexWithUV(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ, 0, 1); } var2.draw(); } void drawFace(AxisAlignedBB par1AxisAlignedBB) { Tessellator var2 = Tessellator.instance; //Top var2.startDrawing(GL11.GL_QUADS); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.draw(); } void drawBox(AxisAlignedBB par1AxisAlignedBB) { Tessellator var2 = Tessellator.instance; //Top var2.startDrawing(GL11.GL_QUADS); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.draw(); //Bottom var2.startDrawing(GL11.GL_QUADS); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ); var2.draw(); //-x var2.startDrawing(GL11.GL_QUADS); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ); var2.draw(); //+x var2.startDrawing(GL11.GL_QUADS); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ); var2.draw(); //-z var2.startDrawing(GL11.GL_QUADS); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ); var2.draw(); //+z var2.startDrawing(GL11.GL_QUADS); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ); var2.draw(); } void drawOutlinedBoundingBox(AxisAlignedBB par1AxisAlignedBB) { Tessellator var2 = Tessellator.instance; var2.startDrawing(3); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ); var2.draw(); var2.startDrawing(3); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.draw(); var2.startDrawing(GL11.GL_LINES); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.minZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.maxX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.minY, par1AxisAlignedBB.maxZ); var2.addVertex(par1AxisAlignedBB.minX, par1AxisAlignedBB.maxY, par1AxisAlignedBB.maxZ); var2.draw(); } }
Timeslice42/TFCraft
TFC_Shared/src/TFC/Handlers/Client/PlankHighlightHandler.java
Java
gpl-3.0
14,157
<?php global $_MODULE; $_MODULE = array(); $_MODULE['<{blocksearch}prestashop>blocksearch-top_13348442cc6a27032d2b4aa28b75a5d3'] = 'Cerca'; $_MODULE['<{blocksearch}prestashop>blocksearch_31a0c03d7fbd1dc61d3b8e02760e703b'] = 'Blocco ricerca rapida'; $_MODULE['<{blocksearch}prestashop>blocksearch_99e20473c0bf3c22d7420eff03ce66c3'] = 'Aggiunge un blocco con un campo di ricerca rapida'; $_MODULE['<{blocksearch}prestashop>blocksearch_13348442cc6a27032d2b4aa28b75a5d3'] = 'Cerca'; $_MODULE['<{blocksearch}prestashop>blocksearch_52d578d063d6101bbdae388ece037e60'] = 'Inserisci il nome di un prodotto'; $_MODULE['<{blocksearch}prestashop>blocksearch_34d1f91fb2e514b8576fab1a75a89a6b'] = 'Vai';
desarrollosimagos/puroextremo.com.ve
modules/blocksearch_mod/translations/it.php
PHP
gpl-3.0
691
package com.bahram.relationshippoints.logistical.Lifecycle; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.View; /** * Created by bahram on 23.05.2015. */ public abstract class SupportFragmentLifecycle extends Fragment implements LifecycleDataHandling { /** * Called to retrieve per-instance state from an activity before being killed * so that the state can be restored in {@link #onCreate} or * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method * will be passed to both). * <p/> * <p>This method is called before an activity may be killed so that when it * comes back some time in the future it can restore its state. For example, * if activity B is launched in front of activity A, and at some point activity * A is killed to reclaim resources, activity A will have a chance to save the * current state of its user interface via this method so that when the user * returns to activity A, the state of the user interface can be restored * via {@link #onCreate} or {@link #onRestoreInstanceState}. * <p/> * <p>Do not confuse this method with activity lifecycle callbacks such as * {@link #onPause}, which is always called when an activity is being placed * in the background or on its way to destruction, or {@link #onStop} which * is called before destruction. One example of when {@link #onPause} and * {@link #onStop} is called and not this method is when a user navigates back * from activity B to activity A: there is no need to call {@link #onSaveInstanceState} * on B because that particular instance will never be restored, so the * system avoids calling it. An example when {@link #onPause} is called and * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A: * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't * killed during the lifetime of B since the state of the user interface of * A will stay intact. * <p/> * <p>The default implementation takes care of most of the UI per-instance * state for you by calling {@link View#onSaveInstanceState()} on each * view in the hierarchy that has an id, and by saving the id of the currently * focused view (all of which is restored by the default implementation of * {@link #onRestoreInstanceState}). If you override this method to save additional * information not captured by each individual view, you will likely want to * call through to the default implementation, otherwise be prepared to save * all of the state of each view yourself. * <p/> * <p>If called, this method will occur before {@link #onStop}. There are * no guarantees about whether it will occur before or after {@link #onPause}. * * @param outState Bundle in which to place your saved state. * @see #onCreate * @see #onRestoreInstanceState * @see #onPause */ @Override public void onSaveInstanceState(Bundle outState) { saveNecessaryData(outState); storeStateGUI(outState); super.onSaveInstanceState(outState); } }
Mithrandir21/RelationshipPoints
app/src/main/java/com/bahram/relationshippoints/logistical/Lifecycle/SupportFragmentLifecycle.java
Java
gpl-3.0
3,247
<?php /** * * UEA Style report * * This is the report suggested from the team using WebPA at UEA, UK * * * @copyright 2007 Loughborough University * @license http://www.gnu.org/licenses/gpl.txt * @version 0.0.0.1 * @since 8 Aug 2008 * */ require_once("../../../includes/inc_global.php"); require_once(DOC__ROOT . 'includes/classes/class_assessment.php'); require_once(DOC__ROOT . 'includes/classes/class_algorithm_factory.php'); require_once(DOC__ROOT . 'includes/functions/lib_array_functions.php'); if (!check_user($_user, APP__USER_TYPE_TUTOR)){ header('Location:'. APP__WWW .'/logout.php?msg=denied'); exit; } // -------------------------------------------------------------------------------- // Process GET/POST $assessment_id = fetch_GET('a'); $type = fetch_GET('t', 'view'); $tab = fetch_GET('tab'); $year = fetch_GET('y', date('Y')); $marking_date = fetch_GET('md'); // -------------------------------------------------------------------------------- $assessment = new Assessment($DB); if (!$assessment->load($assessment_id)) { $assessment = null; echo(gettext('Error: The requested assessment could not be loaded.')); exit; } else { // ---------------------------------------- // Get the marking parameters used for the marksheet this report will display $marking_params = $assessment->get_marking_params($marking_date); if (!$marking_params) { echo(gettext('Error: The requested marksheet could not be loaded.')); exit; } // ---------------------------------------- // Get the appropriate algorithm and calculate the grades $algorithm = AlgorithmFactory::get_algorithm($marking_params['algorithm']); if (!$algorithm) { echo(gettext('Error: The requested algorithm could not be loaded.')); exit; } else { $algorithm->set_assessment($assessment); $algorithm->set_marking_params($marking_params); $algorithm->calculate(); $group_members = $algorithm->get_group_members(); $member_names = array(); for ($i =0; $i<count($group_members); $i++){ $array_key = array_keys($group_members); $temp = $group_members[$array_key[$i]]; for ($j=0; $j<count($temp);$j++){ array_push($member_names, $CIS->get_user($temp[$j])); } } }// /if-else(is algorithm) }// /if-else(is assessment) // ---------------------------------------- // Get the questions used in this assessment $form = new Form($DB); $form_xml =& $assessment->get_form_xml(); $form->load_from_xml($form_xml); $question_count = (int) $form->get_question_count(); // Create the actual array (question_ids are 0-based) if ($question_count>0) { $questions = range(0, $question_count-1); } else { $questions = array(); } //get the information in the format required $score_array = null; //get the information in the format required //get an array of the group names $group_names = $algorithm->get_group_names(); if ($assessment) { foreach ($group_members as $group_id => $g_members) { $g_member_count = count($group_members[$group_id]); foreach ($questions as $question_id) { $q_index = $question_id+1; $question = $form->get_question($question_id); $q_text = "Q{$q_index} : {$question['text']['_data']}"; foreach ($g_members as $i => $member_id) { $individ = $CIS->get_user($member_id); $mark_recipient = "{$individ['lastname']}, {$individ['forename']}"; foreach ($g_members as $j => $target_member_id) { $individ = $CIS->get_user($target_member_id); $marker = "{$individ['lastname']}, {$individ['forename']}"; if ($assessment->assessment_type == '0') { if ($member_id == $target_member_id) { $score_array[$group_names[$group_id]][$mark_recipient][$q_text][$marker] = 'n/a'; } else { $score_array[$group_names[$group_id]][$mark_recipient][$q_text][$marker] = $algorithm->get_member_response($group_id, $target_member_id, $question_id,$member_id ); } } else { $score_array[$group_names[$group_id]][$mark_recipient][$q_text][$marker] = $algorithm->get_member_response($group_id, $target_member_id, $question_id, $member_id); } if (is_null($score_array[$group_names[$group_id]][$mark_recipient][$q_text][$marker])) { $score_array[$group_names[$group_id]][$mark_recipient][$q_text][$marker] = '-'; } } } } } } /* * -------------------------------------------------------------------------------- * If report type is HTML view * -------------------------------------------------------------------------------- */ if ($type == 'view') { // Begin Page $page_title = ($assessment) ? "{$assessment->name}" : gettext('report'); $UI->page_title = APP__NAME . ' ' . $page_title; $UI->head(); ?> <style type="text/css"> <!-- #side_bar { display: none; } #main { margin: 0px; } table.grid th { padding: 8px; } table.grid td { padding: 8px; text-align: center; } table.grid td.important { background-color: #eec; } --> </style> <?php $UI->body(); $UI->content_start(); ?> <div class="content_box"> <h1 style="font-size: 150%;"><?php echo gettext('Student Responses');?></h1> <table class="grid" cellpadding="2" cellspacing="1"> <tr> <td> <?php //get an array of the group names $group_names = $algorithm->get_group_names(); $teams = array_keys($score_array); foreach ($teams as $i=> $team) { echo "<h2>{$team}</h2>"; $team_members = array_keys($score_array[$team]); foreach ($team_members as $team_member) { echo "<h3>".gettext("Results for:")." {$team_member}</h3>"; $questions = array_keys($score_array[$team][$team_member]); //print_r($questions); echo "<table class='grid' cellpadding='2' cellspacing='1' style='font-size: 0.8em'>"; $q_count = 0; foreach ($questions as $question) { $markers = array_keys($score_array[$team][$team_member][$question]); $markers_row = ''; $scores_row = ''; foreach ($markers as $marker) { $markers_row = $markers_row ."<th>{$marker}</th>"; $score = $score_array[$team][$team_member][$question][$marker]; $scores_row = $scores_row . "<td>{$score}</td>"; } if ($q_count == 0) { echo "<tr><th>&nbsp;</th>"; echo $markers_row; } echo "</tr><tr><th>{$question}</th>"; echo $scores_row; $q_count++; } echo "</tr></table><br/><br/>"; } } ?> </td> </tr> </table> </div> <?php $UI->content_end(false, false, false); } /* * -------------------------------------------------------------------------------- * If report type is download RTF (Rich Text Files) * -------------------------------------------------------------------------------- */ if ($type == 'download-rtf') { header("Content-Disposition: attachment; filename=uea.rtf"); header("Content-Type: text/enriched\n"); $group_names = $algorithm->get_group_names(); $teams = array_keys($score_array); foreach ($teams as $i=> $team) { echo "\n{$team}\n"; $team_members = array_keys($score_array[$team]); foreach ($team_members as $team_member) { echo "\n".gettext("Results for:")." {$team_member}\n"; $questions = array_keys($score_array[$team][$team_member]); $q_count = 0; foreach ($questions as $question) { $markers = array_keys($score_array[$team][$team_member][$question]); $markers_row = ''; $scores_row = ''; foreach ($markers as $marker) { $markers_row = $markers_row ."{$marker}\t"; $score = $score_array[$team][$team_member][$question][$marker]; $scores_row = $scores_row . "{$score}\t"; } if ($q_count == 0) { echo "\n\t"; echo $markers_row ."\t"; } echo "\n{$question}\t"; echo $scores_row . "\n"; $q_count++; } echo "\n"; } } } if ($type == 'download-csv') { header("Content-Disposition: attachment; filename=\"uea_report_style.csv\""); header('Content-Type: text/csv'); $group_names = $algorithm->get_group_names(); $teams = array_keys($score_array); foreach ($teams as $i=> $team) { echo "\n{$team}\n"; $team_members = array_keys($score_array[$team]); foreach ($team_members as $team_member) { echo "\n\"".gettext("Results for:")." {$team_member}\""; $questions = array_keys($score_array[$team][$team_member]); $q_count = 0; foreach ($questions as $question) { $markers = array_keys($score_array[$team][$team_member][$question]); $markers_row = ''; $scores_row = ''; foreach ($markers as $marker) { $markers_row .= APP__SEPARATION."\"{$marker}\""; $score = $score_array[$team][$team_member][$question][$marker]; $scores_row = $scores_row . "\"{$score}\"".APP__SEPARATION; } if ($q_count == 0) { echo "\n"; echo $markers_row; } echo "\n\"{$question}\"".APP__SEPARATION; echo $scores_row; $q_count++; } echo "\n"; } } } ?>
ICTO/WebPA-Source
tutors/assessments/reports/report_uea.php
PHP
gpl-3.0
9,239
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Linq; using System.Drawing; using System.IO; using FeedReader; using FeedReader.Xml.Interfaces; namespace FeedReader.Xml { internal class FeedRdfImageXmlParser : IFeedTypeImageXmlParser { private Image _feedImage; private string _feedImagePath = string.Empty; public Image GetParsedImage() { return _feedImage; } public string GetImagePath() { return _feedImagePath; } public bool TryParseFeedImageUrl(XDocument xmlFeed, string cacheFolder, string feedTitle) { bool returnValue = false; _feedImage = null; _feedImagePath = string.Empty; //1. Try string url = FeedXmlParser.ParseString(xmlFeed.Descendants("channel").Elements("image").Attributes("resource"), "channel/image/attribute[resource]"); returnValue = DownloadAndCheckFeedImageValid(cacheFolder, url, feedTitle); if (returnValue) return true; LogEvents.InvokeOnDebug(new FeedArgs("No feed image could be parsed")); return false; } public bool TryParseFeedItemImageUrl(XDocument xmlFeed, string cacheFolder, string feedTitle, string feedItemTitle, int itemNumber) { XElement item = xmlFeed.Descendants("item").ElementAt(itemNumber); bool returnValue = false; _feedImage = null; _feedImagePath = string.Empty; if (item != null) { //1. Try string url = FeedXmlParser.ParseString(item.Element("item"), "about", "item[" + itemNumber + "]/attribute[about]"); if (Path.GetExtension(url) == ".gif" || Path.GetExtension(url) == ".bmp" || Path.GetExtension(url) == ".jpg" || Path.GetExtension(url) == ".png" || Path.GetExtension(url) == ".jpeg") { returnValue = DownloadAndCheckFeedItemImageValid(cacheFolder, url, feedTitle, feedItemTitle); if (returnValue) return true; } //Last Try LogEvents.InvokeOnDebug(new FeedArgs("Try to get feed item image out of description field...")); string description = FeedXmlParser.ParseString(item.Element("description"), "item[" + itemNumber + "]/description"); url = Utils.GetImageOutOfDescription(Utils.ReplaceHTMLSpecialChars(description)); returnValue = DownloadAndCheckFeedItemImageValid(cacheFolder, url, feedTitle, feedItemTitle); if (returnValue) return true; } LogEvents.InvokeOnDebug(new FeedArgs("No feed item image could be parsed")); return false; } public bool DownloadAndCheckFeedImageValid(string cacheFolder, string url, string feedTitle) { if (Utils.IsValidUrl(ref url)) { LogEvents.InvokeOnDebug(new FeedArgs("Parsed feed image \"" + url + "\" successfull. Downloading image/Load image from cache...")); if (string.IsNullOrEmpty(cacheFolder)) { if (Utils.LoadFeedImage(url, feedTitle, out _feedImage)) return true; } else { if (Utils.LoadFeedImage(url, feedTitle, cacheFolder, out _feedImage, out _feedImagePath)) return true; } } return false; } public bool DownloadAndCheckFeedItemImageValid(string cacheFolder, string url, string feedTitle, string feedItemTitle) { if (Utils.IsValidUrl(ref url)) { LogEvents.InvokeOnDebug(new FeedArgs("Parsed feed item image \"" + url + "\" successfull. Downloading image/Load image from cache...")); if (string.IsNullOrEmpty(cacheFolder)) { if (Utils.LoadFeedItemImage(url, feedTitle, feedItemTitle, out _feedImage)) return true; } else { if (Utils.LoadFeedItemImage(url, feedTitle, feedItemTitle, cacheFolder, out _feedImage, out _feedImagePath)) return true; } } return false; } public bool TryParseFeedImageUrl(XDocument xmlFeed, string feedTitle) { return TryParseFeedImageUrl(xmlFeed, string.Empty, feedTitle); } public bool TryParseFeedItemImageUrl(XDocument xmlFeed, string feedTitle, string feedItemTitle, int itemNumber) { return TryParseFeedItemImageUrl(xmlFeed, string.Empty, feedTitle, feedItemTitle, itemNumber); } } }
hasenbolle/InfoService
InfoService/InfoService/Feeds/FeedReader/Xml/FeedRdfImageXmlParser.cs
C#
gpl-3.0
4,835
<?php /** * New Offer email * * @since 0.1.0 * @package public/includes/emails * @author AngellEYE <andrew@angelleye.com> */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly ?> <?php do_action( 'woocommerce_email_header', $email_heading ); ?> <?php printf( '<p><strong>' . __('New offer submitted on', 'offers-for-woocommerce') . ' %s.</strong><br />' . __('To manage this offer please use the following link:', 'offers-for-woocommerce') . '</p> %s', get_bloginfo( 'name' ), '<a style="background:#EFEFEF; color:#161616; padding:8px 15px; margin:10px; border:1px solid #CCCCCC; text-decoration:none; " href="'. admin_url( 'post.php?post='. $offer_args['offer_id'] .'&action=edit' ) .'"><span style="border-bottom:1px dotted #666; ">' . __( 'Manage Offer', 'offers-for-woocommerce') . '</span></a>' ); ?> <h2><?php echo __( 'Offer ID:', 'offers-for-woocommerce') . ' ' . $offer_args['offer_id']; ?> (<?php printf( '<time datetime="%s">%s</time>', date_i18n( 'c', time() ), date_i18n( wc_date_format(), time() ) ); ?>)</h2> <table cellspacing="0" cellpadding="6" style="width: 100%; border: 1px solid #eee;" border="1" bordercolor="#eee"> <thead> <tr> <th scope="col" style="text-align:left; border: 1px solid #eee;"><?php _e( 'Product', 'woocommerce' ); ?></th> <th scope="col" style="text-align:left; border: 1px solid #eee;"><?php _e( 'Quantity', 'woocommerce' ); ?></th> <th scope="col" style="text-align:left; border: 1px solid #eee;"><?php _e( 'Price', 'woocommerce' ); ?></th> </tr> </thead> <tbody> <tr> <td style="text-align:left; vertical-align:middle; border: 1px solid #eee; padding:12px;"><?php echo stripslashes($offer_args['product_title_formatted']); ?></td> <td style="text-align:left; vertical-align:middle; border: 1px solid #eee; padding:12px;"><?php echo number_format( $offer_args['product_qty'], 0 ); ?></td> <td style="text-align:left; vertical-align:middle; border: 1px solid #eee; padding:12px;"><?php echo get_woocommerce_currency_symbol() . ' ' . number_format( $offer_args['product_price_per'], 2 ); ?></td> </tr> </tbody> <tfoot> <tr> <th scope="row" colspan="2" style="text-align:left; border: 1px solid #eee; border-top-width: 4px; "><?php _e( 'Subtotal', 'woocommerce' ); ?></th> <td style="text-align:left; border: 1px solid #eee; border-top-width: 4px; "><?php echo get_woocommerce_currency_symbol() . ' ' . number_format( $offer_args['product_total'], 2 ); ?></td> </tr> </tfoot> </table> <h4><?php echo __('Offer Contact Details:', 'offers-for-woocommerce'); ?></h4> <?php echo (isset($offer_args['offer_name']) && $offer_args['offer_name'] != '') ? '<strong>' . __('Name:', 'offers-for-woocommerce') . '&nbsp;</strong>'.stripslashes($offer_args['offer_name']) : ''; ?> <?php echo (isset($offer_args['offer_company_name']) && $offer_args['offer_company_name'] != '') ? '<br /><strong>' . __('Company Name:', 'offers-for-woocommerce') . '&nbsp;</strong>'.stripslashes($offer_args['offer_company_name']) : ''; ?> <?php echo (isset($offer_args['offer_email']) && $offer_args['offer_email'] != '') ? '<br /><strong>' . __('Email:', 'offers-for-woocommerce') . '&nbsp;</strong>'.stripslashes($offer_args['offer_email']) : ''; ?> <?php echo (isset($offer_args['offer_phone']) && $offer_args['offer_phone'] != '') ? '<br /><strong>' . __('Phone:', 'offers-for-woocommerce') . '&nbsp;</strong>'.stripslashes($offer_args['offer_phone']) : ''; ?> <?php if(isset($offer_args['offer_notes']) && $offer_args['offer_notes'] != '') { echo '<h4>'. __( 'Offer Notes:', 'offers-for-woocommerce' ) .'</h4>'. stripslashes($offer_args['offer_notes']); } ?> <?php do_action( 'woocommerce_email_footer' ); ?>
wp-plugins/offers-for-woocommerce
public/includes/emails/woocommerce-new-offer.php
PHP
gpl-3.0
3,810
using System.Diagnostics; using System.Security.Claims; using System.Security.Principal; namespace DotnetSpider.Portal.Common { /// <summary> /// Extension methods for <see cref="System.Security.Principal.IPrincipal"/> and <see cref="System.Security.Principal.IIdentity"/> . /// </summary> public static class PrincipalExtensions { /// <summary> /// Gets the name. /// </summary> /// <param name="principal">The principal.</param> /// <returns></returns> [DebuggerStepThrough] public static string GetDisplayName(this ClaimsPrincipal principal) { var name = principal.Identity.Name; if (!string.IsNullOrWhiteSpace(name)) return name; var sub = principal.FindFirst("sub"); if (sub != null) return sub.Value; return string.Empty; } /// <summary> /// Determines whether this instance is authenticated. /// </summary> /// <param name="principal">The principal.</param> /// <returns> /// <c>true</c> if the specified principal is authenticated; otherwise, <c>false</c>. /// </returns> [DebuggerStepThrough] public static bool IsAuthenticated(this IPrincipal principal) { return principal != null && principal.Identity != null && principal.Identity.IsAuthenticated; } } }
zlzforever/DotnetSpider
src/DotnetSpider.Portal/Common/PrincipalExtensions.cs
C#
gpl-3.0
1,235
<p class="quote"><?php echo $quote->quoteText; ?></p> <p class="author">-<?php echo $quote->quoteAuthor; ?></p>
Hammercake/pi-kiosk-alarm
modules/quote/view.php
PHP
gpl-3.0
111
#!/usr/bin/env python3 # # Copyright (C) 2016 Canonical, Ltd. # Author: Scott Sweeny <scott.sweeny@canonical.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import os class Rule: def __init__(self, path): # Make sure path ends in a separator to make things easier self.path = os.path.join(path, '') def get_file_list(self): '''Return a list of files in the snap''' file_list = [] for root, dirs, files in os.walk(self.path): for f in files: file_list.append(os.path.relpath(os.path.join(root, f), self.path)) return file_list def get_dir_list(self): '''Return a list of directories in the snap''' dir_list = [] for root, dirs, files in os.walk(self.path): for d in dirs: dir_list.append(os.path.relpath(os.path.join(root, d), self.path)) return dir_list def scan(self): '''Override this method to implement your rule checking logic''' pass
ssweeny/snaplint
snaplint/_rule.py
Python
gpl-3.0
1,643
using System.Runtime.InteropServices; using System.Diagnostics; using System; using System.Security; namespace System.Threading { [ComVisibleAttribute(false)] [DebuggerDisplayAttribute("Participant Count={ParticipantCount},Participants Remaining={ParticipantsRemaining}")] public class Barrier : IDisposable { public int ParticipantsRemaining { get { throw new NotImplementedException(); } } public int ParticipantCount { get { throw new NotImplementedException(); } } public long CurrentPhaseNumber { get { throw new NotImplementedException(); } } public Barrier(int participantCount) { throw new NotImplementedException(); } public Barrier(int participantCount, Action<Barrier> postPhaseAction) { throw new NotImplementedException(); } public long AddParticipant() { throw new NotImplementedException(); } public long AddParticipants(int participantCount) { throw new NotImplementedException(); } public void RemoveParticipant() { throw new NotImplementedException(); } public void RemoveParticipants(int participantCount) { throw new NotImplementedException(); } public void SignalAndWait() { throw new NotImplementedException(); } public void SignalAndWait(CancellationToken cancellationToken) { throw new NotImplementedException(); } public bool SignalAndWait(TimeSpan timeout) { throw new NotImplementedException(); } public bool SignalAndWait(TimeSpan timeout, CancellationToken cancellationToken) { throw new NotImplementedException(); } public bool SignalAndWait(int millisecondsTimeout) { throw new NotImplementedException(); } public bool SignalAndWait(int millisecondsTimeout, CancellationToken cancellationToken) { throw new NotImplementedException(); } public void Dispose() { throw new NotImplementedException(); } protected virtual void Dispose(bool disposing) { throw new NotImplementedException(); } } }
zebraxxl/CIL2Java
StdLibs/System/System/Threading/Barrier.cs
C#
gpl-3.0
2,746
// Copyright (c) Clickberry, Inc. All rights reserved. // Licensed under the GNU GENERAL PUBLIC LICENSE Version 3. See License.txt in the project root for license information. define("datacontext", ["jquery"], function($) { return function(resourceUri) { if (!resourceUri) { throw Error("Invalid resource uri."); } function getUri(uri, id) { return id ? uri + "/" + id : uri; } this.post = function(requestData) { return $.Deferred(function(deferred) { $.ajax({ type: 'POST', url: getUri(resourceUri), data: requestData, error: function(responseData) { deferred.reject(responseData); }, success: function(responseData) { deferred.resolve(responseData); } }); }).promise(); }; this.get = function(id) { return $.Deferred(function(deferred) { $.ajax({ url: getUri(resourceUri, id), dataType: 'json', error: function(responseData) { deferred.reject(responseData); }, success: function(responseData) { deferred.resolve(responseData); } }); }).promise(); }; this.put = function(id, requestData) { return $.Deferred(function(deferred) { $.ajax({ type: 'POST', url: getUri(resourceUri, id), data: requestData, headers: { 'X-HTTP-Method-Override': "PUT" }, error: function(responseData) { deferred.reject(responseData); }, success: function(responseData) { deferred.resolve(responseData); } }); }).promise(); }; this.remove = function(id, requestData) { return $.Deferred(function(deferred) { $.ajax({ type: 'POST', url: getUri(resourceUri, id), data: requestData, headers: { 'X-HTTP-Method-Override': "DELETE" }, error: function(responseData) { deferred.reject(responseData); }, success: function(responseData) { deferred.resolve(responseData); } }); }).promise(); }; }; });
clickberry/video-portal
Source/FrontEnd/Portal.Web/Cdn/js/spa/datacontext.js
JavaScript
gpl-3.0
2,802
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * Copyright (C) 2012-2015 Marco Craveiro <marco.craveiro@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * */ #include <string> #include <ostream> #include <stdexcept> #include "masd.dogen.extraction/io/editors_io.hpp" namespace masd::dogen::extraction { std::ostream& operator<<(std::ostream& s, const editors& v) { s << "{ " << "\"__type__\": " << "\"editors\", " << "\"value\": "; std::string attr; switch (v) { case editors::invalid: attr = "\"invalid\""; break; case editors::emacs: attr = "\"emacs\""; break; case editors::vi: attr = "\"vi\""; break; case editors::vim: attr = "\"vim\""; break; case editors::ex: attr = "\"ex\""; break; default: throw std::invalid_argument("Invalid value for editors"); } s << attr << " }"; return s; } }
DomainDrivenConsulting/dogen
projects/masd.dogen.extraction/src/io/editors_io.cpp
C++
gpl-3.0
1,654
<?php /** * Kunena Component * @package Kunena.Template.Crypsis * @subpackage Layout.User * * @copyright (C) 2008 - 2015 Kunena Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @link http://www.kunena.org **/ defined('_JEXEC') or die; ?> <h2> <?php echo JText::_('COM_KUNENA_USER_PROFILE'); ?> <?php echo $this->escape($this->profile->getName()); ?> <?php echo $this->profile->getLink( '<i class="glyphicon glyphicon-arrow-left"></i> ' . JText::_('COM_KUNENA_BACK'), JText::_('COM_KUNENA_BACK'), 'nofollow', '', 'btn pull-right' ); ?> </h2> <form action="<?php echo KunenaRoute::_('index.php?option=com_kunena&view=user'); ?>" method="post" enctype="multipart/form-data" name="kuserform" class="form-validate" id="kuserform"> <input type="hidden" name="task" value="save" /> <input type="hidden" name="userid" value="<?php echo (int) $this->user->id; ?>" /> <?php echo JHtml::_('form.token'); ?> <div class="tabs"> <ul id="KunenaUserEdit" class="nav nav-tabs"> <li class="active"> <a href="#home" data-toggle="tab"> <?php echo JText::_('COM_KUNENA_PROFILE_EDIT_USER'); ?> </a> </li> <li> <a href="#editprofile" data-toggle="tab"> <?php echo JText::_('COM_KUNENA_PROFILE_EDIT_PROFILE'); ?> </a> </li> <li> <a href="#editavatar" data-toggle="tab"> <?php echo JText::_('COM_KUNENA_PROFILE_EDIT_AVATAR'); ?> </a> </li> <li> <a href="#editsettings" data-toggle="tab"> <?php echo JText::_('COM_KUNENA_PROFILE_EDIT_SETTINGS'); ?> </a> </li> </ul> <div id="KunenaUserEdit" class="tab-content"> <div class="tab-pane fade in active" id="home"> <?php echo $this->subRequest('User/Edit/User'); ?> </div> <div class="tab-pane fade" id="editprofile"> <?php echo $this->subRequest('User/Edit/Profile'); ?> </div> <div class="tab-pane fade" id="editavatar"> <?php echo $this->subRequest('User/Edit/Avatar'); ?> </div> <div class="tab-pane fade" id="editsettings"> <?php echo $this->subRequest('User/Edit/Settings'); ?> </div> <br /> <div class="center"> <button class="btn btn-primary validate" type="submit"> <?php echo JText::_('COM_KUNENA_SAVE'); ?> </button> <input type="button" name="cancel" class="btn" value="<?php echo (' ' . JText::_('COM_KUNENA_CANCEL') . ' '); ?>" onclick="window.history.back();" title="<?php echo (JText::_('COM_KUNENA_EDITOR_HELPLINE_CANCEL')); ?>" /> </div> </div> </div> </form>
OSTraining/Kunena-Forum
components/com_kunena/site/template/crypsisb3/layouts/user/edit/default.php
PHP
gpl-3.0
2,560
#pragma once /* This file is part of Imagine. Imagine 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. Imagine 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 Imagine. If not, see <http://www.gnu.org/licenses/> */ #include <type_traits> #include <imagine/io/IO.hh> #include <imagine/io/PosixFileIO.hh> using FileIO = PosixFileIO; #ifdef __ANDROID__ #include <imagine/io/AAssetIO.hh> using AssetIO = AAssetIO; #else using AssetIO = FileIO; #endif namespace FileUtils { AssetIO openAppAsset(const char *name, IO::AccessHint access, const char *appName); ssize_t writeToPath(const char *path, void *data, size_t size, std::error_code *ecOut = nullptr); ssize_t writeToPath(const char *path, IO &io, std::error_code *ecOut = nullptr); ssize_t readFromPath(const char *path, void *data, size_t size); }
DarkCaster/emu-ex-plus-alpha
imagine/include/imagine/io/FileIO.hh
C++
gpl-3.0
1,248
ModX Revolution 2.5.0 = 539f52dd202abe6bff3cf711e1c09993 MODX Revolution 2.2.8 = 93c2ffd8a497f42474f7b4a3e49503ca
gohdan/DFC
known_files/hashes/core/lexicon/de/filters.inc.php
PHP
gpl-3.0
114
package org.halvors.nuclearphysics.common.event.handler; import net.minecraft.entity.item.EntityItem; import net.minecraft.item.ItemStack; import net.minecraftforge.event.entity.item.ItemExpireEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import org.halvors.nuclearphysics.common.ConfigurationManager.General; import org.halvors.nuclearphysics.common.effect.explosion.AntimatterExplosion; import org.halvors.nuclearphysics.common.init.ModItems; @EventBusSubscriber public class ItemEventHandler { @SubscribeEvent public static void onItemExpireEvent(final ItemExpireEvent event) { if (General.enableAntimatterPower) { final EntityItem entityItem = event.getEntityItem(); if (entityItem != null) { final ItemStack itemStack = entityItem.getEntityItem(); if (itemStack.getItem() == ModItems.itemAntimatterCell) { final AntimatterExplosion explosion = new AntimatterExplosion(entityItem.getEntityWorld(), entityItem, entityItem.getPosition(), 4, itemStack.getMetadata()); explosion.explode(); } } } } }
halvors/Nuclear-Physics
src/main/java/org/halvors/nuclearphysics/common/event/handler/ItemEventHandler.java
Java
gpl-3.0
1,244
package com.jeewd.web_store.security; import java.util.Collection; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; public class User implements UserDetails { private static final long serialVersionUID = -3849758589040177326L; private boolean accountNonExpired; private boolean accountNonLocked; private boolean credentialsNonExpired; private boolean enabled; private String username; private String password; private Collection<GrantedAuthority> authorities; public User(String username, String password, Collection<GrantedAuthority> authorities) { this.enabled = true; this.accountNonExpired = true; this.credentialsNonExpired = true; this.accountNonLocked = true; this.username = username; this.password = password; this.authorities = authorities; } public void setAccountNonExpired(boolean accountNonExpired) { this.accountNonExpired = accountNonExpired; } public void setAccountNonLocked(boolean accountNonLocked) { this.accountNonLocked = accountNonLocked; } public void setCredentialsNonExpired(boolean credentialsNonExpired) { this.credentialsNonExpired = credentialsNonExpired; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setUsername(String username) { this.username = username; } public void setPassword(String password) { this.password = password; } public void setAuthorities(Collection<GrantedAuthority> authorities) { this.authorities = authorities; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return accountNonExpired; } @Override public boolean isAccountNonLocked() { return accountNonLocked; } @Override public boolean isCredentialsNonExpired() { return credentialsNonExpired; } @Override public boolean isEnabled() { return enabled; } }
slavidlancer/JavaEEWebDevelopment
11_CourseProject_Java_Web_Development/CourseProjectWebStore/src/main/java/com/jeewd/web_store/security/User.java
Java
gpl-3.0
2,377
# -*- coding: utf-8 -*- import numpy as np import config from feature.feature_multi import FeatureMulti from similarity.similarity_base import SimiliarityBase class SimilarityStyle(SimiliarityBase): def calculate(self, image1, image2): # 获取特征 multi_feature_extractor = FeatureMulti() luminance_sample_p, mu_p, sigma_p = multi_feature_extractor.extract(image1) luminance_sample_s, mu_s, sigma_s = multi_feature_extractor.extract(image2) # 实际相似度计算 return self.__class__.calculate_inner(luminance_sample_p, luminance_sample_s, mu_p, mu_s, sigma_p, sigma_s) @classmethod def calculate_inner(cls, luminance_sample_p, luminance_sample_s, mu_p, mu_s, sigma_p, sigma_s): # 参数 lambda_l = config.style_ranking['lambda_l'] lambda_c = config.style_ranking['lambda_c'] epsilon = config.style_ranking['epsilon'] # 求亮度之间的欧式距离 de = np.power(np.linalg.norm(luminance_sample_p - luminance_sample_s, 2), 2) # 求色彩之间的距离 mu = np.matrix(np.abs(mu_p - mu_s) + epsilon).T sigma = np.matrix((sigma_p + sigma_s) / 2) dh_1 = np.power(np.linalg.norm(sigma_s.dot(sigma_p), 1), 1 / 4) / (np.power(np.linalg.norm(sigma, 1), 1 / 2)) dh_2 = (-1 / 8) * mu.T * np.linalg.inv(sigma) * mu dh = 1 - dh_1 * np.exp(dh_2) ans = np.exp(-de / lambda_l) * np.exp(-np.power(dh, 2) / lambda_c) # 因为ans是一个 1x1 Matrix,所以必须弄成一个值 return np.max(ans)
jinyu121/ACACTS
similarity/similarity_style.py
Python
gpl-3.0
1,581
// ***************************************************************************** // randpool.cpp Tao3D project // ***************************************************************************** // // File description: // // // // // // // // // ***************************************************************************** // This software is licensed under the GNU General Public License v3 // (C) 2019, Christophe de Dinechin <christophe@dinechin.org> // (C) 2011, Jérôme Forissier <jerome@taodyne.com> // ***************************************************************************** // This file is part of Tao3D // // Tao3D is free software: you can r 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. // // Tao3D 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 Tao3D, in a file named COPYING. // If not, see <https://www.gnu.org/licenses/>. // ***************************************************************************** // randpool.cpp - written and placed in the public domain by Wei Dai // RandomPool used to follow the design of randpool in PGP 2.6.x, // but as of version 5.5 it has been redesigned to reduce the risk // of reusing random numbers after state rollback (which may occur // when running in a virtual machine like VMware). #include "pch.h" #ifndef CRYPTOPP_IMPORTS #include "randpool.h" #include "aes.h" #include "sha.h" #include "hrtimer.h" #include <time.h> NAMESPACE_BEGIN(CryptoPP) RandomPool::RandomPool() : m_pCipher(new AES::Encryption), m_keySet(false) { memset(m_key, 0, m_key.SizeInBytes()); memset(m_seed, 0, m_seed.SizeInBytes()); } void RandomPool::IncorporateEntropy(const byte *input, size_t length) { SHA256 hash; hash.Update(m_key, 32); hash.Update(input, length); hash.Final(m_key); m_keySet = false; } void RandomPool::GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword size) { if (size > 0) { if (!m_keySet) m_pCipher->SetKey(m_key, 32); Timer timer; TimerWord tw = timer.GetCurrentTimerValue(); CRYPTOPP_COMPILE_ASSERT(sizeof(tw) <= 16); *(TimerWord *)m_seed.data() += tw; time_t t = time(NULL); CRYPTOPP_COMPILE_ASSERT(sizeof(t) <= 8); *(time_t *)(m_seed.data()+8) += t; do { m_pCipher->ProcessBlock(m_seed); size_t len = UnsignedMin(16, size); target.ChannelPut(channel, m_seed, len); size -= len; } while (size > 0); } } NAMESPACE_END #endif
c3d/tao-3D
libcryptopp/cryptopp/randpool.cpp
C++
gpl-3.0
2,879
#!/usr/bin/env python3 """ Copyright 2020 Paul Willworth <ioscode@gmail.com> This file is part of Galaxy Harvester. Galaxy Harvester is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Galaxy Harvester 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 Galaxy Harvester. If not, see <http://www.gnu.org/licenses/>. """ import os import sys import dbSession import pymysql import cgi from http import cookies import ghShared import ghLists import dbShared # form = cgi.FieldStorage() C = cookies.SimpleCookie() errorstr = '' try: C.load(os.environ['HTTP_COOKIE']) except KeyError: errorstr = 'no cookies\n' if errorstr == '': try: currentUser = C['userID'].value except KeyError: currentUser = '' try: sid = C['gh_sid'].value except KeyError: sid = form.getfirst('gh_sid', '') else: currentUser = '' sid = form.getfirst('gh_sid', '') # Get a session logged_state = 0 sess = dbSession.getSession(sid) if (sess != ''): logged_state = 1 currentUser = sess groupType = form.getfirst('groupType', '') profession = form.getfirst('profession', '') craftingTab = form.getfirst('craftingTab', '') resType = form.getfirst('resType', '') resSecondary = form.getfirst('resSecondary', '') resGroup = form.getfirst('resGroup', '') selectSchematic = form.getfirst('selectSchematic', '') listFormat = form.getfirst('listFormat', 'list') galaxy = form.getfirst('galaxy', '') # escape input to prevent sql injection groupType = dbShared.dbInsertSafe(groupType) profession = dbShared.dbInsertSafe(profession) craftingTab = dbShared.dbInsertSafe(craftingTab) resType = dbShared.dbInsertSafe(resType) resSecondary = dbShared.dbInsertSafe(resSecondary) resGroup = dbShared.dbInsertSafe(resGroup) selectSchematic = dbShared.dbInsertSafe(selectSchematic) listFormat = dbShared.dbInsertSafe(listFormat) # groupType determines the filtering method for narrowing down schematic list filterStr = '' joinStr = '' if (groupType == 'prof'): if (profession.isdigit()): filterStr = ' WHERE tSkillGroup.profID = ' + str(profession) elif (groupType == 'tab'): if (craftingTab.isdigit()): filterStr = ' WHERE tSchematic.craftingTab = ' + str(craftingTab) elif (groupType == 'res'): if (resGroup != '' and resGroup != None): if resSecondary == '1': joinStr = ' INNER JOIN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup="' + resGroup + '") rtg ON ingredientObject = rtg.resourceType' else: filterStr = ' WHERE ingredientObject = "' + resGroup + '"' else: if resSecondary == '1': filterStr = ' WHERE ingredientObject IN (SELECT tResourceTypeGroup.resourceGroup FROM tResourceTypeGroup INNER JOIN tResourceGroup ON tResourceTypeGroup.resourceGroup=tResourceGroup.resourceGroup WHERE resourceType="' + resType + '" AND groupLevel=(SELECT Max(rg.groupLevel) FROM tResourceTypeGroup rtg INNER JOIN tResourceGroup rg ON rtg.resourceGroup = rg.resourceGroup WHERE rtg.resourceType="' + resType + '") GROUP BY tResourceTypeGroup.resourceGroup)' joinStr = ' INNER JOIN (SELECT tResourceTypeGroup.resourceGroup FROM tResourceTypeGroup INNER JOIN tResourceGroup ON tResourceTypeGroup.resourceGroup=tResourceGroup.resourceGroup WHERE resourceType="' + resType + '" AND groupLevel=(SELECT Max(rg.groupLevel) FROM tResourceTypeGroup rtg INNER JOIN tResourceGroup rg ON rtg.resourceGroup = rg.resourceGroup WHERE rtg.resourceType="' + resType + '") GROUP BY tResourceTypeGroup.resourceGroup) rtgg ON ingredientObject = rtgg.resourceGroup' else: filterStr = ' WHERE ingredientObject = "' + resType + '"' elif (groupType == 'favorite'): filterStr = ' WHERE tFavorites.userID = "' + currentUser + '" AND favType = 4' joinStr = ' INNER JOIN tFavorites ON tSchematic.schematicID = tFavorites.favGroup' conn = dbShared.ghConn() # Some schematics are custom entered per galaxy but those with galaxyID 0 are for all if galaxy.isdigit(): baseProfs = '0, 1337' checkCursor = conn.cursor() if (checkCursor): checkCursor.execute('SELECT galaxyNGE FROM tGalaxy WHERE galaxyID={0};'.format(str(galaxy))) checkRow = checkCursor.fetchone() if (checkRow != None) and (checkRow[0] > 0): baseProfs = '-1, 1337' checkCursor.close() filterStr = filterStr + ' AND tSchematic.galaxy IN ({1}, {0}) AND tSchematic.schematicID NOT IN (SELECT schematicID FROM tSchematicOverrides WHERE galaxyID={0})'.format(galaxy, baseProfs) # We output an unordered list or a bunch of select element options depending on listFormat currentGroup = '' currentIngredient = '' print('Content-type: text/html\n') if listFormat != 'option': print(' <ul class="schematics">') cursor = conn.cursor() if (cursor): if (groupType == 'tab' or groupType == 'favorite'): sqlStr1 = 'SELECT schematicID, tSchematic.craftingTab, typeName, schematicName FROM tSchematic INNER JOIN tObjectType ON tSchematic.objectType = tObjectType.objectType' + joinStr + filterStr + ' ORDER BY craftingTab, typeName, schematicName' elif (groupType == 'res'): sqlStr1 = 'SELECT DISTINCT tSchematic.schematicID, tSchematic.craftingTab, typeName, schematicName, ingredientObject, res.resName FROM tSchematic INNER JOIN tObjectType ON tSchematic.objectType = tObjectType.objectType INNER JOIN tSchematicIngredients ON tSchematic.schematicID = tSchematicIngredients.schematicID' + joinStr + ' LEFT JOIN (SELECT resourceGroup AS resID, groupName AS resName FROM tResourceGroup UNION ALL SELECT resourceType, resourceTypeName FROM tResourceType) res ON ingredientObject = res.resID' + filterStr + ' ORDER BY res.resName, craftingTab, typeName, schematicName' else: sqlStr1 = 'SELECT schematicID, profName, skillGroupName, schematicName FROM tSchematic INNER JOIN tSkillGroup ON tSchematic.skillGroup = tSkillGroup.skillGroup LEFT JOIN tProfession ON tSkillGroup.profID = tProfession.profID' + joinStr + filterStr if listFormat == 'option': sqlStr1 += ' ORDER BY schematicName' else: sqlStr1 += ' ORDER BY profName, skillGroupName, schematicName' cursor.execute(sqlStr1) row = cursor.fetchone() if (row == None): print(' <li><h3>No Schematics Found</h3></li>') while (row != None): if listFormat == 'option': print('<option value="' + row[0] + '">' + row[3] + '</option>') else: if (groupType == 'res'): if (currentIngredient != row[5]): print(' </ul>') print(' <div style="margin-top:14px;"><a class="bigLink" href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + str(row[4]) + '">' + str(row[5]) + '</a></div>') print(' <ul class="schematics">') currentIngredient = row[5] currentGroup = '' if (currentGroup != row[2]): print(' <li><h3>' + row[2] + '</h3></li>') currentGroup = row[2] if row[0] == selectSchematic: print(' <li class="listSelected"><a href="' + ghShared.BASE_SCRIPT_URL + 'schematics.py/' + row[0] + '">' + row[3] + '</a></li>') else: print(' <li><a href="' + ghShared.BASE_SCRIPT_URL + 'schematics.py/' + row[0] + '">' + row[3] + '</a></li>') row = cursor.fetchone() cursor.close() conn.close() if listFormat != 'option': print(' </ul>')
pwillworth/galaxyharvester
html/getSchematicList.py
Python
gpl-3.0
7,494
#include "mounter.h" #include "manager.h" #include <iostream> #include <QStringList> #include <QDir> #include <QDebug> #include <QQueue> class MounterItem { public: MounterItem( const QString & f , const QString & m ) { file = f ; mount_point = m; } QString file; QString mount_point; }; class MounterPrivate { public: QProcess *process; QString command; QQueue<MounterItem> queue; }; Mounter::Mounter(QObject *parent) : QObject(parent) { p = new MounterPrivate; p->process = new QProcess( this ); p->command = "mount"; connect( p->process , SIGNAL(finished(int,QProcess::ExitStatus)) , SLOT(finished(int,QProcess::ExitStatus)) , Qt::QueuedConnection ); } void Mounter::mount( const QString & file , const QString & mount_point ) { p->queue.enqueue( MounterItem( file , mount_point ) ); if( p->queue.count() == 1 ) mount_prev( file , mount_point ); Manager::increase(); } void Mounter::mount_prev( const QString & file , const QString & mount_point ) { QDir dir( mount_point ); dir.mkpath( mount_point ); QStringList arguments; arguments << "-o"; arguments << "loop"; arguments << file; arguments << mount_point; p->process->start( p->command , arguments ); } void Mounter::finished( int exit_code , QProcess::ExitStatus state ) { p->queue.dequeue(); if( !p->queue.isEmpty() ) { const MounterItem & item = p->queue.dequeue(); mount_prev( item.file , item.mount_point ); } if( state == QProcess::CrashExit ) { qDebug() << "The mount process has unexpectedly finished."; Manager::decrease(); return; } if( exit_code == 0 ) { Manager::decrease(); return; } if( exit_code & 1 ) qDebug() << "Incorrect invocation or permissions."; if( exit_code & 2 ) qDebug() << "System error (out of memory, cannot fork, no more loop devices)."; if( exit_code & 4 ) qDebug() << "Internal mount bug."; if( exit_code & 8 ) qDebug() << "User interrupt."; if( exit_code & 16 ) qDebug() << "Problems writing or locking /etc/mtab ."; if( exit_code & 32 ) qDebug() << "Mount failure."; if( exit_code & 64 ) qDebug() << "Some mount succeeded."; Manager::decrease(); } Mounter::~Mounter() { delete p; }
realbardia/silicon
SPlugins/RootMount/Binary/mounter.cpp
C++
gpl-3.0
2,378
/*---------------------------------------------------------------------------*\ * interactive networked Virtual Reality system (inVRs) * * * * Copyright (C) 2005-2009 by the Johannes Kepler University, Linz * * * * www.inVRs.org * * * * contact: canthes@inVRs.org, rlander@inVRs.org * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * \*---------------------------------------------------------------------------*/ #include "AllInOneTranslationModel.h" #include <inVRs/SystemCore/ArgumentVector.h> #include <inVRs/SystemCore/DebugOutput.h> AllInOneTranslationModel::AllInOneTranslationModel(unsigned upDownIdx, unsigned speedIdx, float forBackSpeed, float upDownSpeed) { this->upDownIdx = upDownIdx; this->speedIdx = speedIdx; this->upDownSpeed = upDownSpeed; this->forBackSpeed = forBackSpeed; } void AllInOneTranslationModel::getTranslation(ControllerInterface* controller, const gmtl::Quatf& rotationChange, gmtl::Vec3f& result, float dt) { gmtl::Vec3f temp; gmtl::Vec3f frontBackDir = gmtl::Vec3f(0, 0, 1); gmtl::Vec3f upDownDir = gmtl::Vec3f(0, 1, 0); result = gmtl::Vec3f(0, 0, 0); if(controller->getNumberOfAxes() <= (int)speedIdx) return; result += frontBackDir*controller->getAxisValue(speedIdx)*forBackSpeed; if(controller->getNumberOfAxes() <= (int)upDownIdx) return; result += upDownDir*controller->getAxisValue(upDownIdx)*upDownSpeed; } AllInOneTranslationModelFactory::~AllInOneTranslationModelFactory() { } TranslationModel* AllInOneTranslationModelFactory::create( std::string className, ArgumentVector* args) { if (className != "AllInOneTranslationModel") { return NULL; } unsigned upDownIdx = 0; unsigned speedIdx = 1; float upDownSpeed = 1; float forBackSpeed = 1; if (args && args->keyExists("upDownIdx")) args->get("upDownIdx", upDownIdx); else printd(WARNING, "AllInOneTranslationModelFactory::create(): WARNING: missing attribute upDownIdx, assuming default!\n"); if (args && args->keyExists("speedIdx")) args->get("speedIdx", speedIdx); else printd(WARNING, "AllInOneTranslationModelFactory::create(): WARNING: missing attribute speedIdx, assuming default!\n"); if (args && args->keyExists("upDownSpeed")) args->get("upDownSpeed", upDownSpeed); else printd(WARNING, "AllInOneTranslationModelFactory::create(): WARNING: missing attribute upDownSpeed, assuming default!\n"); if (args && args->keyExists("forBackSpeed")) args->get("forBackSpeed", forBackSpeed); else printd(WARNING, "AllInOneTranslationModelFactory::create(): WARNING: missing attribute forBackSpeed, assuming default!\n"); return new AllInOneTranslationModel(upDownIdx, speedIdx, forBackSpeed, upDownSpeed); }
jzarl/inVRs
src/inVRs/Modules/Navigation/AllInOneTranslationModel.cpp
C++
gpl-3.0
4,248
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- """ @file outTemp.py @brief ModuleDescription @date $Date$ """ import sys import time sys.path.append(".") # Import RTM module import RTC import OpenRTM_aist # Import Service implementation class # <rtc-template block="service_impl"> # </rtc-template> # Import Service stub modules # <rtc-template block="consumer_import"> # </rtc-template> # This module's spesification # <rtc-template block="module_spec"> outtemp_spec = ["implementation_id", "outTemp", "type_name", "outTemp", "description", "ModuleDescription", "version", "1.0.0", "vendor", "VenderName", "category", "Category", "activity_type", "STATIC", "max_instance", "1", "language", "Python", "lang_type", "SCRIPT", ""] # </rtc-template> ## # @class outTemp # @brief ModuleDescription # # get original temperature and output by celius. # # class outTemp(OpenRTM_aist.DataFlowComponentBase): ## # @brief constructor # @param manager Maneger Object # def __init__(self, manager): OpenRTM_aist.DataFlowComponentBase.__init__(self, manager) origin_Temp_arg = [None] * ((len(RTC._d_TimedDouble) - 4) / 2) self._d_origin_Temp = RTC.TimedDouble(*origin_Temp_arg) """ """ self._origin_TempIn = OpenRTM_aist.InPort("origin_Temp", self._d_origin_Temp,OpenRTM_aist.RingBuffer(1)) # initialize of configuration-data. # <rtc-template block="init_conf_param"> # </rtc-template> ## # # The initialize action (on CREATED->ALIVE transition) # formaer rtc_init_entry() # # @return RTC::ReturnCode_t # # def onInitialize(self): # Bind variables and configuration variabl print "onInitialize" print # Set InPort buffers self.addInPort("origin_Temp",self._origin_TempIn) # Set OutPort buffers # Set service provider to Ports # Set service consumers to Ports # Set CORBA Service Ports return RTC.RTC_OK # ## # # # # The finalize action (on ALIVE->END transition) # # formaer rtc_exiting_entry() # # # # @return RTC::ReturnCode_t # # # #def onFinalize(self): # # return RTC.RTC_OK # ## # # # # The startup action when ExecutionContext startup # # former rtc_starting_entry() # # # # @param ec_id target ExecutionContext Id # # # # @return RTC::ReturnCode_t # # # # #def onStartup(self, ec_id): # # return RTC.RTC_OK # ## # # # # The shutdown action when ExecutionContext stop # # former rtc_stopping_entry() # # # # @param ec_id target ExecutionContext Id # # # # @return RTC::ReturnCode_t # # # # #def onShutdown(self, ec_id): # # return RTC.RTC_OK # ## # # # # The activated action (Active state entry action) # # former rtc_active_entry() # # # # @param ec_id target ExecutionContext Id # # # # @return RTC::ReturnCode_t # # # # #def onActivated(self, ec_id): # # return RTC.RTC_OK # ## # # # # The deactivated action (Active state exit action) # # former rtc_active_exit() # # # # @param ec_id target ExecutionContext Id # # # # @return RTC::ReturnCode_t # # # # #def onDeactivated(self, ec_id): # # return RTC.RTC_OK ## # # The execution action that is invoked periodically # former rtc_active_do() # # @param ec_id target ExecutionContext Id # # @return RTC::ReturnCode_t # # def onExecute(self, ec_id): self._origin_TempIn.read() # if(self._origin_TempIn.isNew()): self._d_origin_Temp = self._origin_TempIn.read() temp = self._d_origin_Temp.data #print "Temp: %4.2lf" % self._d_origin_Temp.data #print self._d_origin_Temp.data print temp #else: # print "no new data" time.sleep(5) return RTC.RTC_OK # ## # # # # The aborting action when main logic error occurred. # # former rtc_aborting_entry() # # # # @param ec_id target ExecutionContext Id # # # # @return RTC::ReturnCode_t # # # # #def onAborting(self, ec_id): # # return RTC.RTC_OK # ## # # # # The error action in ERROR state # # former rtc_error_do() # # # # @param ec_id target ExecutionContext Id # # # # @return RTC::ReturnCode_t # # # # #def onError(self, ec_id): # # return RTC.RTC_OK # ## # # # # The reset action that is invoked resetting # # This is same but different the former rtc_init_entry() # # # # @param ec_id target ExecutionContext Id # # # # @return RTC::ReturnCode_t # # # # #def onReset(self, ec_id): # # return RTC.RTC_OK # ## # # # # The state update action that is invoked after onExecute() action # # no corresponding operation exists in OpenRTm-aist-0.2.0 # # # # @param ec_id target ExecutionContext Id # # # # @return RTC::ReturnCode_t # # # # #def onStateUpdate(self, ec_id): # # return RTC.RTC_OK # ## # # # # The action that is invoked when execution context's rate is changed # # no corresponding operation exists in OpenRTm-aist-0.2.0 # # # # @param ec_id target ExecutionContext Id # # # # @return RTC::ReturnCode_t # # # # #def onRateChanged(self, ec_id): # # return RTC.RTC_OK def outTempInit(manager): profile = OpenRTM_aist.Properties(defaults_str=outtemp_spec) manager.registerFactory(profile, outTemp, OpenRTM_aist.Delete) def MyModuleInit(manager): outTempInit(manager) # Create a component comp = manager.createComponent("outTemp") def main(): mgr = OpenRTM_aist.Manager.init(sys.argv) mgr.setModuleInitProc(MyModuleInit) mgr.activateManager() mgr.runManager() if __name__ == "__main__": main()
max-koara/OutTemp
outTemp.py
Python
gpl-3.0
5,559
# Paperwork - Using OCR to grep dead trees the easy way # Copyright (C) 2014 Jerome Flesch # # Paperwork 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. # # Paperwork 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 Paperwork. If not, see <http://www.gnu.org/licenses/>. import os import logging from gi.repository import Gdk from gi.repository import GdkPixbuf from gi.repository import Gtk from paperwork.backend.labels import Label from paperwork.frontend.util import load_uifile from paperwork.frontend.util.actions import SimpleAction logger = logging.getLogger(__name__) DROPPER_BITS = ( "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377\377\377\377" "\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\0\0\0\377" "\0\0\0\377\0\0\0\377\377\377\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377" "\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\377\377\377\377" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377" "\377\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\377\0\0" "\0\377\0\0\0\377\0\0\0\377\377\377\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\0\0\0\377\0\0\0\377\0" "\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\377\377\377" "\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\377\377\377\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0\0\0\377\0" "\0\0\377\377\377\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\0\0\0\377\0\0" "\0\377\0\0\0\377\377\377\377\377\377\377\377\377\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377" "\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\377\377\377" "\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377\377\377\377\377\377\377" "\0\0\0\377\377\377\377\377\0\0\0\377\377\377\377\377\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377" "\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\377\377" "\377\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\377\377\377\377\377\377\377\377\377\377\377\377\377\0\0\0" "\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377\377\377\377" "\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377" "\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\377\377\377\377\377\377\377\377\377\377\377\377\377\0\0\0\377\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\377\377\377\377\377\377\377\377\0\0" "\0\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\0\0\0\0\377\0\0\0" "\377\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\377\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0" ) DROPPER_WIDTH = 17 DROPPER_HEIGHT = 17 DROPPER_X_HOT = 2 DROPPER_Y_HOT = 16 class PickColorAction(SimpleAction): """ Hack taken from libgtk3/gtk/deprecated/gtkcolorsel.c """ def __init__(self, label_editor): super(PickColorAction, self).__init__("Pick color") self.__editor = label_editor self.__dropper_grab_widget = None self.__grab_time = None self.__has_grab = False self.__pointer_device = None def do(self): self._get_screen_color() def _make_picker_cursor(self, display): # XXX(Jflesch) ... do not work try: return Gdk.Cursor.new_from_name(display, "color-picker") except TypeError: pass try: # happens when new_from_name returns NULL at C level pixbuf = GdkPixbuf.Pixbuf.new_from_data( DROPPER_BITS, GdkPixbuf.Colorspace.RGB, True, 8, DROPPER_WIDTH, DROPPER_HEIGHT, DROPPER_WIDTH * 4 ) cursor = Gdk.Cursor.new_from_pixbuf(display, pixbuf, DROPPER_X_HOT, DROPPER_Y_HOT) return cursor except TypeError: pass return None def _get_screen_color(self): time = Gtk.get_current_event_time() screen = self.__editor._pick_button.get_screen() display = self.__editor._pick_button.get_display() # XXX(JFlesch): Assumption: mouse is used pointer_device = Gtk.get_current_event_device() if not self.__dropper_grab_widget: self.__dropper_grab_widget = Gtk.Window.new(Gtk.WindowType.POPUP) self.__dropper_grab_widget.set_screen(screen) self.__dropper_grab_widget.resize(1, 1) self.__dropper_grab_widget.move(-100, -100) self.__dropper_grab_widget.show() self.__dropper_grab_widget.add_events( Gdk.EventMask.BUTTON_RELEASE_MASK ) toplevel = self.__editor._pick_button.get_toplevel() if isinstance(toplevel, Gtk.Window): if toplevel.has_group(): toplevel.get_group().add_window(self.__dropper_grab_widget) window = self.__dropper_grab_widget.get_window() picker_cursor = self._make_picker_cursor(display) if (pointer_device.grab( window, Gdk.GrabOwnership.APPLICATION, False, Gdk.EventMask.BUTTON_RELEASE_MASK, picker_cursor, time) != Gdk.GrabStatus.SUCCESS): logger.warning("Pointer device grab failed !") return Gtk.device_grab_add(self.__dropper_grab_widget, pointer_device, True) self.__grab_time = time self.__pointer_device = pointer_device self.__has_grab = True self.__dropper_grab_widget.connect("button-release-event", self._on_mouse_release) def _grab_color_at_pointer(self, screen, device, x, y): root_window = screen.get_root_window() pixbuf = Gdk.pixbuf_get_from_window(root_window, x, y, 1, 1) # XXX(Jflesch): bad shortcut here ... pixels = pixbuf.get_pixels() rgb = ( float(ord(pixels[0]) * 0x101) / 65535, float(ord(pixels[1]) * 0x101) / 65535, float(ord(pixels[2]) * 0x101) / 65535, ) logger.info("Picked color: %s" % str(rgb)) return rgb def _on_mouse_release(self, invisible_widget, event): if not self.__has_grab: return try: color = self._grab_color_at_pointer( event.get_screen(), event.get_device(), event.x_root, event.y_root ) self.__editor._color_chooser.set_rgba( Gdk.RGBA( red=color[0], green=color[1], blue=color[2], alpha=1.0 ) ) finally: self.__pointer_device.ungrab(self.__grab_time) Gtk.device_grab_remove(self.__dropper_grab_widget, self.__pointer_device) self.__has_grab = False self.__pointer_device = None class LabelEditor(object): """ Dialog to create / edit labels """ def __init__(self, label_to_edit=None): if label_to_edit is None: label_to_edit = Label() self.label = label_to_edit self.__ok_button = None def edit(self, main_window): """ Open the edit dialog, and update the label according to user changes """ widget_tree = load_uifile( os.path.join("labeleditor", "labeleditor.glade")) dialog = widget_tree.get_object("dialogLabelEditor") dialog.set_transient_for(main_window) self.__ok_button = widget_tree.get_object("buttonOk") self._pick_button = widget_tree.get_object("buttonPickColor") PickColorAction(self).connect([self._pick_button]) self._color_chooser = widget_tree.get_object("labelColorChooser") self._color_chooser.set_rgba(self.label.color) name_entry = widget_tree.get_object("entryLabelName") name_entry.connect("changed", self.__on_label_entry_changed) name_entry.set_text(self.label.name) response = dialog.run() if (response == Gtk.ResponseType.OK and name_entry.get_text().strip() == ""): response = Gtk.ResponseType.CANCEL if (response == Gtk.ResponseType.OK): logger.info("Label validated") self.label.name = unicode(name_entry.get_text(), encoding='utf-8') self.label.color = self._color_chooser.get_rgba() else: logger.info("Label editing cancelled") dialog.destroy() logger.info("Label after editing: %s" % self.label) return (response == Gtk.ResponseType.OK) def __on_label_entry_changed(self, label_entry): txt = unicode(label_entry.get_text(), encoding='utf-8').strip() ok_enabled = True ok_enabled = ok_enabled and txt != u"" ok_enabled = ok_enabled and u"," not in txt self.__ok_button.set_sensitive(ok_enabled)
kschwank/paperwork
src/paperwork/frontend/labeleditor/__init__.py
Python
gpl-3.0
10,471
package com.cloudera.cmf.service; import com.cloudera.cmf.command.ConfirmCommandInfo; import com.cloudera.cmf.command.ServiceCommandHandler; import com.cloudera.cmf.command.SvcCmdArgs; import com.cloudera.cmf.model.DbCommand; import com.cloudera.cmf.model.DbRole; import com.cloudera.cmf.model.DbService; import com.cloudera.cmf.model.TypedDbBase; import com.cloudera.cmf.persist.CmfEntityManager; import com.cloudera.server.web.common.I18n; import com.google.common.collect.ImmutableList; import java.util.Collections; import java.util.List; import java.util.Set; @Deprecated public abstract class AbstractServiceCommand<A extends SvcCmdArgs> extends AbstractCommandHandler<DbService, A> implements ServiceCommandHandler<A> { protected AbstractServiceCommand(ServiceDataProvider sdp) { super(sdp); } public final DbCommand execute(DbService service, A arg, DbCommand parent) { Set roles = Collections.emptySet(); if (arg != null) { roles = arg.targetRoles; } if ((isExclusive()) && (hasActiveCommands(service, roles, parent))) { return CommandUtils.createFailedCommand(getName(), service, "There is already a pending command on this service.", parent); } DbCommand cmd = DbCommand.of(service, getName()); cmd.setParent(parent); CmfEntityManager.currentCmfEntityManager().persistCommand(cmd); executeImpl(cmd, service, roles, arg); return cmd; } protected abstract void executeImpl(DbCommand paramDbCommand, DbService paramDbService, Set<DbRole> paramSet, A paramA); public boolean isApplicableToAllRoleInstances() { return false; } public ConfirmCommandInfo getConfirmCommandInfo(DbService target, A args) { String msg; String msg; if (args.targetRoles.isEmpty()) msg = I18n.t("message.service.commandConfirm", new String[] { getDisplayName(), target.getDisplayName() }); else { msg = I18n.t("message.roleInstances.commandConfirm", new String[] { getDisplayName() }); } return ConfirmCommandInfo.create(msg, getConfirmCommandWarning(target, args)); } protected String getConfirmCommandWarning(DbService target, A args) { return null; } public List<? extends TypedDbBase> getContext(CmfEntityManager em, DbCommand cmd) { return ImmutableList.of(cmd.getService()); } }
Mapleroid/cm-server
server-5.11.0.src/com/cloudera/cmf/service/AbstractServiceCommand.java
Java
gpl-3.0
2,398
package HHCP; import causalgraph.Edge; import org.jgrapht.graph.ClassBasedEdgeFactory; import org.jgrapht.graph.DefaultDirectedWeightedGraph; import java.util.*; /** * Created by ignasi on 21/08/17. */ public class JustificationGraph { private DefaultDirectedWeightedGraph<String, Edge> graph; public BitSet relevants = new BitSet(); public JustificationGraph(Problem p){ graph = createStringGraph(); for(VAction va : p.getVaList()){ if(va.isObservation){ feedObservations(va); }else if(va.isNondeterministic){ feedNonDetActions(va); }else{ feedActions(va); } } } private void feedActions(VAction a) { for(VEffect e : a.getEffects()){ for(int to = e.getAddList().nextSetBit(0);to>=0;to = e.getAddList().nextSetBit(to+1)){ graph.addVertex(String.valueOf(to)); BitSet origins = (BitSet) e.getCondition().clone(); origins.or(a.getPreconditions()); for(int from = origins.nextSetBit(0);from>=0;from = origins.nextSetBit(from+1)){ if(from == to) continue; graph.addVertex(String.valueOf(from)); Edge<String> edge = new Edge<String>(String.valueOf(from), String.valueOf(to), a.getName()); graph.addEdge(String.valueOf(from), String.valueOf(to), edge); graph.setEdgeWeight(edge, a.cost * -1); } } } } private void feedObservations(VAction a) { for(VEffect e : a.getEffects()){ for(int to = e.getAddList().nextSetBit(0);to>=0;to = e.getAddList().nextSetBit(to+1)){ graph.addVertex(String.valueOf(to)); for(int from = a.getPreconditions().nextSetBit(0);from>=0;from = a.getPreconditions().nextSetBit(from+1)){ if(from == to) continue; graph.addVertex(String.valueOf(from)); Edge<String> edge = new Edge<String>(String.valueOf(from), String.valueOf(to), a.getName()); graph.addEdge(String.valueOf(from), String.valueOf(to), edge); graph.setEdgeWeight(edge, a.cost * -1); } } } } private void feedNonDetActions(VAction a){ for(VEffect e : a.getEffects()){ for(int to = e.getAddList().nextSetBit(0);to>=0;to = e.getAddList().nextSetBit(to+1)){ graph.addVertex(String.valueOf(to)); for(int from = a.getPreconditions().nextSetBit(0);from>=0;from = a.getPreconditions().nextSetBit(from+1)){ if(from == to) continue; graph.addVertex(String.valueOf(from)); Edge<String> edge = new Edge<String>(String.valueOf(from), String.valueOf(to), a.getName()); graph.addEdge(String.valueOf(from), String.valueOf(to), edge); graph.setEdgeWeight(edge, a.cost * -1); } } } } private DefaultDirectedWeightedGraph<String, Edge> createStringGraph(){ DefaultDirectedWeightedGraph<String, Edge> g = new DefaultDirectedWeightedGraph<String, Edge>( new ClassBasedEdgeFactory<String, Edge>(Edge.class)); return g; } public Set<Edge> getIncomingEdgesOf(String goal) { Set<Edge> hS = graph.incomingEdgesOf(goal); return hS; } public double getEdgeWeight(Edge e) { return graph.getEdgeWeight(e)*-1; } public void setRelevantLiterals(Problem p, HashSet<String> relevantList){ for(String lit : relevantList){ relevants.set(p.getPredicate(lit)); } } public BitSet getReachableLiterals(BitSet goalState, BitSet initial){ BitSet next = new BitSet(); BitSet current = (BitSet) initial.clone(); HashSet<String> visited = new HashSet<String>(); boolean reached = false; while(!reached || !contained(current, goalState)){ if(current.equals(next)){ reached = true; } for(int i = current.nextSetBit(0); i>=0; i=current.nextSetBit(i+1)){ if(!graph.containsVertex(String.valueOf(i))) continue; Set<Edge> edges = graph.outgoingEdgesOf(String.valueOf(i)); for(Edge e : edges){ if(!visited.contains(e.getTarget())) { visited.add(e.getTarget()); next.set(Integer.parseInt(e.getTarget())); } } } current.or(next); } return current; } private boolean contained(BitSet current, BitSet goalState) { BitSet aux = new BitSet(); aux.or(goalState); aux.and(current); if(goalState.equals(aux)) return true; return false; } }
ignasiet/Translator
src/HHCP/JustificationGraph.java
Java
gpl-3.0
4,984
package database; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; /** * Singleton class for connecting to the database through JDBC. * * @author Maks (original) * @author Brett Commandeur (modified by) * @reference https://github.com/MaksJS/jdbc-singleton/blob/master/JDBC.java on March 1, 2015 **/ public class JDBC { private static Connection connection = null; private static String username = null; private static String password = null; private static Boolean connectingFromLab = null; private final static String REMOTE_URL = "jdbc:oracle:thin:@localhost:1525:CRS"; // Work from Home private final static String LAB_URL = "jdbc:oracle:thin:@gwynne.cs.ualberta.ca:1521:CRS"; // Lab Machines private final static String DRIVER = "oracle.jdbc.driver.OracleDriver"; private static final int LOGIN_TIMEOUT = 3; /** * Method that loads the specified driver * * @return void **/ private static void loadDriver() { try { Class drvClass = Class.forName(DRIVER); DriverManager.registerDriver((Driver)drvClass.newInstance()); } catch (Exception e) { errorHandler("Failed to load the driver " + DRIVER, e); } } /** * Method that loads the connection into the right property * * @return void **/ private static void loadConnection() { if (username == null || password == null || connectingFromLab == null) { errorHandler("Please configure username, password, connecting from lab", null); } else { String url = (connectingFromLab) ? LAB_URL : REMOTE_URL; DriverManager.setLoginTimeout(LOGIN_TIMEOUT); try { connection = DriverManager.getConnection(url, username, password); } catch (SQLException e) { errorHandler("Failed to connect to the database " + url, e); } } } /** * Method that shows the errors thrown by the singleton * * @param {String} Message * @option {Exception} e * @return void **/ private static void errorHandler(String message, Exception e) { System.out.println(message); if (e != null) System.out.println(e.getMessage()); } /** * Method that sets the user and password for the connection * * @param newUser * @param newPassword * @return void */ public static void configure(String newUsername, String newPassword, boolean isConnectingFromLab) { username = newUsername; password = newPassword; connectingFromLab = isConnectingFromLab; } /*** * Method that checks whether db info has been set. * * @return Whether the necessary db info is configured. */ public static boolean isConfigured() { return (username != null && password != null && connectingFromLab != null); } /** * Static method that returns the instance for the singleton * * @return {Connection} connection **/ public static Connection connect() { if (connection == null) { loadDriver(); loadConnection(); } return connection; } /** * Static method that closes the connection to the database * * @return true on success. **/ public static boolean closeConnection() { if (connection == null) { errorHandler("No connection found", null); } else { try { connection.close(); connection = null; return true; } catch (SQLException e) { errorHandler("Failed to close the connection", e); } } return false; } /** * Method to execute a given SQL update on the connection * * @param sql * @return void **/ public static boolean hasConnection() { boolean valid = false; if (connection != null) { valid = true; } return valid; } }
C391-Project/RadiologyApp
src/database/JDBC.java
Java
gpl-3.0
4,195
#ifndef FO_BASE_BUFFER_HPP_ #define FO_BASE_BUFFER_HPP_ #include <stdint.h> #include <cstdlib> #include "Common.hpp" namespace fonline { class Buffer { public: FONLINE_COMMON_API Buffer(); FONLINE_COMMON_API Buffer(size_t alen); FONLINE_COMMON_API ~Buffer(); FONLINE_COMMON_API void Reset(); FONLINE_COMMON_API void Write(const void* buf, size_t alen); FONLINE_COMMON_API void Read(void *buf, size_t alen); // XXX[1.8.2012 alex]: new names FONLINE_COMMON_API bool IsError(); FONLINE_COMMON_API bool NeedProcess(); FONLINE_COMMON_API void EnsureCapacity(size_t capacity); FONLINE_COMMON_API void EnsureWriteCapacity(size_t dataSize); template<class T> Buffer& operator<<(const T& value) { // XXX[1.8.2012 alex]: endianness? Write(&value, sizeof(value)); return *this; } template<class T> Buffer& operator>>(T& value) { // XXX[1.8.2012 alex]: endianness? Read(&value, sizeof(value)); return *this; } bool error; char* data; size_t capacity; size_t writePosition; size_t readPosition; }; }; // namespace fonline #endif // FO_BASE_BUFFER_HPP_
alexknvl/fonline
src/FOnlineCommon/buffer.hpp
C++
gpl-3.0
1,163
@extends('layouts.app') @section('title') Account Settings - Barmate POS @stop @section('custom-css') @stop @section('content') <div class="row paper"> <div class="paper-header"> <h2><i class="fa fa-gear"></i>&nbsp;&nbsp;Account Settings</h2> </div> @if ( Session::has('error') ) <div class="paper-notify error"> <i class="fa fa-exclamation-triangle"></i>&nbsp; {{ Session::get('error') }} </div> @elseif ( Session::has('success') ) <div class="paper-notify success"> <i class="fa fa-check"></i>&nbsp; {{ Session::get('success') }} </div> @endif <div class="paper-body"> {!! Form::open(['url'=>'app/account', 'method'=>'POST']) !!} <!-- GENERAL INFORMATIONS --> <div class="col-md-4"> <label>First name</label> <input type="text" class="form-control" name="firstname" value="{{ $user->firstname }}"> </div> <div class="col-md-4"> <label>Last name</label> <input type="text" class="form-control" name="lastname" value="{{ $user->lastname }}"> </div> <div class="col-md-4"> <label>Role</label> <input type="text" class="form-control" disabled value="{{ $roleDescription }}"> </div> <!-- EMAIL --> <div class="col-md-12"> <label>Email</label> <input type="text" class="form-control" name="email" value="{{ $user->email }}"> </div> <!-- PASSWORD --> <div class="col-md-4"> <label>Current password</label> <input type="password" class="form-control" disabled value="password"> </div> <div class="col-md-4"> <label>New password</label> <input type="password" name="password" class="form-control"> </div> <div class="col-md-4"> <label>Repeat new password</label> <input type="password" name="repeat_password" class="form-control"> </div> <!-- NOTES --> <div class="col-md-12"> <label>About me</label> <textarea class="form-control" name="notes">{{ $user->notes }}</textarea> <br> <input type="submit" class="btn btn-primary pull-right" value="Save settings"> </div> <!-- TRICKY PATCH TO ALLOW PADDING BOTTOM --> &nbsp; </form> </div> </div> @stop @section('custom-js') @stop
Saluki/Barmate
resources/views/account/main.blade.php
PHP
gpl-3.0
2,925
package com.hhd.breath.app.main.ui; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import com.hhd.breath.app.BaseActivity; import com.hhd.breath.app.R; import com.hhd.breath.app.utils.ShareUtils; public class ModifyNameActivity extends BaseActivity { private TextView mTextTop ; private RelativeLayout mLayoutBackRe ; private RelativeLayout mLayoutRight ; private EditText mEditName ; private InputMethodManager imm ; private String userName ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_modify_name); userName = getIntent().getExtras().getString("userName") ; imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); initView(); initEvent(); } @Override protected void initView() { mTextTop = (TextView)findViewById(R.id.topText) ; mLayoutBackRe = (RelativeLayout)findViewById(R.id.back_re) ; mLayoutRight = (RelativeLayout)findViewById(R.id.layout_right) ; mEditName = (EditText)findViewById(R.id.edit_username) ; mLayoutRight.setVisibility(View.VISIBLE); } public static void actionActivity(Activity mActivity , String userName){ Bundle mBundle = new Bundle() ; mBundle.putString("userName",userName); Intent mIntent = new Intent() ; mIntent.setClass(mActivity,ModifyNameActivity.class) ; mIntent.putExtras(mBundle) ; mActivity.startActivity(mIntent); } @Override protected void initEvent() { mTextTop.setText("修改用户名"); mEditName.setText(userName); mLayoutBackRe.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (imm.isActive()) { imm.hideSoftInputFromWindow(mEditName.getWindowToken(), 0); //强制隐藏键盘 } ModifyNameActivity.this.finish(); } }); mLayoutRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (imm.isActive()) { imm.hideSoftInputFromWindow(mEditName.getWindowToken(), 0); //强制隐藏键盘 } ShareUtils.setUserName(ModifyNameActivity.this,mEditName.getText().toString().trim()); ModifyNameActivity.this.finish(); } }); } }
weibingithub/BreathApp
app/src/main/java/com/hhd/breath/app/main/ui/ModifyNameActivity.java
Java
gpl-3.0
2,791
""" SicPy """ # __version__ = '0.1' # __author__ = 'disrupts' # __license__ = 'GPLv3' # Cryptobox should only be used to implement ciphers #from sicpy.cryptobox import Cryptobox # Ciphers are imported directly with sicpy #  not requiring an aditional import from sicpy.ciphers.caesar import Caesar from sicpy.ciphers.vigenere import Vigenere from sicpy.ciphers.railfence import RailFence # Alphabet can be used to build alphabets easily # >>> myalpha = Alphabet('ABSDE') from sicpy.alphabet import Alphabet # LATIN is imported by cryptobox.py
disrupts/SicPy
sicpy/__init__.py
Python
gpl-3.0
557
<?php /** * Membership Settings meta box * * @package LifterLMS/Admin/PostTypes/MetaBoxes/Classes * * @since 1.0.0 * @version 5.9.0 */ defined( 'ABSPATH' ) || exit; /** * Membership Settings meta box class * * @since 1.0.0 * @since 3.30.3 Fixed spelling errors; removed duplicate array keys. * @since 3.35.0 Verify nonces and sanitize `$_POST` data. * @since 3.36.0 Allow some fields to store values with quotes. * @since 3.36.3 In the `save() method Added logic to correctly sanitize fields of type * 'multi' (array) and 'shortcode' (preventing quotes encode). * Also align the method return type to the parent `save()` method. */ class LLMS_Meta_Box_Membership extends LLMS_Admin_Metabox { /** * This function allows extending classes to configure required class properties * $this->id, $this->title, and $this->screens should be configured in this function. * * @return void * @since 3.0.0 */ public function configure() { $this->id = 'lifterlms-membership'; $this->title = __( 'Membership Settings', 'lifterlms' ); $this->screens = array( 'llms_membership', ); $this->priority = 'high'; } /** * Get array of data to pass to the auto enrollment courses table. * * @since 3.0.0 * @since 3.30.0 Removed sorting by title. * @since 3.30.3 Fixed spelling errors. * * @param obj $membership instance of LLMS_Membership for the current post. * @return array */ private function get_content_table( $membership ) { $data = array(); $data[] = array( '', '<br>' . __( 'No automatic enrollment courses found. Add a course below.', 'lifterlms' ) . '<br><br>', '', ); foreach ( $membership->get_auto_enroll_courses() as $course_id ) { $course = new LLMS_Course( $course_id ); $title = $course->get( 'title' ); $data[] = array( '<span class="llms-drag-handle" style="color:#999;"><i class="fa fa-ellipsis-v" aria-hidden="true" style="margin-right:2px;"></i><i class="fa fa-ellipsis-v" aria-hidden="true"></i></span>', '<a href="' . get_edit_post_link( $course->get( 'id' ) ) . '">' . $title . ' (ID#' . $course_id . ')</a>', '<a class="llms-button-danger small" data-id="' . $course_id . '" href="#llms-course-remove" style="float:right;">' . __( 'Remove course', 'lifterlms' ) . '</a> <a class="llms-button-secondary small" data-id="' . $course_id . '" href="#llms-course-bulk-enroll" style="float:right;">' . __( 'Enroll All Members', 'lifterlms' ) . '</a>', ); } return apply_filters( 'llms_membership_get_content_table_data', $data, $membership ); } /** * This function is where extending classes can configure all the fields within the metabox. * The function must return an array which can be consumed by the "output" function. * * @since 3.0.0 * @since 3.30.0 Removed empty field settings. Modified settings to accommodate sortable auto-enrollment table. * @since 3.30.3 Removed duplicate array keys. * @since 3.36.0 Allow some fields to store values with quotes. * * @return array */ public function get_fields() { global $post; $membership = new LLMS_Membership( $this->post ); $redirect_options = array(); $redirect_page_id = $membership->get( 'redirect_page_id' ); if ( $redirect_page_id ) { $redirect_options[] = array( 'key' => $redirect_page_id, 'title' => get_the_title( $redirect_page_id ) . '(ID#' . $redirect_page_id . ')', ); } $sales_page_content_type = 'none'; if ( $post && 'auto-draft' !== $post->post_status && $post->post_excerpt ) { $sales_page_content_type = 'content'; } return array( array( 'title' => __( 'Sales Page', 'lifterlms' ), 'fields' => array( array( 'allow_null' => false, 'class' => 'llms-select2', 'desc' => __( 'Customize the content displayed to visitors and students who are not enrolled in the membership.', 'lifterlms' ), 'desc_class' => 'd-3of4 t-3of4 m-1of2', 'default' => $sales_page_content_type, 'id' => $this->prefix . 'sales_page_content_type', 'is_controller' => true, 'label' => __( 'Sales Page Content', 'lifterlms' ), 'type' => 'select', 'value' => llms_get_sales_page_types(), ), array( 'controller' => '#' . $this->prefix . 'sales_page_content_type', 'controller_value' => 'content', 'desc' => __( 'This content will only be shown to visitors who are not enrolled in this membership.', 'lifterlms' ), 'id' => '', 'label' => __( 'Sales Page Custom Content', 'lifterlms' ), 'type' => 'post-excerpt', ), array( 'controller' => '#' . $this->prefix . 'sales_page_content_type', 'controller_value' => 'page', 'data_attributes' => array( 'post-type' => 'page', 'placeholder' => __( 'Select a page', 'lifterlms' ), ), 'class' => 'llms-select2-post', 'id' => $this->prefix . 'sales_page_content_page_id', 'type' => 'select', 'label' => __( 'Select a Page', 'lifterlms' ), 'value' => $membership->get( 'sales_page_content_page_id' ) ? llms_make_select2_post_array( array( $membership->get( 'sales_page_content_page_id' ) ) ) : array(), ), array( 'controller' => '#' . $this->prefix . 'sales_page_content_type', 'controller_value' => 'url', 'type' => 'text', 'label' => __( 'Sales Page Redirect URL', 'lifterlms' ), 'id' => $this->prefix . 'sales_page_content_url', 'class' => 'input-full', 'value' => '', 'desc_class' => 'd-all', 'group' => 'top', ), ), ), array( 'title' => __( 'Restrictions', 'lifterlms' ), 'fields' => array( array( 'allow_null' => false, 'class' => '', 'desc' => __( 'When a non-member attempts to access content restricted to this membership', 'lifterlms' ), 'id' => $this->prefix . 'restriction_redirect_type', 'is_controller' => true, 'type' => 'select', 'label' => __( 'Restricted Access Redirect', 'lifterlms' ), 'value' => array( array( 'key' => 'none', 'title' => __( 'Stay on page', 'lifterlms' ), ), array( 'key' => 'membership', 'title' => __( 'Redirect to this membership page', 'lifterlms' ), ), array( 'key' => 'page', 'title' => __( 'Redirect to a WordPress page', 'lifterlms' ), ), array( 'key' => 'custom', 'title' => __( 'Redirect to a Custom URL', 'lifterlms' ), ), ), ), array( 'class' => 'llms-select2-post', 'controller' => '#' . $this->prefix . 'restriction_redirect_type', 'controller_value' => 'page', 'data_attributes' => array( 'post-type' => 'page', ), 'id' => $this->prefix . 'redirect_page_id', 'label' => __( 'Select a WordPress Page', 'lifterlms' ), 'type' => 'select', 'value' => $redirect_options, ), array( 'class' => '', 'controller' => '#' . $this->prefix . 'restriction_redirect_type', 'controller_value' => 'custom', 'id' => $this->prefix . 'redirect_custom_url', 'label' => __( 'Enter a Custom URL', 'lifterlms' ), 'type' => 'text', 'value' => 'test', ), array( 'class' => '', 'controls' => '#' . $this->prefix . 'restriction_notice', 'default' => 'yes', 'desc' => __( 'Check this box to output a message after redirecting. If no redirect is selected this message will replace the normal content that would be displayed.', 'lifterlms' ), 'desc_class' => 'd-3of4 t-3of4 m-1of2', 'id' => $this->prefix . 'restriction_add_notice', 'label' => __( 'Display a Message', 'lifterlms' ), 'type' => 'checkbox', 'value' => 'yes', ), array( 'class' => 'full-width', 'desc' => sprintf( __( 'Shortcodes like %s can be used in this message', 'lifterlms' ), '[lifterlms_membership_link id="' . $this->post->ID . '"]' ), 'default' => sprintf( __( 'You must belong to the %s membership to access this content.', 'lifterlms' ), '[lifterlms_membership_link id="' . $this->post->ID . '"]' ), 'id' => $this->prefix . 'restriction_notice', 'label' => __( 'Restricted Content Notice', 'lifterlms' ), 'type' => 'text', 'sanitize' => 'shortcode', ), ), ), array( 'title' => __( 'Auto Enrollment', 'lifterlms' ), 'fields' => array( array( 'label' => __( 'Automatic Enrollment', 'lifterlms' ), 'desc' => sprintf( __( 'When a student joins this membership they will be automatically enrolled in these courses. Click %1$shere%2$s for more information.', 'lifterlms' ), '<a href="https://lifterlms.com/docs/membership-auto-enrollment/" target="_blank">', '</a>' ), 'id' => $this->prefix . 'content_table', 'titles' => array( '', __( 'Course Name', 'lifterlms' ), '' ), 'type' => 'table', 'table_data' => $this->get_content_table( $membership ), ), array( 'class' => 'llms-select2-post', 'data_attributes' => array( 'placeholder' => __( 'Select course(s)', 'lifterlms' ), 'post-type' => 'course', 'no-view-button' => true, ), 'id' => $this->prefix . 'auto_enroll', 'label' => __( 'Add Course(s)', 'lifterlms' ), 'type' => 'select', 'value' => array(), ), ), ), ); } /** * Save field data. * * @since 3.0.0 * @since 3.30.0 Autoenroll courses saved via AJAX and removed from this method. * @since 3.35.0 Verify nonces and sanitize `$_POST` data. * @since 3.36.3 Added logic to correctly sanitize fields of type 'multi' (array) * and 'shortcode' (preventing quotes encode). * Also align the return type to the parent `save()` method. * @since 5.9.0 Stop using deprecated `FILTER_SANITIZE_STRING`. * * @see LLMS_Admin_Metabox::save_actions() * * @param int $post_id WP_Post ID of the post being saved. * @return int `-1` When no user or user is missing required capabilities or when there's no or invalid nonce. * `0` during inline saves or ajax requests or when no fields are found for the metabox. * `1` if fields were found. This doesn't mean there weren't errors during saving. */ public function save( $post_id ) { if ( ! llms_verify_nonce( 'lifterlms_meta_nonce', 'lifterlms_save_data' ) ) { return -1; } // Return early during quick saves and ajax requests. if ( isset( $_POST['action'] ) && 'inline-save' === $_POST['action'] ) { return 0; } elseif ( llms_is_ajax() ) { return 0; } $membership = new LLMS_Membership( $post_id ); if ( ! isset( $_POST[ $this->prefix . 'restriction_add_notice' ] ) ) { $_POST[ $this->prefix . 'restriction_add_notice' ] = 'no'; } // Get all defined fields. $fields = $this->get_fields(); // save all the fields. $save_fields = array( $this->prefix . 'restriction_redirect_type', $this->prefix . 'redirect_page_id', $this->prefix . 'redirect_custom_url', $this->prefix . 'restriction_add_notice', $this->prefix . 'restriction_notice', $this->prefix . 'sales_page_content_page_id', $this->prefix . 'sales_page_content_type', $this->prefix . 'sales_page_content_url', ); if ( ! is_array( $fields ) ) { return 0; } $to_return = 0; // Loop through the fields. foreach ( $fields as $group => $data ) { // Find the fields in each tab. if ( isset( $data['fields'] ) && is_array( $data['fields'] ) ) { // loop through the fields. foreach ( $data['fields'] as $field ) { // don't save things that don't have an ID or that are not listed in $save_fields. if ( isset( $field['id'] ) && in_array( $field['id'], $save_fields, true ) ) { if ( isset( $field['sanitize'] ) && 'shortcode' === $field['sanitize'] ) { $val = llms_filter_input_sanitize_string( INPUT_POST, $field['id'], array( FILTER_FLAG_NO_ENCODE_QUOTES ) ); } elseif ( isset( $field['multi'] ) && $field['multi'] ) { $val = llms_filter_input_sanitize_string( INPUT_POST, $field['id'], array( FILTER_REQUIRE_ARRAY ) ); } else { $val = llms_filter_input_sanitize_string( INPUT_POST, $field['id'] ); } $membership->set( substr( $field['id'], strlen( $this->prefix ) ), $val ); $to_return = 1; } } } } return $to_return; } }
gocodebox/lifterlms
includes/admin/post-types/meta-boxes/class.llms.meta.box.membership.php
PHP
gpl-3.0
13,071
package ru.mos.polls.quests.model.quest; import android.content.Context; import com.google.gson.annotations.SerializedName; import ru.mos.polls.quests.model.QuestFamilyElement; import ru.mos.polls.quests.vm.QuestsFragmentVM; public class OtherQuest extends BackQuest { public static final String TYPE = "other"; private static final String LINK_URL = "link_url"; @SerializedName("link_url") private String linkUrl; public OtherQuest(long innerId, QuestFamilyElement questFamilyElement) { super(innerId, questFamilyElement); linkUrl = questFamilyElement.getLinkUrl(); } @Override public void onClick(Context context, QuestsFragmentVM.Listener listener) { listener.onNews(getTitle(), linkUrl, Integer.valueOf(getId())); } }
active-citizen/android.java
app/src/main/java/ru/mos/polls/quests/model/quest/OtherQuest.java
Java
gpl-3.0
788
<?php /** * Display the upload transaction file screen * * @author Fabrice Douteaud <admin@clearbudget.net> * @package snippets * @access public */ /*********************************************************************** Copyright (C) 2008 Fabrice Douteaud (admin@clearbudget.net) This file is part of ClearBudget. ClearBudget 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. ClearBudget 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 ClearBudget. If not, see <http://www.gnu.org/licenses/>. ************************************************************************/ //prevent direct access if(!defined('ENGINEON')) die('Direct access forbidden'); ?> <h2><img src="style/icons/table_add.png"/> <?php echo $keys->pageTitle_UploadQif; ?></h2> <form id="QIFUploadForm" enctype="multipart/form-data" action="" method="POST"> <div id="qifUploadError" style="display: none" class="error"><blockquote><?php echo $keys->error_UploadQif; ?>: <span id="qifUploadErrorText"></span></blockquote></div> <table class="tableReport"> <tr> <td colspan="3"> <span id="qifUploadLoading" style="display:none;"><?php echo $keys->text_pageUploadQifLoading; ?></span> <span id="qifUploadResultCount" style="display:none; color: #3A7;"></span> </td> </tr> <tr> <td style="width: 350px"> <input name="MAX_FILE_SIZE" value="300000" type="hidden" /> <input name="action" id="action" value="uploadQifSubmit" type="hidden" /> <input name="datafile" id="fileToUpload" type="file" size="60"/> </td> <td style="width: 300px"> <?php echo $keys->text_dateFormat; ?>: <input type="radio" name="QIFLocaleType" id="QIFLocaleType" value="us" checked>MM/DD/YYYY <input type="radio" name="QIFLocaleType" id="QIFLocaleType" value="eu">DD/MM/YYYY </td> <td style="width: 150px"> <span class="jqUploader" id="jqUploader"> <button class="button" id="buttonUpload" onclick="return ajaxFileUpload();"><?php echo $keys->text_SendButton;?></button> </span> </td> </td> </tr> <!-- <tr> <td colspan="3"><small><?php echo $keys->text_qifFile; ?></small></td> </tr> --> </table> </form> <div id="importDetails"></div> <br/>
thunderace/clearbudget
snippets/uploadQif.php
PHP
gpl-3.0
2,711
<?php namespace common\modules\prj\models; use Yii; /** * This is the model class for table "{{%prj_burden_cost_base}}". * * @property string $prj_burden_cost_base_id * @property string $cost_base * @property string $description * @property string $cost_base_type * @property string $effective_from * @property string $effective_to * @property integer $priority * @property integer $created_by * @property string $creation_date * @property integer $last_update_by * @property string $last_update_date * @property integer $company_id */ class PrjBurdenCostBase extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%prj_burden_cost_base}}'; } /** * @inheritdoc */ public function rules() { return [ [['cost_base', 'created_by', 'last_update_by'], 'required'], [['effective_from', 'effective_to', 'creation_date', 'last_update_date'], 'safe'], [['priority', 'created_by', 'last_update_by', 'company_id'], 'integer'], [['cost_base', 'cost_base_type'], 'string', 'max' => 25], [['description'], 'string', 'max' => 255], [['cost_base'], 'unique'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'prj_burden_cost_base_id' => Yii::t('app', 'Prj Burden Cost Base ID'), 'cost_base' => Yii::t('app', 'Cost Base'), 'description' => Yii::t('app', 'Description'), 'cost_base_type' => Yii::t('app', 'Cost Base Type'), 'effective_from' => Yii::t('app', 'Effective From'), 'effective_to' => Yii::t('app', 'Effective To'), 'priority' => Yii::t('app', 'Priority'), 'created_by' => Yii::t('app', 'Created By'), 'creation_date' => Yii::t('app', 'Creation Date'), 'last_update_by' => Yii::t('app', 'Last Update By'), 'last_update_date' => Yii::t('app', 'Last Update Date'), 'company_id' => Yii::t('app', 'Company ID'), ]; } }
zeddarn/yinoerp
_protected/common/modules/prj/models/PrjBurdenCostBase.php
PHP
gpl-3.0
2,128
<span class="fright"> <?php if($this->phpsession->get('menu_type') == FRONT_END_MENU):?> <a class="button back" href="/dashboard/menu/<?php echo isset($lang) && $lang != '' ? $lang :$this->phpsession->get('current_menus_lang'); ?>"><em>&nbsp;</em>Quay lại trang Menu</a> <?php endif;?> <?php if($this->phpsession->get('menu_type') == BACK_END_MENU):?> <a class="button back" href="/dashboard/menu-admin/<?php echo isset($lang) && $lang != '' ? $lang :$this->phpsession->get('current_menus_lang'); ?>" ><em>&nbsp;</em>Quay lại trang Menu</a> <?php endif;?> </span>
dzung2t/noithatgo
ci_app/modules/menus/views/admin/back-menu-nav.php
PHP
gpl-3.0
591
var express = require('express'); var router = express.Router(); var seminar = require('../controllers/seminar.controllers'); router.get('/', function(req, res) { res.json({status: false, message: 'None API Implemented'}); }); router.get('/user/:id', function(req, res) { seminar.get(req, res); }); // router.get('/seminar/:id', function(req, res) { // seminar.getById(req, res); // }); router.get('/all', function(req, res) { seminar.getAll(req, res); }); router.post('/register', function(req, res) { seminar.register(req, res); }); router.delete('/delete', function(req, res) { seminar.delete(req, res); }); router.post('/attend', function(req, res) { seminar.attend(req, res); }); module.exports = router;
Rajamuda/ittoday-2017
api/routes/seminar.routes.js
JavaScript
gpl-3.0
733
#include "InputModels/SimpleGaussianModel.h" #include "Keyboard.h" #include "Polygon.h" #include "math.h" #include <cctype> #include <boost/random.hpp> #include <boost/random/normal_distribution.hpp> using namespace std; SimpleGaussianModel::SimpleGaussianModel(double xscale, double yscale, double corr) { ysigma = xscale*0.5; xsigma = yscale*0.5; fixed_length = true; SetCorrelation(corr); } void SimpleGaussianModel::SetCorrelation(double corr) { if(corr < 0) corr = 0; if(corr > 1) corr = 1; correlation = corr; correlation_complement = sqrt(1.0-correlation*correlation); } InputVector SimpleGaussianModel::RandomVector(const char* word, Keyboard& k) { //it's wasteful to remake this every time but I had trouble making it a global member boost::normal_distribution<> nd(0.0, 1.0); boost::variate_generator<boost::mt19937&, boost::normal_distribution<> > normal(generator, nd); InputVector sigma; double lastx = normal(), lasty = normal(); for(unsigned int i = 0; i < strlen(word); i++) { Polygon p = k.GetKey(tolower(word[i])); const double t = p.TopExtreme(); const double b = p.BottomExtreme(); const double r = p.RightExtreme(); const double l = p.LeftExtreme(); if(i > 0) { lastx = lastx*correlation + normal()*correlation_complement; lasty = lasty*correlation + normal()*correlation_complement; } const double x = lastx*xsigma*(r-l) + 0.5*(r+l); const double y = lasty*ysigma*(t-b) + 0.5*(t+b); sigma.AddPoint(x, y, double(i)); } return sigma; } InputVector SimpleGaussianModel::PerfectVector(const char* word, Keyboard& k) { const double tmp_xsigma = xsigma; xsigma = 0; const double tmp_ysigma = ysigma; ysigma = 0; InputVector sigma = RandomVector(word, k); xsigma = tmp_xsigma; ysigma = tmp_ysigma; return sigma; } double SimpleGaussianModel::MarginalProbability( InputVector& sigma, const char* word, Keyboard& k) { if(sigma.Length() != strlen(word)) { return 0; } double probability = 1; for(unsigned int i = 0; i < sigma.Length(); i++) { const Polygon p = k.GetKey(word[i]); const double r = p.RightExtreme(); const double l = p.LeftExtreme(); const double x = sigma.X(i); const double xmu = 0.5*(r+l); if(xsigma > 0) { const double xsd = xsigma*(r-l); probability *= (0.3989422804/xsd)*exp(-0.5*(pow((x-xmu)/xsd,2))); } else { if(xmu != x) { probability = 0; break; } } const double t = p.TopExtreme(); const double b = p.BottomExtreme(); const double y = sigma.Y(i); const double ymu = 0.5*(t+b); if(ysigma > 0) { const double ysd = ysigma*(t-b); probability *= (0.3989422804/ysd)*exp(-0.5*(pow((y-ymu)/ysd,2))); } else { if(ymu != y) { probability = 0; break; } } } return probability; } double SimpleGaussianModel::Distance( InputVector& sigma, const char* word, Keyboard& k) { if(sigma.Length() != strlen(word)) { return 1; } double probability = 1; if(xsigma > 0 && ysigma > 0) { for(unsigned int i = 0; i < sigma.Length(); i++) { const Polygon p = k.GetKey(word[i]); if(xsigma > 0) { const double r = p.RightExtreme(); const double l = p.LeftExtreme(); const double xsd = xsigma*(r-l); probability *= 0.3989422804/xsd; } if(ysigma > 0) { const double t = p.TopExtreme(); const double b = p.BottomExtreme(); const double ysd = ysigma*(t-b); probability *= 0.3989422804/ysd; } } } return (probability - MarginalProbability(sigma, word, k))/probability; } double SimpleGaussianModel::VectorDistance(InputVector& vector1, InputVector& vector2) { double d2 = 0; for(unsigned int i = 0; i < vector1.Length(); i++) { d2 += pow( vector1.X(i) - vector2.X(i), 2) + pow( vector1.Y(i) - vector2.Y(i), 2); } return sqrt(d2); }
sangaline/dodona
core/src/InputModels/SimpleGaussianModel.cpp
C++
gpl-3.0
4,337
#!/usr/bin/env node // Special Pythagorean triplet var SUM = 1000; var triplet = get_pythagorean_triplet_by_sum(SUM); console.log(triplet[0] * triplet[1] * triplet[2]); function get_pythagorean_triplet_by_sum(s) { var s2 = Math.floor(SUM / 2); var mlimit = Math.ceil(Math.sqrt(s2)) - 1; for (var m = 2; m <= mlimit; m++) { if (s2 % m == 0) { var sm = Math.floor(s2 / m); while (sm % 2 == 0) { sm = Math.floor(sm / 2); } var k = m + 1; if (m % 2 == 1) { k = m + 2; } while (k < 2 * m && k <= sm) { if (sm % k == 0 && gcd(k, m) == 1) { var d = Math.floor(s2 / (k * m)); var n = k - m; var a = d * (m * m - n * n); var b = 2 * d * m * n; var c = d * (m * m + n * n); return [a, b, c]; } k += 2; } } } return [0, 0, 0]; } function gcd(int1, int2) { if (int1 > int2) { var tmp = int1; int1 = int2; int2 = tmp; } while (int1) { var tmp = int1; int1 = int2 % int1; int2 = tmp; } return int2; }
iansealy/projecteuler
optimal/9.js
JavaScript
gpl-3.0
1,296
#include "Reseaux/RequetePartie/RequetePartie.hpp" RequetePartie::RequetePartie(int tailleRequete, int numeroRequete) : Requete(tailleRequete, 0) { numeroRequete = numeroRequete << 3; data[0] = numeroRequete; }
Aredhele/FreakyMonsters
client/src/Reseaux/RequetePartie/RequetePartie.cpp
C++
gpl-3.0
215
<?php use Phinx\Migration\AbstractMigration; class NullableInvitationFrom extends AbstractMigration { /** * Migrate Up. */ public function up() { $this->execute("ALTER TABLE invitations MODIFY sent_by INT(10) UNSIGNED DEFAULT NULL COMMENT 'The player who sent the invitation'"); } /** * Migrate Down. */ public function down() { } }
allejo/bzion
migrations/20160212221926_nullable_invitation_from.php
PHP
gpl-3.0
396
import ChatMessage from "phasecore/messagetypes/chatmessage"; interface DeepHistoryNewer { discID: number; messages: ChatMessage[]; newestID: number; } export default DeepHistoryNewer;
popstarfreas/PhaseClient
app/node_modules/phasecore/messagetypes/deephistorynewer.ts
TypeScript
gpl-3.0
199
<div class="col-md-12"> <div class="row"> <div class="col-md-6"> <h1><?php echo L('sensor_LIST'); ?></h1> </div> </div> <div class="row"> <?php if($this->session()->getUserLevel() == 3) : ?> <div class="col-md-4 text-left"> <a href="javascript:void(0)" id="sensors_rescan" class="btn btn-primary"> <span class="fa fa-refresh btn-icon"></span><span class="">&nbsp;<?php echo L('sensor_REFRESH_LIST'); ?></span></a> </div> <?php endif; ?> </div> <?php if(isset($this->view->content->list )) : ?> <br/> <table class="table table-responsive table-condensed" id="sensor_list_table"> <thead> <tr> <th>ID</th> <th><?php echo L('sensor_VALUE_NAME'); ?></th> <th><?php echo L('sensor_VALUE_SI_NOTATION'); ?></th> <th title="<?php echo L('sensor_VALUE_SI_NAME'); ?>"><?php echo L('sensor_VALUE_SI_NSHORT'); ?></th> <th title="<?php echo L('sensor_VALUE_MIN_RANGE'); ?>"><?php echo L('sensor_VALUE_MIN'); ?></th> <th title="<?php echo L('sensor_VALUE_MAX_RANGE'); ?>"><?php echo L('sensor_VALUE_MAX'); ?></th> <th><?php echo L('sensor_VALUE_ERROR'); ?></th> <th><span class="fa fa-tv"></span></th> </tr> </thead> <tbody> <?php $cnt = 0; foreach($this->view->content->list as $sensor_id => $item) : $sensor_name = (string) preg_replace('/\-.*/i', '', $sensor_id); $i = 0; foreach($item->{'Values'} as $sensor_val_id => &$data) : if (strlen($sensor_name) == 0) { continue; } $key = '' . $sensor_id . '#' . (int)$sensor_val_id; ?> <tr class="row-sensor" data-sensor-id="<?php echo htmlspecialchars($key, ENT_QUOTES, 'UTF-8');?>"> <td> <?php echo htmlspecialchars($key, ENT_QUOTES, 'UTF-8');?> </td> <td class="sensor-setup-valname"> <?php echo htmlspecialchars($data->value_name, ENT_QUOTES, 'UTF-8'); ?> </td> <td> <?php echo htmlspecialchars($data->si_notation, ENT_QUOTES, 'UTF-8'); ?> </td> <td> <?php echo htmlspecialchars($data->si_name, ENT_QUOTES, 'UTF-8'); ?> </td> <td> <?php echo htmlspecialchars($data->{'Range'}->{'Min'}, ENT_QUOTES, 'UTF-8'); ?> </td> <td> <?php echo htmlspecialchars($data->{'Range'}->{'Max'}, ENT_QUOTES, 'UTF-8'); ?> </td> <td> <?php echo isset($data->error) ? htmlspecialchars($data->error, ENT_QUOTES, 'UTF-8') : '-'; ?> </td> <td> <span class="glyphicon glyphicon-eye-open sensor-icon-btn" style="cursor:pointer;"></span>&nbsp;<span class="sensor-value"></span> </td> </tr> <?php $i++; $cnt++; endforeach; endforeach; ?> </tbody> <tfoot style="display: none;"> <tr> <td colspan="8" id="sensors_msgs"> <?php if (!$cnt) : ?> <div class="alert alert-info" role="alert"> <span class="glyphicon glyphicon-info-sign"></span>&nbsp;<?php echo L('setup_MSG_NO_AVAILABLE_SENSORS'); ?> </div> <?php endif; ?> </td> </tr> </tfoot> </table> <?php endif; ?> </div>
scratchduino/sdlab-frontend
app/views/sensors/view.all.tpl.php
PHP
gpl-3.0
2,954
# -*- coding: utf-8 -*- # This file is part of BBFlux (BackBox XFCE -> FluxBox Menu Automatic Update Daemon). # # Copyright(c) 2010-2011 Simone Margaritelli # evilsocket@gmail.com - evilsocket@backbox.org # http://www.evilsocket.net # http://www.backbox.org # # This file may be licensed under the terms of of the # GNU General Public License Version 2 (the ``GPL''). # # Software distributed under the License is distributed # on an ``AS IS'' basis, WITHOUT WARRANTY OF ANY KIND, either # express or implied. See the GPL for the specific language # governing rights and limitations. # # You should have received a copy of the GPL along with this # program. If not, go to http://www.gnu.org/licenses/gpl.html # or write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import os import fnmatch class IconParser: __instance = None def __init__(self): self.cache = {} def __findIcon( self, path, pattern ): for root, dirnames, filenames in os.walk( path ): for filename in fnmatch.filter( filenames, pattern ): return os.path.join(root, filename) return None def getIconByName( self, name ): name = name.replace( '.png', '' ) if name is None or name == '': return None if name[0] == '/': return name elif self.cache.has_key(name): return self.cache[name] else: if os.path.exists( '/usr/share/pixmaps/' + name + '.png' ): self.cache[name] = '/usr/share/pixmaps/' + name + '.png' return '/usr/share/pixmaps/' + name + '.png' elif os.path.exists( '/usr/share/pixmaps/' + name + '.xpm' ): self.cache[name] = '/usr/share/pixmaps/' + name + '.xpm' return '/usr/share/pixmaps/' + name + '.xpm' else: icon = self.__findIcon( '/usr/share/icons', name + '.png' ) if icon is not None: self.cache[name] = icon else: icon = self.__findIcon( '/usr/share/icons', name + '.xpm' ) if icon is not None: self.cache[name] = icon return icon @classmethod def getInstance(cls): if cls.__instance is None: cls.__instance = IconParser() return cls.__instance
evilsocket/BBFlux
parsers/IconParser.py
Python
gpl-3.0
2,214
// Events document.onkeypress = function (e) { e = e || window.event; var key = e.key; return keymap[key](); }; // Mouse events document.onmousemove = function (e) { e = e || window.event; lfo.frequency.value = e.clientX; main_osc.frequency.value = e.clientY / 10; changeBackgroundColor(lfo_amp.gain.value/3.125, e.clientY, e.clientX); }; // Color events var changeBackgroundColor = function(red, green, blue) { document.body.style.backgroundColor = "rgb(" + red + "," + green + "," + blue + ")"; };
ruckert/web_audio_experiments
synth007/events.js
JavaScript
gpl-3.0
534
import { Menu } from 'electron' import menuActions from './actions' import deviceItems from './devices' import folderItems from './folders' import { getDevicesWithConnections } from '../reducers/devices' import { getFoldersWithStatus } from '../reducers/folders' import { name, version } from '../../../package.json' export default function buildMenu({ st, state, state: { connected, config, }, }){ const devices = getDevicesWithConnections(state) const folders = getFoldersWithStatus(state) let menu = null const actions = menuActions(st) const sharedItems = [ { label: `${name} ${version}`, enabled: false }, { label: 'Restart Syncthing', click: actions.restart, accelerator: 'CommandOrControl+R' }, { label: 'Quit Syncthing', click: actions.quit, accelerator: 'CommandOrControl+Q' }, ] if(connected && config.isSuccess){ menu = Menu.buildFromTemplate([ ...folderItems(folders), { type: 'separator' }, ...deviceItems(devices), { type: 'separator' }, { label: 'Open...', click: actions.editConfig, accelerator: 'CommandOrControl+,' }, { type: 'separator' }, ...sharedItems, ]) }else{ menu = Menu.buildFromTemplate([ { label: config.isFailed ? 'No config available' : 'Connection error', enabled: false }, ...sharedItems, ]) } return menu }
JodusNodus/syncthing-tray
app/main/menu/index.js
JavaScript
gpl-3.0
1,367
# -*- coding: utf-8 -*- # Copyright (C) 2005 Osmo Salomaa # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. import gaupol from gi.repository import Gtk class _TestPositionTransformDialog(gaupol.TestCase): def run_dialog(self): self.dialog.run() self.dialog.destroy() def test__on_response(self): self.dialog.response(Gtk.ResponseType.OK) class TestFrameTransformDialog(_TestPositionTransformDialog): def setup_method(self, method): self.application = self.new_application() self.dialog = gaupol.FrameTransformDialog( self.application.window, self.application) self.dialog.show() class TestTimeTransformDialog(_TestPositionTransformDialog): def setup_method(self, method): self.application = self.new_application() self.dialog = gaupol.TimeTransformDialog( self.application.window, self.application) self.dialog.show()
otsaloma/gaupol
gaupol/dialogs/test/test_position_transform.py
Python
gpl-3.0
1,527
package com.kinztech.os.network.codec.game.decode; import com.kinztech.os.game.node.entity.player.Player; import com.kinztech.os.network.protocol.PacketDefinition; import com.kinztech.os.utilities.RSBuffer; /** * Created by Allen Kinzalow on 5/25/2015. */ public interface DecodedPacket { void decode(Player player, RSBuffer in, PacketDefinition definition, int size); }
kinztechcom/OSRS-Server
src/com/kinztech/os/network/codec/game/decode/DecodedPacket.java
Java
gpl-3.0
382
/****************************************************************************** * The MIT License * * Copyright (c) 2011 LeafLabs, LLC. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *****************************************************************************/ /** * @file board.cpp for STM32 Nucleo-F103RB * @original author Grégoire Passault <g.passault@gmail.com> * @brief Nucleo board file * edited and tested by Matthias Diro, Release Date: 27.01.2015 * there are some solderings neccessary for complete compatibility * consider the Nucleo User manual for: * OSC clock: clock must be driven either from "MCO from ST-Link" or Oscillator from external PF0/PD0/PH0. Soldering is neccessary if board number is MB1136 C-01, see -> 5.7 OSC clock * USART: If PA2/PA3 needed, solder bridges must be changed. see -> 5.8 USART communication */ //#include <board/board.h> // For this board's header file //#include <wirish_types.h> // For stm32_pin_info and its contents // (these go into PIN_MAP). //#include "boards_private.h" // For PMAP_ROW(), which makes // PIN_MAP easier to read. #include <board/board.h> #include <libmaple/gpio.h> #include <libmaple/timer.h> /* Roger Clark. Added next to includes for changes to Serial */ #include <libmaple/usart.h> #include <HardwareSerial.h> #include <wirish_debug.h> #include <wirish_types.h> // boardInit(): NUCLEO rely on some remapping void boardInit(void) { afio_cfg_debug_ports(AFIO_DEBUG_SW_ONLY); // relase PC3 and PC5 on nucleo afio_remap(AFIO_REMAP_USART3_PARTIAL); // remap Serial2(USART3)PB10/PB11 // to PC10/PC11 -> don't forget to insert into gpio.h: // AFIO_REMAP_USART3_PARTIAL = AFIO_MAPR_USART3_REMAP_PARTIAL afio_remap(AFIO_REMAP_TIM2_FULL); // better PWM compatibility afio_remap(AFIO_REMAP_TIM3_PARTIAL);// better PWM compatibility } /* namespace wirish { namespace priv { static stm32f1_rcc_pll_data pll_data = {RCC_PLLMUL_9}; rcc_clk w_board_pll_in_clk = RCC_CLK_HSI; rcc_pll_cfg w_board_pll_cfg = {RCC_PLLSRC_HSI_DIV_2, &pll_data}; } } */ // Pin map: this lets the basic I/O functions (digitalWrite(), // analogRead(), pwmWrite()) translate from pin numbers to STM32 // peripherals. // // PMAP_ROW() lets us specify a row (really a struct stm32_pin_info) // in the pin map. Its arguments are: // // - GPIO device for the pin (&gpioa, etc.) // - GPIO bit for the pin (0 through 15) // - Timer device, or NULL if none // - Timer channel (1 to 4, for PWM), or 0 if none // - ADC device, or NULL if none // - ADC channel, or ADCx if none // gpioX, PINbit, TIMER/NULL, timerch/0, &adc1/NULL, adcsub/0 // gpioX, TIMER/NULL, &adc1/NULL, PINbit, timerch/0, adcsub/0 // 0 1 2 3 4 5 // 0 3 1 4 2 5 // 0 1 3 4 2 5 // 0 1 2 4 2 5 extern const stm32_pin_info PIN_MAP[BOARD_NR_GPIO_PINS] = { /* Arduino-like header, right connectors */ {&gpioa, NULL, &adc1, 3, 0, 3}, /* D0/PA3 */ {&gpioa, NULL, &adc1, 2, 0, 2}, /* D1/PA2 */ {&gpioa, &timer1, NULL, 10, 3, ADCx}, /* D2/PA10 */ {&gpiob, &timer2, NULL, 3, 2, ADCx}, /* D3/PB3 */ {&gpiob, &timer3, NULL, 5, 2, ADCx}, /* D4/PB5 */ {&gpiob, &timer3, NULL, 4, 1, ADCx}, /* D5/PB4 */ {&gpiob, &timer2, NULL, 10, 3, ADCx}, /* D6/PB10 */ {&gpioa, &timer1, NULL, 8, 1, ADCx}, /* D7/PA8 */ {&gpioa, &timer1, NULL, 9, 2, ADCx}, /* D8/PA9 */ {&gpioc, NULL, NULL, 7, 0, ADCx}, /* D9/PC7 */ {&gpiob, &timer4, NULL, 6, 1, ADCx}, /* D10/PB6 */ {&gpioa, NULL, &adc1, 7, 0, 7}, /* D11/PA7 */ {&gpioa, NULL, &adc1, 6, 0, 6}, /* D12/PA6 */ {&gpioa, NULL, NULL, 5, 0, ADCx}, /* D13/PA5 LED - no &adc12_IN5 !*/ {&gpiob, &timer4, NULL, 9, 4, ADCx}, /* D14/PB9 */ {&gpiob, &timer4, NULL, 8, 3, ADCx}, /* D15/PB8 */ {&gpioa, NULL, &adc1, 0, 0, 0}, /* D16/A0/PA0 */ {&gpioa, NULL, &adc1, 1, 0, 1}, /* D17/A1/PA1 */ {&gpioa, NULL, &adc1, 4, 0, 4}, /* D18/A2/PA4 */ {&gpiob, &timer3, &adc1, 0, 3, 8}, /* D19/A3/PB0 */ {&gpioc, NULL, &adc1, 1, 0, 11}, /* D20/A4/PC1 */ {&gpioc, NULL, &adc1, 0, 0, 10}, /* D21/A5/PC0 */ {&gpioc, NULL, NULL, 10, 0, ADCx}, /* D22/PC10 */ {&gpioc, NULL, NULL, 12, 0, ADCx}, /* D23/PC12 */ {&gpiob, &timer4, NULL, 7, 2, ADCx}, /* D24/PB7 */ {&gpioc, NULL, NULL, 13, 0, ADCx}, /* D25/PC13 USER BLUE BUTTON */ {&gpioc, NULL, NULL, 14, 0, ADCx}, /* D26/PC14 */ {&gpioc, NULL, NULL, 15, 0, ADCx}, /* D27/PC15 */ {&gpioc, NULL, &adc1, 2, 0, 12}, /* D28/PC2 */ {&gpioc, NULL, &adc1, 3, 0, 13}, /* D29/PC3 */ {&gpioc, NULL, NULL, 11, 0, ADCx}, /* D30/PC11 */ {&gpiod, NULL, NULL, 2, 0, ADCx}, /* D31/PD2 */ {&gpioc, NULL, NULL, 9, 0, ADCx}, /* D32/PC9 */ {&gpioc, NULL, NULL, 8, 0, ADCx}, /* D33/PC8 */ {&gpioc, NULL, NULL, 6, 0, ADCx}, /* D34/PC6 */ {&gpioc, NULL, &adc1, 5, 0, 15}, /* D35/PC5 */ {&gpioa, NULL, NULL, 12, 0, ADCx}, /* D36/PA12 */ {&gpioa, &timer1, NULL, 11, 4, ADCx}, /* D37/PA11 */ {&gpiob, NULL, NULL, 12, 0, ADCx}, /* D38/PB12 */ {&gpiob, &timer2, NULL, 11, 4, ADCx}, /* D39/PB11 PWM-not working?*/ {&gpiob, NULL, NULL, 2, 0, ADCx}, /* D40/PB2 BOOT1 !!*/ {&gpiob, &timer3, &adc1, 1, 4, 9}, /* D41/PB1 */ {&gpiob, NULL, NULL, 15, 0, ADCx}, /* D42/PB15 */ {&gpiob, NULL, NULL, 14, 0, ADCx}, /* D43/PB14 */ {&gpiob, NULL, NULL, 13, 0, ADCx}, /* D44/PB13 */ {&gpioc, NULL, &adc1, 4, 0, 14}, /* D45/PC4 */ // PMAP_ROW(&gpioa, 13, NULL, 0, NULL, ADCx), /* D41/PA13 do not use*/ // PMAP_ROW(&gpioa, 14, NULL, 0, NULL, ADCx), /* D42/PA14 do not use*/ // PMAP_ROW(&gpioa, 15, &timer2, 1, NULL, ADCx), /* D43/PA15 do not use*/ }; // Array of pins you can use for pwmWrite(). Keep it in Flash because // it doesn't change, and so we don't waste RAM. extern const uint8 boardPWMPins[] __FLASH__ = { 2,3,5,6,7,8,10,14,15,19,24,37,39,41 }; // Array of pins you can use for analogRead(). extern const uint8 boardADCPins[] __FLASH__ = { 0,1,11,12,16,17,18,19,20,21,28,29,35,41,45 }; // Array of pins that the board uses for something special. Other than // the button and the LED, it's usually best to leave these pins alone // unless you know what you're doing. /* remappings Infos ************************************* Bit 12 TIM4_REMAP: TIM4 remapping This bit is set and cleared by software. It controls the mapping of TIM4 channels 1 to 4 onto the GPIO ports. 0: No remap (TIM4_CH1/PB6, TIM4_CH2/PB7, TIM4_CH3/PB8, TIM4_CH4/PB9) 1: Full remap (TIM4_CH1/PD12, TIM4_CH2/ ************************************* Bits 11:10 TIM3_REMAP[1:0]: TIM3 remapping These bits are set and cleared by software. They control the mapping of TIM3 channels 1 to 4 on the GPIO ports. 00: No remap (CH1/PA6, CH2/PA7, CH3/PB0, CH4/PB1) 01: Not used 10: Partial remap (CH1/PB4, CH2/PB5, CH3/PB0, CH4/PB1) 11: Full remap (CH1/PC6, CH2/PC7, CH3/PC8, CH4/PC9) Note: TIM3_ETR on PE0 is not re-mapped. ************************************* Bits 9:8 TIM2_REMAP[1:0]: TIM2 remapping These bits are set and cleared by software. They control the mapping of TIM2 channels 1 to 4 and external trigger (ETR) on the GPIO ports. 00: No remap (CH1/ETR/PA0, CH2/PA1, CH3/PA2, CH4/PA3) 01: Partial remap (CH1/ETR/PA15, CH2/PB3, CH3/PA2, CH4/PA3) 10: Partial remap (CH1/ETR/PA0, CH2/PA1, CH3/PB10, CH4/PB11) 11: Full remap (CH1/ETR/PA15, CH2/PB3, CH3/PB10, CH4/PB11) ************************************* Bits 7:6 TIM1_REMAP[1:0]: TIM1 remapping These bits are set and cleared by software. They control the mapping of TIM1 channels 1 to 4, 1N to 3N, external trigger (ETR) and Break input (BKIN) on the GPIO ports. 00: No remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PB12, CH1N/PB13, CH2N/PB14, CH3N/PB15) 01: Partial remap (ETR/PA12, CH1/PA8, CH2/PA9, CH3/PA10, CH4/PA11, BKIN/PA6, CH1N/PA7, CH2N/PB0, CH3N/PB1) 10: not used 11: Full remap (ETR/PE7, CH1/PE9, CH2/PE11, CH3/PE13, CH4/PE14, BKIN/PE15, CH1N/PE8, CH2N/PE10, CH3N/PE12) ************************************* Bits 5:4 USART3_REMAP[1:0]: USART3 remapping These bits are set and cleared by software. They control the mapping of USART3 CTS, RTS,CK,TX and RX alternate functions on the GPIO ports. 00: No remap (TX/PB10, RX/PB11, CK/PB12, CTS/PB13, RTS/PB14) 01: Partial remap (TX/PC10, RX/PC11, CK/PC12, CTS/PB13, RTS/PB14) 10: not used 11: Full remap (TX/PD8, RX/PD9, CK/PD10, CTS/PD11, RTS/PD12) ************************************* Bit 3 USART2_REMAP: USART2 remapping This bit is set and cleared by software. It controls the mapping of USART2 CTS, RTS,CK,TX and RX alternate functions on the GPIO ports. 0: No remap (CTS/PA0, RTS/PA1, TX/PA2, RX/PA3, CK/PA4) 1: Remap (CTS/PD3, RTS/PD4, TX/PD5, RX/PD6, CK/PD7) ************************************* Bit 2 USART1_REMAP: USART1 remapping This bit is set and cleared by software. It controls the mapping of USART1 TX and RX alternate functions on the GPIO ports. 0: No remap (TX/PA9, RX/PA10) 1: Remap (TX/PB6, RX/PB7) ************************************* Bit 1 I2C1_REMAP: I2C1 remapping This bit is set and cleared by software. It controls the mapping of I2C1 SCL and SDA alternate functions on the GPIO ports. 0: No remap (SCL/PB6, SDA/PB7) 1: Remap (SCL/PB8, SDA/PB9) ************************************* Bit 0 SPI1_REMAP: SPI1 remapping This bit is set and cleared by software. It controls the mapping of SPI1 NSS, SCK, MISO, MOSI alternate functions on the GPIO ports. 0: No remap (NSS/PA4, SCK/PA5, MISO/PA6, MOSI/PA7) 1: Remap (NSS/PA15, SCK/PB3, MISO/PB4, MOSI/PB5) */ /* * Roger Clark * * 2015/05/28 * * Moved definitions for Hardware Serial devices from HardwareSerial.cpp so that each board can define which Arduino "Serial" instance * Maps to which hardware serial port on the microprocessor */ #ifdef SERIAL_USB DEFINE_HWSERIAL(Serial1, 1); DEFINE_HWSERIAL(Serial2, 2); DEFINE_HWSERIAL(Serial3, 3); #else DEFINE_HWSERIAL(Serial, 3);// Use HW Serial 2 as "Serial" DEFINE_HWSERIAL(Serial1, 2); DEFINE_HWSERIAL(Serial2, 1); #endif
AtDinesh/Arduino_progs
Arduino_STM32/STM32F1/variants/nucleo_f103rb/board.cpp
C++
gpl-3.0
11,487
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); exports.__esModule = true; var communication_1 = require("../../bibliotheque/communication"); var TypeMessageChat; (function (TypeMessageChat) { TypeMessageChat[TypeMessageChat["COM"] = 0] = "COM"; TypeMessageChat[TypeMessageChat["TRANSIT"] = 1] = "TRANSIT"; TypeMessageChat[TypeMessageChat["AR"] = 2] = "AR"; TypeMessageChat[TypeMessageChat["ERREUR_CONNEXION"] = 3] = "ERREUR_CONNEXION"; TypeMessageChat[TypeMessageChat["ERREUR_EMET"] = 4] = "ERREUR_EMET"; TypeMessageChat[TypeMessageChat["ERREUR_DEST"] = 5] = "ERREUR_DEST"; TypeMessageChat[TypeMessageChat["ERREUR_TYPE"] = 6] = "ERREUR_TYPE"; TypeMessageChat[TypeMessageChat["INTERDICTION"] = 7] = "INTERDICTION"; })(TypeMessageChat = exports.TypeMessageChat || (exports.TypeMessageChat = {})); var MessageChat = (function (_super) { __extends(MessageChat, _super); function MessageChat() { return _super !== null && _super.apply(this, arguments) || this; } MessageChat.prototype.net = function () { var msg = this.enJSON(); var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }; return JSON.stringify({ type: TypeMessageChat[msg.type], date: (new Date(msg.date)).toLocaleString("fr-FR", options), de: msg.emetteur, à: msg.destinataire, contenu: msg.contenu }); }; return MessageChat; }(communication_1.Message)); exports.MessageChat = MessageChat; function creerMessageErreurConnexion(emetteur, messageErreur) { return new MessageChat({ "emetteur": emetteur, "destinataire": emetteur, "type": TypeMessageChat.ERREUR_CONNEXION, "contenu": messageErreur, "date": new Date() }); } exports.creerMessageErreurConnexion = creerMessageErreurConnexion; function creerMessageCommunication(emetteur, destinataire, texte) { return new MessageChat({ "emetteur": emetteur, "destinataire": destinataire, "type": TypeMessageChat.COM, "contenu": texte, "date": new Date() }); } exports.creerMessageCommunication = creerMessageCommunication; function creerMessageRetourErreur(original, codeErreur, messageErreur) { return new MessageChat({ "emetteur": original.enJSON().emetteur, "destinataire": original.enJSON().destinataire, "type": codeErreur, "contenu": messageErreur, "date": original.enJSON().date }); } exports.creerMessageRetourErreur = creerMessageRetourErreur; function creerMessageTransit(msg) { return new MessageChat({ "emetteur": msg.enJSON().emetteur, "destinataire": msg.enJSON().destinataire, "type": TypeMessageChat.TRANSIT, "contenu": msg.enJSON().contenu, "date": msg.enJSON().date }); } exports.creerMessageTransit = creerMessageTransit; function creerMessageAR(msg) { return new MessageChat({ "emetteur": msg.enJSON().emetteur, "destinataire": msg.enJSON().destinataire, "type": TypeMessageChat.AR, "contenu": msg.enJSON().contenu, "date": msg.enJSON().date }); } exports.creerMessageAR = creerMessageAR; var SommetChat = (function (_super) { __extends(SommetChat, _super); function SommetChat() { return _super !== null && _super.apply(this, arguments) || this; } SommetChat.prototype.net = function () { var msg = this.enJSON(); return JSON.stringify({ nom: msg.pseudo + "(" + msg.id + ")" }); }; return SommetChat; }(communication_1.Sommet)); exports.SommetChat = SommetChat; function fabriqueSommetChat(s) { return new SommetChat(s); } exports.fabriqueSommetChat = fabriqueSommetChat; function creerAnneauChat(noms) { var assembleur = new communication_1.AssemblageReseauEnAnneau(noms.length); noms.forEach(function (nom, i, tab) { var s = new SommetChat({ id: "id-" + i, pseudo: tab[i] }); assembleur.ajouterSommet(s); }); return assembleur.assembler(); } exports.creerAnneauChat = creerAnneauChat; //# sourceMappingURL=chat.js.map
hgrall/merite
src/communication/v0/typeScript/build/tchat/commun/chat.js
JavaScript
gpl-3.0
4,687
package pl.llp.aircasting.screens.common.base; import android.app.ProgressDialog; /** * Created by IntelliJ IDEA. * User: obrok * Date: 1/16/12 * Time: 12:03 PM */ public interface ActivityWithProgress { public static final int SPINNER_DIALOG = 6355; public ProgressDialog showProgressDialog(int progressStyle, SimpleProgressTask task); public void hideProgressDialog(); }
HabitatMap/AirCastingAndroidClient
src/main/java/pl/llp/aircasting/screens/common/base/ActivityWithProgress.java
Java
gpl-3.0
394
/** * This file is part of MythTV Android Frontend * * MythTV Android Frontend 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. * * MythTV Android Frontend 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 MythTV Android Frontend. If not, see <http://www.gnu.org/licenses/>. * * This software can be found at <https://github.com/MythTV-Clients/MythTV-Android-Frontend/> */ package org.mythtv.client.ui.preferences; import org.mythtv.R; import org.mythtv.client.ui.AbstractMythtvFragmentActivity; import org.mythtv.client.ui.preferences.LocationProfile.LocationType; import org.mythtv.db.preferences.PlaybackProfileConstants; import org.mythtv.db.preferences.PlaybackProfileDaoHelper; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; /** * @author Daniel Frey * */ public class PlaybackProfileEditor extends AbstractMythtvFragmentActivity { private static final String TAG = PlaybackProfileEditor.class.getSimpleName(); private PlaybackProfileDaoHelper mPlaybackProfileDaoHelper = PlaybackProfileDaoHelper.getInstance(); private PlaybackProfile profile; @Override public void onCreate( Bundle savedInstanceState ) { Log.v( TAG, "onCreate : enter" ); super.onCreate( savedInstanceState ); setContentView( this.getLayoutInflater().inflate( R.layout.preference_playback_profile_editor, null ) ); setupSaveButtonEvent( R.id.btnPreferencePlaybackProfileSave ); setupCancelButtonEvent( R.id.btnPreferencePlaybackProfileCancel ); int id = getIntent().getIntExtra( PlaybackProfileConstants._ID, -1 ); profile = mPlaybackProfileDaoHelper.findOne( this, (long) id ); if( null == profile ) { profile = new PlaybackProfile(); profile.setId( id ); profile.setType( LocationType.valueOf( getIntent().getStringExtra( PlaybackProfileConstants.FIELD_TYPE ) ) ); profile.setName( getIntent().getStringExtra( PlaybackProfileConstants.FIELD_NAME ) ); profile.setWidth( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_WIDTH, -1 ) ); profile.setHeight( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_HEIGHT, -1 ) ); profile.setVideoBitrate( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_BITRATE, -1 ) ); profile.setAudioBitrate( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_AUDIO_BITRATE, -1 ) ); profile.setAudioSampleRate( getIntent().getIntExtra( PlaybackProfileConstants.FIELD_SAMPLE_RATE, -1 ) ); profile.setSelected( 0 != getIntent().getIntExtra( PlaybackProfileConstants.FIELD_SELECTED, 0 ) ); } setUiFromPlaybackProfile(); Log.v( TAG, "onCreate : exit" ); } // internal helpers private void setUiFromPlaybackProfile() { Log.v( TAG, "setUiFromPlaybackProfile : enter" ); setName( profile.getName() ); setWidth( "" + profile.getWidth() ); setHeight( "" + profile.getHeight() ); setVideoBitrate( "" + profile.getVideoBitrate() ); setAudioBitrate( "" + profile.getAudioBitrate() ); setSampleRate( "" + profile.getAudioSampleRate() ); Log.v( TAG, "setUiFromPlaybackProfile : exit" ); } private final String getName() { return getTextBoxText( R.id.preference_playback_profile_edit_text_name ); } private final void setName( String name ) { setTextBoxText( R.id.preference_playback_profile_edit_text_name, name ); } private final String getWidth() { return getTextBoxText( R.id.preference_playback_profile_edit_text_width ); } private final void setWidth( String width ) { setTextBoxText( R.id.preference_playback_profile_edit_text_width, width ); } private final String getHeight() { return getTextBoxText( R.id.preference_playback_profile_edit_text_height ); } private final void setHeight( String height ) { setTextBoxText( R.id.preference_playback_profile_edit_text_height, height ); } private final String getVideoBitrate() { return getTextBoxText( R.id.preference_playback_profile_edit_text_video_bitrate ); } private final void setVideoBitrate( String videoBitrate ) { setTextBoxText( R.id.preference_playback_profile_edit_text_video_bitrate, videoBitrate ); } private final String getAudioBitrate() { return getTextBoxText( R.id.preference_playback_profile_edit_text_audio_bitrate ); } private final void setAudioBitrate( String audioBitrate ) { setTextBoxText( R.id.preference_playback_profile_edit_text_audio_bitrate, audioBitrate ); } private final String getSampleRate() { return getTextBoxText( R.id.preference_playback_profile_edit_text_sample_rate ); } private final void setSampleRate( String sampleRate ) { setTextBoxText( R.id.preference_playback_profile_edit_text_sample_rate, sampleRate ); } private final String getTextBoxText( int textBoxViewId ) { final EditText text = (EditText) findViewById( textBoxViewId ); return text.getText().toString(); } private final void setTextBoxText( int textBoxViewId, String text ) { final EditText textBox = (EditText) findViewById( textBoxViewId ); textBox.setText( text ); } private final void setupSaveButtonEvent( int buttonViewId ) { Log.v( TAG, "setupSaveButtonEvent : enter" ); final Button button = (Button) this.findViewById( buttonViewId ); button.setOnClickListener( new OnClickListener() { public void onClick( View v ) { Log.v( TAG, "setupSaveButtonEvent.onClick : enter" ); saveAndExit(); Log.v( TAG, "setupSaveButtonEvent.onClick : exit" ); } }); Log.v( TAG, "setupSaveButtonEvent : exit" ); } private final void setupCancelButtonEvent( int buttonViewId ) { Log.v( TAG, "setupCancelButtonEvent : enter" ); final Button button = (Button) this.findViewById( buttonViewId ); button.setOnClickListener( new OnClickListener() { public void onClick( View v ) { Log.v( TAG, "setupCancelButtonEvent.onClick : enter" ); finish(); Log.v( TAG, "setupCancelButtonEvent.onClick : exit" ); } }); Log.v( TAG, "setupCancelButtonEvent : enter" ); } private void saveAndExit() { Log.v( TAG, "saveAndExit : enter" ); if( save() ) { Log.v( TAG, "saveAndExit : save completed successfully" ); finish(); } Log.v( TAG, "saveAndExit : exit" ); } private boolean save() { Log.v( TAG, "save : enter" ); boolean retVal = false; if( null == profile ) { Log.v( TAG, "save : creating new Playback Profile" ); profile = new PlaybackProfile(); } profile.setName( getName() ); profile.setWidth( Integer.parseInt( getWidth() ) ); profile.setHeight( Integer.parseInt( getHeight() ) ); profile.setVideoBitrate( Integer.parseInt( getVideoBitrate() ) ); profile.setAudioBitrate( Integer.parseInt( getAudioBitrate() ) ); profile.setAudioSampleRate( Integer.parseInt( getSampleRate() ) ); AlertDialog.Builder builder = new AlertDialog.Builder( this ); builder.setTitle( R.string.preference_edit_error_dialog_title ); builder.setNeutralButton( R.string.btn_ok, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which ) { } }); if( "".equals( profile.getName().trim() ) ) { Log.v( TAG, "save : name contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_name_error_invalid ); builder.show(); } else if( profile.getWidth() < 1 ) { Log.v( TAG, "save : width contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_width_error_invalid ); builder.show(); } else if( profile.getHeight() < 1 ) { Log.v( TAG, "save : height contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_height_error_invalid ); builder.show(); } else if( profile.getVideoBitrate() < 1 ) { Log.v( TAG, "save : video bitrate contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_video_bitrate_error_invalid ); builder.show(); } else if( profile.getAudioBitrate() < 1 ) { Log.v( TAG, "save : audio bitrate contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_audio_bitrate_error_invalid ); builder.show(); } else if( profile.getAudioSampleRate() < 1 ) { Log.v( TAG, "save : sample rate contains errors" ); builder.setMessage( R.string.preference_playback_profile_text_view_sample_rate_error_invalid ); builder.show(); } else { Log.v( TAG, "save : proceeding to save" ); if( profile.getId() != -1 ) { Log.v( TAG, "save : updating existing playback profile" ); retVal = mPlaybackProfileDaoHelper.save( this, profile ); } } Log.v( TAG, "save : exit" ); return retVal; } }
MythTV-Clients/MythTV-Android-Frontend
src/org/mythtv/client/ui/preferences/PlaybackProfileEditor.java
Java
gpl-3.0
9,195
/* * Son of Mars * * Copyright (c) 2015-2016, Team Son of Mars * * 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 "Hud.h" #include <cassert> #include <stdlib.h> #include "local/config.h" Hud::Hud(game::EventManager& events, game::ResourceManager& resources,game::WindowGeometry& geometry) : m_geometry(geometry) , m_timeElapsed(0.0f) , m_font(nullptr) , m_characterMaxHealth(0) , m_characterHealth(0) , m_characterGold(0) , m_characterDamage(0) , m_characterArmor(0) , m_characterRegenValue(0) , m_characterRegenRate(0) , m_display(false) { m_font=resources.getFont("GRECOromanLubedWrestling.ttf"); assert(m_font!=nullptr); // Register event events.registerHandler<CharacterStatsEvent>(&Hud::onCharacterStatsEvent, this); } Hud::~Hud() { } void Hud::update(const float dt) { } void Hud::render(sf::RenderWindow& window) { if(m_display==true) { sf::RectangleShape baseHud; baseHud.setFillColor(sf::Color(0,0,0,128)); baseHud.setPosition(sf::Vector2f(0.0f,0.0f)); baseHud.setSize({m_geometry.getXFromRight(0),m_geometry.getYRatio(0.05f,0.0f)}); sf::Text strHealth; //Set the characteristics of strHealth strHealth.setFont(*m_font); strHealth.setCharacterSize(25); strHealth.setColor(sf::Color::Red); strHealth.setPosition(0.0f,0.0f); strHealth.setString("Health: "+std::to_string(m_characterHealth)+"/"+std::to_string(m_characterMaxHealth)+" (A)"); sf::Text strGold; //Set the characteristics of strGold strGold.setFont(*m_font); strGold.setCharacterSize(25); strGold.setColor(sf::Color::Green); strGold.setPosition(250.0f,0.0f); strGold.setString("Sesterces: "+std::to_string(m_characterGold)); sf::Text strDamage; //Set the characteristics of strDamage strDamage.setFont(*m_font); strDamage.setCharacterSize(25); strDamage.setColor(sf::Color::Blue); strDamage.setPosition(400.0f,0.0f); strDamage.setString("Damages: "+std::to_string(m_characterDamage)+" (E)"); sf::Text strArmor; //Set the characteristics of strDamage strArmor.setFont(*m_font); strArmor.setCharacterSize(25); strArmor.setColor(sf::Color::White); strArmor.setPosition(600.0f,0.0f); strArmor.setString("Armor: "+std::to_string(m_characterArmor)); sf::Text strRegen; //Set the characteristics of strRegen strRegen.setFont(*m_font); strRegen.setCharacterSize(25); strRegen.setColor(sf::Color::Cyan); strRegen.setPosition(720.0f,0.0f); strRegen.setString("Regeneration: "+std::to_string(m_characterRegenValue)+" over "+std::to_string(m_characterRegenRate)+" seconds (R)"); window.draw(baseHud); window.draw(strHealth); window.draw(strGold); window.draw(strDamage); window.draw(strArmor); window.draw(strRegen); } } game::EventStatus Hud::onCharacterStatsEvent(game::EventType type, game::Event *event) { auto statsEvent = static_cast<CharacterStatsEvent *>(event); m_characterHealth = statsEvent->characterHealth; m_characterMaxHealth = statsEvent->characterMaxHealth; m_characterGold = statsEvent->characterGold; m_characterDamage = statsEvent->characterDamage; m_characterArmor = statsEvent->characterArmor; m_characterRegenValue = statsEvent->characterRegenValue; m_characterRegenRate = statsEvent->characterRegenRate; return game::EventStatus::KEEP; } void Hud::switchDisplay() { if(m_display==true) { m_display=false; } else { m_display=true; } }
DeadPixelsSociety/SonOfMars
src/local/Hud.cc
C++
gpl-3.0
4,307
#!/usr/bin/python # # Copyright 2016 Red Hat | Ansible # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: docker_container short_description: manage docker containers description: - Manage the life cycle of docker containers. - Supports check mode. Run with C(--check) and C(--diff) to view config difference and list of actions to be taken. version_added: "2.1" notes: - For most config changes, the container needs to be recreated, i.e. the existing container has to be destroyed and a new one created. This can cause unexpected data loss and downtime. You can use the I(comparisons) option to prevent this. - If the module needs to recreate the container, it will only use the options provided to the module to create the new container (except I(image)). Therefore, always specify *all* options relevant to the container. - When I(restart) is set to C(true), the module will only restart the container if no config changes are detected. Please note that several options have default values; if the container to be restarted uses different values for these options, it will be recreated instead. The options with default values which can cause this are I(auto_remove), I(detach), I(init), I(interactive), I(memory), I(paused), I(privileged), I(read_only) and I(tty). This behavior can be changed by setting I(container_default_behavior) to C(no_defaults), which will be the default value from Ansible 2.14 on. options: auto_remove: description: - Enable auto-removal of the container on daemon side when the container's process exits. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool version_added: "2.4" blkio_weight: description: - Block IO (relative weight), between 10 and 1000. type: int capabilities: description: - List of capabilities to add to the container. type: list elements: str cap_drop: description: - List of capabilities to drop from the container. type: list elements: str version_added: "2.7" cleanup: description: - Use with I(detach=false) to remove the container after successful execution. type: bool default: no version_added: "2.2" command: description: - Command to execute when the container starts. A command may be either a string or a list. - Prior to version 2.4, strings were split on commas. type: raw comparisons: description: - Allows to specify how properties of existing containers are compared with module options to decide whether the container should be recreated / updated or not. - Only options which correspond to the state of a container as handled by the Docker daemon can be specified, as well as C(networks). - Must be a dictionary specifying for an option one of the keys C(strict), C(ignore) and C(allow_more_present). - If C(strict) is specified, values are tested for equality, and changes always result in updating or restarting. If C(ignore) is specified, changes are ignored. - C(allow_more_present) is allowed only for lists, sets and dicts. If it is specified for lists or sets, the container will only be updated or restarted if the module option contains a value which is not present in the container's options. If the option is specified for a dict, the container will only be updated or restarted if the module option contains a key which isn't present in the container's option, or if the value of a key present differs. - The wildcard option C(*) can be used to set one of the default values C(strict) or C(ignore) to *all* comparisons which are not explicitly set to other values. - See the examples for details. type: dict version_added: "2.8" container_default_behavior: description: - Various module options used to have default values. This causes problems with containers which use different values for these options. - The default value is C(compatibility), which will ensure that the default values are used when the values are not explicitly specified by the user. - From Ansible 2.14 on, the default value will switch to C(no_defaults). To avoid deprecation warnings, please set I(container_default_behavior) to an explicit value. - This affects the I(auto_remove), I(detach), I(init), I(interactive), I(memory), I(paused), I(privileged), I(read_only) and I(tty) options. type: str choices: - compatibility - no_defaults version_added: "2.10" cpu_period: description: - Limit CPU CFS (Completely Fair Scheduler) period. - See I(cpus) for an easier to use alternative. type: int cpu_quota: description: - Limit CPU CFS (Completely Fair Scheduler) quota. - See I(cpus) for an easier to use alternative. type: int cpus: description: - Specify how much of the available CPU resources a container can use. - A value of C(1.5) means that at most one and a half CPU (core) will be used. type: float version_added: '2.10' cpuset_cpus: description: - CPUs in which to allow execution C(1,3) or C(1-3). type: str cpuset_mems: description: - Memory nodes (MEMs) in which to allow execution C(0-3) or C(0,1). type: str cpu_shares: description: - CPU shares (relative weight). type: int detach: description: - Enable detached mode to leave the container running in background. - If disabled, the task will reflect the status of the container run (failed if the command failed). - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(yes). type: bool devices: description: - List of host device bindings to add to the container. - "Each binding is a mapping expressed in the format C(<path_on_host>:<path_in_container>:<cgroup_permissions>)." type: list elements: str device_read_bps: description: - "List of device path and read rate (bytes per second) from device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit in format C(<number>[<unit>])." - "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - "Omitting the unit defaults to bytes." type: str required: yes version_added: "2.8" device_write_bps: description: - "List of device and write rate (bytes per second) to device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit in format C(<number>[<unit>])." - "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - "Omitting the unit defaults to bytes." type: str required: yes version_added: "2.8" device_read_iops: description: - "List of device and read rate (IO per second) from device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit." - "Must be a positive integer." type: int required: yes version_added: "2.8" device_write_iops: description: - "List of device and write rate (IO per second) to device." type: list elements: dict suboptions: path: description: - Device path in the container. type: str required: yes rate: description: - "Device read limit." - "Must be a positive integer." type: int required: yes version_added: "2.8" dns_opts: description: - List of DNS options. type: list elements: str dns_servers: description: - List of custom DNS servers. type: list elements: str dns_search_domains: description: - List of custom DNS search domains. type: list elements: str domainname: description: - Container domainname. type: str version_added: "2.5" env: description: - Dictionary of key,value pairs. - Values which might be parsed as numbers, booleans or other types by the YAML parser must be quoted (e.g. C("true")) in order to avoid data loss. type: dict env_file: description: - Path to a file, present on the target, containing environment variables I(FOO=BAR). - If variable also present in I(env), then the I(env) value will override. type: path version_added: "2.2" entrypoint: description: - Command that overwrites the default C(ENTRYPOINT) of the image. type: list elements: str etc_hosts: description: - Dict of host-to-IP mappings, where each host name is a key in the dictionary. Each host name will be added to the container's C(/etc/hosts) file. type: dict exposed_ports: description: - List of additional container ports which informs Docker that the container listens on the specified network ports at runtime. - If the port is already exposed using C(EXPOSE) in a Dockerfile, it does not need to be exposed again. type: list elements: str aliases: - exposed - expose force_kill: description: - Use the kill command when stopping a running container. type: bool default: no aliases: - forcekill groups: description: - List of additional group names and/or IDs that the container process will run as. type: list elements: str healthcheck: description: - Configure a check that is run to determine whether or not containers for this service are "healthy". - "See the docs for the L(HEALTHCHECK Dockerfile instruction,https://docs.docker.com/engine/reference/builder/#healthcheck) for details on how healthchecks work." - "I(interval), I(timeout) and I(start_period) are specified as durations. They accept duration as a string in a format that look like: C(5h34m56s), C(1m30s) etc. The supported units are C(us), C(ms), C(s), C(m) and C(h)." type: dict suboptions: test: description: - Command to run to check health. - Must be either a string or a list. If it is a list, the first item must be one of C(NONE), C(CMD) or C(CMD-SHELL). type: raw interval: description: - Time between running the check. - The default used by the Docker daemon is C(30s). type: str timeout: description: - Maximum time to allow one check to run. - The default used by the Docker daemon is C(30s). type: str retries: description: - Consecutive number of failures needed to report unhealthy. - The default used by the Docker daemon is C(3). type: int start_period: description: - Start period for the container to initialize before starting health-retries countdown. - The default used by the Docker daemon is C(0s). type: str version_added: "2.8" hostname: description: - The container's hostname. type: str ignore_image: description: - When I(state) is C(present) or C(started), the module compares the configuration of an existing container to requested configuration. The evaluation includes the image version. If the image version in the registry does not match the container, the container will be recreated. You can stop this behavior by setting I(ignore_image) to C(True). - "*Warning:* This option is ignored if C(image: ignore) or C(*: ignore) is specified in the I(comparisons) option." type: bool default: no version_added: "2.2" image: description: - Repository path and tag used to create the container. If an image is not found or pull is true, the image will be pulled from the registry. If no tag is included, C(latest) will be used. - Can also be an image ID. If this is the case, the image is assumed to be available locally. The I(pull) option is ignored for this case. type: str init: description: - Run an init inside the container that forwards signals and reaps processes. - This option requires Docker API >= 1.25. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool version_added: "2.6" interactive: description: - Keep stdin open after a container is launched, even if not attached. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool ipc_mode: description: - Set the IPC mode for the container. - Can be one of C(container:<name|id>) to reuse another container's IPC namespace or C(host) to use the host's IPC namespace within the container. type: str keep_volumes: description: - Retain volumes associated with a removed container. type: bool default: yes kill_signal: description: - Override default signal used to kill a running container. type: str kernel_memory: description: - "Kernel memory limit in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte). Minimum is C(4M)." - Omitting the unit defaults to bytes. type: str labels: description: - Dictionary of key value pairs. type: dict links: description: - List of name aliases for linked containers in the format C(container_name:alias). - Setting this will force container to be restarted. type: list elements: str log_driver: description: - Specify the logging driver. Docker uses C(json-file) by default. - See L(here,https://docs.docker.com/config/containers/logging/configure/) for possible choices. type: str log_options: description: - Dictionary of options specific to the chosen I(log_driver). - See U(https://docs.docker.com/engine/admin/logging/overview/) for details. type: dict aliases: - log_opt mac_address: description: - Container MAC address (e.g. 92:d0:c6:0a:29:33). type: str memory: description: - "Memory limit in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C("0"). type: str memory_reservation: description: - "Memory soft limit in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. type: str memory_swap: description: - "Total memory limit (memory + swap) in format C(<number>[<unit>]). Number is a positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. type: str memory_swappiness: description: - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. - If not set, the value will be remain the same if container exists and will be inherited from the host machine if it is (re-)created. type: int mounts: version_added: "2.9" type: list elements: dict description: - Specification for mounts to be added to the container. More powerful alternative to I(volumes). suboptions: target: description: - Path inside the container. type: str required: true source: description: - Mount source (e.g. a volume name or a host path). type: str type: description: - The mount type. - Note that C(npipe) is only supported by Docker for Windows. type: str choices: - bind - npipe - tmpfs - volume default: volume read_only: description: - Whether the mount should be read-only. type: bool consistency: description: - The consistency requirement for the mount. type: str choices: - cached - consistent - default - delegated propagation: description: - Propagation mode. Only valid for the C(bind) type. type: str choices: - private - rprivate - shared - rshared - slave - rslave no_copy: description: - False if the volume should be populated with the data from the target. Only valid for the C(volume) type. - The default value is C(false). type: bool labels: description: - User-defined name and labels for the volume. Only valid for the C(volume) type. type: dict volume_driver: description: - Specify the volume driver. Only valid for the C(volume) type. - See L(here,https://docs.docker.com/storage/volumes/#use-a-volume-driver) for details. type: str volume_options: description: - Dictionary of options specific to the chosen volume_driver. See L(here,https://docs.docker.com/storage/volumes/#use-a-volume-driver) for details. type: dict tmpfs_size: description: - "The size for the tmpfs mount in bytes in format <number>[<unit>]." - "Number is a positive integer. Unit can be one of C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - "Omitting the unit defaults to bytes." type: str tmpfs_mode: description: - The permission mode for the tmpfs mount. type: str name: description: - Assign a name to a new container or match an existing container. - When identifying an existing container name may be a name or a long or short container ID. type: str required: yes network_mode: description: - Connect the container to a network. Choices are C(bridge), C(host), C(none), C(container:<name|id>), C(<network_name>) or C(default). - "*Note* that from Ansible 2.14 on, if I(networks_cli_compatible) is C(true) and I(networks) contains at least one network, the default value for I(network_mode) will be the name of the first network in the I(networks) list. You can prevent this by explicitly specifying a value for I(network_mode), like the default value C(default) which will be used by Docker if I(network_mode) is not specified." type: str userns_mode: description: - Set the user namespace mode for the container. Currently, the only valid value are C(host) and the empty string. type: str version_added: "2.5" networks: description: - List of networks the container belongs to. - For examples of the data structure and usage see EXAMPLES below. - To remove a container from one or more networks, use the I(purge_networks) option. - Note that as opposed to C(docker run ...), M(docker_container) does not remove the default network if I(networks) is specified. You need to explicitly use I(purge_networks) to enforce the removal of the default network (and all other networks not explicitly mentioned in I(networks)). Alternatively, use the I(networks_cli_compatible) option, which will be enabled by default from Ansible 2.12 on. type: list elements: dict suboptions: name: description: - The network's name. type: str required: yes ipv4_address: description: - The container's IPv4 address in this network. type: str ipv6_address: description: - The container's IPv6 address in this network. type: str links: description: - A list of containers to link to. type: list elements: str aliases: description: - List of aliases for this container in this network. These names can be used in the network to reach this container. type: list elements: str version_added: "2.2" networks_cli_compatible: description: - "When networks are provided to the module via the I(networks) option, the module behaves differently than C(docker run --network): C(docker run --network other) will create a container with network C(other) attached, but the default network not attached. This module with I(networks: {name: other}) will create a container with both C(default) and C(other) attached. If I(purge_networks) is set to C(yes), the C(default) network will be removed afterwards." - "If I(networks_cli_compatible) is set to C(yes), this module will behave as C(docker run --network) and will *not* add the default network if I(networks) is specified. If I(networks) is not specified, the default network will be attached." - "*Note* that docker CLI also sets I(network_mode) to the name of the first network added if C(--network) is specified. For more compatibility with docker CLI, you explicitly have to set I(network_mode) to the name of the first network you're adding. This behavior will change for Ansible 2.14: then I(network_mode) will automatically be set to the first network name in I(networks) if I(network_mode) is not specified, I(networks) has at least one entry and I(networks_cli_compatible) is C(true)." - Current value is C(no). A new default of C(yes) will be set in Ansible 2.12. type: bool version_added: "2.8" oom_killer: description: - Whether or not to disable OOM Killer for the container. type: bool oom_score_adj: description: - An integer value containing the score given to the container in order to tune OOM killer preferences. type: int version_added: "2.2" output_logs: description: - If set to true, output of the container command will be printed. - Only effective when I(log_driver) is set to C(json-file) or C(journald). type: bool default: no version_added: "2.7" paused: description: - Use with the started state to pause running processes inside the container. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool pid_mode: description: - Set the PID namespace mode for the container. - Note that Docker SDK for Python < 2.0 only supports C(host). Newer versions of the Docker SDK for Python (docker) allow all values supported by the Docker daemon. type: str pids_limit: description: - Set PIDs limit for the container. It accepts an integer value. - Set C(-1) for unlimited PIDs. type: int version_added: "2.8" privileged: description: - Give extended privileges to the container. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool published_ports: description: - List of ports to publish from the container to the host. - "Use docker CLI syntax: C(8000), C(9000:8000), or C(0.0.0.0:9000:8000), where 8000 is a container port, 9000 is a host port, and 0.0.0.0 is a host interface." - Port ranges can be used for source and destination ports. If two ranges with different lengths are specified, the shorter range will be used. - "Bind addresses must be either IPv4 or IPv6 addresses. Hostnames are *not* allowed. This is different from the C(docker) command line utility. Use the L(dig lookup,../lookup/dig.html) to resolve hostnames." - A value of C(all) will publish all exposed container ports to random host ports, ignoring any other mappings. - If I(networks) parameter is provided, will inspect each network to see if there exists a bridge network with optional parameter C(com.docker.network.bridge.host_binding_ipv4). If such a network is found, then published ports where no host IP address is specified will be bound to the host IP pointed to by C(com.docker.network.bridge.host_binding_ipv4). Note that the first bridge network with a C(com.docker.network.bridge.host_binding_ipv4) value encountered in the list of I(networks) is the one that will be used. type: list elements: str aliases: - ports pull: description: - If true, always pull the latest version of an image. Otherwise, will only pull an image when missing. - "*Note:* images are only pulled when specified by name. If the image is specified as a image ID (hash), it cannot be pulled." type: bool default: no purge_networks: description: - Remove the container from ALL networks not included in I(networks) parameter. - Any default networks such as C(bridge), if not found in I(networks), will be removed as well. type: bool default: no version_added: "2.2" read_only: description: - Mount the container's root file system as read-only. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool recreate: description: - Use with present and started states to force the re-creation of an existing container. type: bool default: no restart: description: - Use with started state to force a matching container to be stopped and restarted. type: bool default: no restart_policy: description: - Container restart policy. - Place quotes around C(no) option. type: str choices: - 'no' - 'on-failure' - 'always' - 'unless-stopped' restart_retries: description: - Use with restart policy to control maximum number of restart attempts. type: int runtime: description: - Runtime to use for the container. type: str version_added: "2.8" shm_size: description: - "Size of C(/dev/shm) in format C(<number>[<unit>]). Number is positive integer. Unit can be C(B) (byte), C(K) (kibibyte, 1024B), C(M) (mebibyte), C(G) (gibibyte), C(T) (tebibyte), or C(P) (pebibyte)." - Omitting the unit defaults to bytes. If you omit the size entirely, Docker daemon uses C(64M). type: str security_opts: description: - List of security options in the form of C("label:user:User"). type: list elements: str state: description: - 'C(absent) - A container matching the specified name will be stopped and removed. Use I(force_kill) to kill the container rather than stopping it. Use I(keep_volumes) to retain volumes associated with the removed container.' - 'C(present) - Asserts the existence of a container matching the name and any provided configuration parameters. If no container matches the name, a container will be created. If a container matches the name but the provided configuration does not match, the container will be updated, if it can be. If it cannot be updated, it will be removed and re-created with the requested config.' - 'C(started) - Asserts that the container is first C(present), and then if the container is not running moves it to a running state. Use I(restart) to force a matching container to be stopped and restarted.' - 'C(stopped) - Asserts that the container is first C(present), and then if the container is running moves it to a stopped state.' - To control what will be taken into account when comparing configuration, see the I(comparisons) option. To avoid that the image version will be taken into account, you can also use the I(ignore_image) option. - Use the I(recreate) option to always force re-creation of a matching container, even if it is running. - If the container should be killed instead of stopped in case it needs to be stopped for recreation, or because I(state) is C(stopped), please use the I(force_kill) option. Use I(keep_volumes) to retain volumes associated with a removed container. - Use I(keep_volumes) to retain volumes associated with a removed container. type: str default: started choices: - absent - present - stopped - started stop_signal: description: - Override default signal used to stop the container. type: str stop_timeout: description: - Number of seconds to wait for the container to stop before sending C(SIGKILL). When the container is created by this module, its C(StopTimeout) configuration will be set to this value. - When the container is stopped, will be used as a timeout for stopping the container. In case the container has a custom C(StopTimeout) configuration, the behavior depends on the version of the docker daemon. New versions of the docker daemon will always use the container's configured C(StopTimeout) value if it has been configured. type: int trust_image_content: description: - If C(yes), skip image verification. - The option has never been used by the module. It will be removed in Ansible 2.14. type: bool default: no tmpfs: description: - Mount a tmpfs directory. type: list elements: str version_added: 2.4 tty: description: - Allocate a pseudo-TTY. - If I(container_default_behavior) is set to C(compatiblity) (the default value), this option has a default of C(no). type: bool ulimits: description: - "List of ulimit options. A ulimit is specified as C(nofile:262144:262144)." type: list elements: str sysctls: description: - Dictionary of key,value pairs. type: dict version_added: 2.4 user: description: - Sets the username or UID used and optionally the groupname or GID for the specified command. - "Can be of the forms C(user), C(user:group), C(uid), C(uid:gid), C(user:gid) or C(uid:group)." type: str uts: description: - Set the UTS namespace mode for the container. type: str volumes: description: - List of volumes to mount within the container. - "Use docker CLI-style syntax: C(/host:/container[:mode])" - "Mount modes can be a comma-separated list of various modes such as C(ro), C(rw), C(consistent), C(delegated), C(cached), C(rprivate), C(private), C(rshared), C(shared), C(rslave), C(slave), and C(nocopy). Note that the docker daemon might not support all modes and combinations of such modes." - SELinux hosts can additionally use C(z) or C(Z) to use a shared or private label for the volume. - "Note that Ansible 2.7 and earlier only supported one mode, which had to be one of C(ro), C(rw), C(z), and C(Z)." type: list elements: str volume_driver: description: - The container volume driver. type: str volumes_from: description: - List of container names or IDs to get volumes from. type: list elements: str working_dir: description: - Path to the working directory. type: str version_added: "2.4" extends_documentation_fragment: - docker - docker.docker_py_1_documentation author: - "Cove Schneider (@cove)" - "Joshua Conner (@joshuaconner)" - "Pavel Antonov (@softzilla)" - "Thomas Steinbach (@ThomasSteinbach)" - "Philippe Jandot (@zfil)" - "Daan Oosterveld (@dusdanig)" - "Chris Houseknecht (@chouseknecht)" - "Kassian Sun (@kassiansun)" - "Felix Fontein (@felixfontein)" requirements: - "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 1.8.0 (use L(docker-py,https://pypi.org/project/docker-py/) for Python 2.6)" - "Docker API >= 1.20" ''' EXAMPLES = ''' - name: Create a data container docker_container: name: mydata image: busybox volumes: - /data - name: Re-create a redis container docker_container: name: myredis image: redis command: redis-server --appendonly yes state: present recreate: yes exposed_ports: - 6379 volumes_from: - mydata - name: Restart a container docker_container: name: myapplication image: someuser/appimage state: started restart: yes links: - "myredis:aliasedredis" devices: - "/dev/sda:/dev/xvda:rwm" ports: - "8080:9000" - "127.0.0.1:8081:9001/udp" env: SECRET_KEY: "ssssh" # Values which might be parsed as numbers, booleans or other types by the YAML parser need to be quoted BOOLEAN_KEY: "yes" - name: Container present docker_container: name: mycontainer state: present image: ubuntu:14.04 command: sleep infinity - name: Stop a container docker_container: name: mycontainer state: stopped - name: Start 4 load-balanced containers docker_container: name: "container{{ item }}" recreate: yes image: someuser/anotherappimage command: sleep 1d with_sequence: count=4 - name: remove container docker_container: name: ohno state: absent - name: Syslogging output docker_container: name: myservice image: busybox log_driver: syslog log_options: syslog-address: tcp://my-syslog-server:514 syslog-facility: daemon # NOTE: in Docker 1.13+ the "syslog-tag" option was renamed to "tag" for # older docker installs, use "syslog-tag" instead tag: myservice - name: Create db container and connect to network docker_container: name: db_test image: "postgres:latest" networks: - name: "{{ docker_network_name }}" - name: Start container, connect to network and link docker_container: name: sleeper image: ubuntu:14.04 networks: - name: TestingNet ipv4_address: "172.1.1.100" aliases: - sleepyzz links: - db_test:db - name: TestingNet2 - name: Start a container with a command docker_container: name: sleepy image: ubuntu:14.04 command: ["sleep", "infinity"] - name: Add container to networks docker_container: name: sleepy networks: - name: TestingNet ipv4_address: 172.1.1.18 links: - sleeper - name: TestingNet2 ipv4_address: 172.1.10.20 - name: Update network with aliases docker_container: name: sleepy networks: - name: TestingNet aliases: - sleepyz - zzzz - name: Remove container from one network docker_container: name: sleepy networks: - name: TestingNet2 purge_networks: yes - name: Remove container from all networks docker_container: name: sleepy purge_networks: yes - name: Start a container and use an env file docker_container: name: agent image: jenkinsci/ssh-slave env_file: /var/tmp/jenkins/agent.env - name: Create a container with limited capabilities docker_container: name: sleepy image: ubuntu:16.04 command: sleep infinity capabilities: - sys_time cap_drop: - all - name: Finer container restart/update control docker_container: name: test image: ubuntu:18.04 env: arg1: "true" arg2: "whatever" volumes: - /tmp:/tmp comparisons: image: ignore # don't restart containers with older versions of the image env: strict # we want precisely this environment volumes: allow_more_present # if there are more volumes, that's ok, as long as `/tmp:/tmp` is there - name: Finer container restart/update control II docker_container: name: test image: ubuntu:18.04 env: arg1: "true" arg2: "whatever" comparisons: '*': ignore # by default, ignore *all* options (including image) env: strict # except for environment variables; there, we want to be strict - name: Start container with healthstatus docker_container: name: nginx-proxy image: nginx:1.13 state: started healthcheck: # Check if nginx server is healthy by curl'ing the server. # If this fails or timeouts, the healthcheck fails. test: ["CMD", "curl", "--fail", "http://nginx.host.com"] interval: 1m30s timeout: 10s retries: 3 start_period: 30s - name: Remove healthcheck from container docker_container: name: nginx-proxy image: nginx:1.13 state: started healthcheck: # The "NONE" check needs to be specified test: ["NONE"] - name: start container with block device read limit docker_container: name: test image: ubuntu:18.04 state: started device_read_bps: # Limit read rate for /dev/sda to 20 mebibytes per second - path: /dev/sda rate: 20M device_read_iops: # Limit read rate for /dev/sdb to 300 IO per second - path: /dev/sdb rate: 300 ''' RETURN = ''' container: description: - Facts representing the current state of the container. Matches the docker inspection output. - Note that facts are part of the registered vars since Ansible 2.8. For compatibility reasons, the facts are also accessible directly as C(docker_container). Note that the returned fact will be removed in Ansible 2.12. - Before 2.3 this was C(ansible_docker_container) but was renamed in 2.3 to C(docker_container) due to conflicts with the connection plugin. - Empty if I(state) is C(absent) - If I(detached) is C(false), will include C(Output) attribute containing any output from container run. returned: always type: dict sample: '{ "AppArmorProfile": "", "Args": [], "Config": { "AttachStderr": false, "AttachStdin": false, "AttachStdout": false, "Cmd": [ "/usr/bin/supervisord" ], "Domainname": "", "Entrypoint": null, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "ExposedPorts": { "443/tcp": {}, "80/tcp": {} }, "Hostname": "8e47bf643eb9", "Image": "lnmp_nginx:v1", "Labels": {}, "OnBuild": null, "OpenStdin": false, "StdinOnce": false, "Tty": false, "User": "", "Volumes": { "/tmp/lnmp/nginx-sites/logs/": {} }, ... }' ''' import os import re import shlex import traceback from distutils.version import LooseVersion from ansible.module_utils.common.text.formatters import human_to_bytes from ansible.module_utils.docker.common import ( AnsibleDockerClient, DifferenceTracker, DockerBaseClass, compare_generic, is_image_name_id, sanitize_result, clean_dict_booleans_for_docker_api, omit_none_from_dict, parse_healthcheck, DOCKER_COMMON_ARGS, RequestException, ) from ansible.module_utils.six import string_types try: from docker import utils from ansible.module_utils.docker.common import docker_version if LooseVersion(docker_version) >= LooseVersion('1.10.0'): from docker.types import Ulimit, LogConfig from docker import types as docker_types else: from docker.utils.types import Ulimit, LogConfig from docker.errors import DockerException, APIError, NotFound except Exception: # missing Docker SDK for Python handled in ansible.module_utils.docker.common pass REQUIRES_CONVERSION_TO_BYTES = [ 'kernel_memory', 'memory', 'memory_reservation', 'memory_swap', 'shm_size' ] def is_volume_permissions(mode): for part in mode.split(','): if part not in ('rw', 'ro', 'z', 'Z', 'consistent', 'delegated', 'cached', 'rprivate', 'private', 'rshared', 'shared', 'rslave', 'slave', 'nocopy'): return False return True def parse_port_range(range_or_port, client): ''' Parses a string containing either a single port or a range of ports. Returns a list of integers for each port in the list. ''' if '-' in range_or_port: try: start, end = [int(port) for port in range_or_port.split('-')] except Exception: client.fail('Invalid port range: "{0}"'.format(range_or_port)) if end < start: client.fail('Invalid port range: "{0}"'.format(range_or_port)) return list(range(start, end + 1)) else: try: return [int(range_or_port)] except Exception: client.fail('Invalid port: "{0}"'.format(range_or_port)) def split_colon_ipv6(text, client): ''' Split string by ':', while keeping IPv6 addresses in square brackets in one component. ''' if '[' not in text: return text.split(':') start = 0 result = [] while start < len(text): i = text.find('[', start) if i < 0: result.extend(text[start:].split(':')) break j = text.find(']', i) if j < 0: client.fail('Cannot find closing "]" in input "{0}" for opening "[" at index {1}!'.format(text, i + 1)) result.extend(text[start:i].split(':')) k = text.find(':', j) if k < 0: result[-1] += text[i:] start = len(text) else: result[-1] += text[i:k] if k == len(text): result.append('') break start = k + 1 return result class TaskParameters(DockerBaseClass): ''' Access and parse module parameters ''' def __init__(self, client): super(TaskParameters, self).__init__() self.client = client self.auto_remove = None self.blkio_weight = None self.capabilities = None self.cap_drop = None self.cleanup = None self.command = None self.cpu_period = None self.cpu_quota = None self.cpus = None self.cpuset_cpus = None self.cpuset_mems = None self.cpu_shares = None self.detach = None self.debug = None self.devices = None self.device_read_bps = None self.device_write_bps = None self.device_read_iops = None self.device_write_iops = None self.dns_servers = None self.dns_opts = None self.dns_search_domains = None self.domainname = None self.env = None self.env_file = None self.entrypoint = None self.etc_hosts = None self.exposed_ports = None self.force_kill = None self.groups = None self.healthcheck = None self.hostname = None self.ignore_image = None self.image = None self.init = None self.interactive = None self.ipc_mode = None self.keep_volumes = None self.kernel_memory = None self.kill_signal = None self.labels = None self.links = None self.log_driver = None self.output_logs = None self.log_options = None self.mac_address = None self.memory = None self.memory_reservation = None self.memory_swap = None self.memory_swappiness = None self.mounts = None self.name = None self.network_mode = None self.userns_mode = None self.networks = None self.networks_cli_compatible = None self.oom_killer = None self.oom_score_adj = None self.paused = None self.pid_mode = None self.pids_limit = None self.privileged = None self.purge_networks = None self.pull = None self.read_only = None self.recreate = None self.restart = None self.restart_retries = None self.restart_policy = None self.runtime = None self.shm_size = None self.security_opts = None self.state = None self.stop_signal = None self.stop_timeout = None self.tmpfs = None self.trust_image_content = None self.tty = None self.user = None self.uts = None self.volumes = None self.volume_binds = dict() self.volumes_from = None self.volume_driver = None self.working_dir = None for key, value in client.module.params.items(): setattr(self, key, value) self.comparisons = client.comparisons # If state is 'absent', parameters do not have to be parsed or interpreted. # Only the container's name is needed. if self.state == 'absent': return if self.cpus is not None: self.cpus = int(round(self.cpus * 1E9)) if self.groups: # In case integers are passed as groups, we need to convert them to # strings as docker internally treats them as strings. self.groups = [str(g) for g in self.groups] for param_name in REQUIRES_CONVERSION_TO_BYTES: if client.module.params.get(param_name): try: setattr(self, param_name, human_to_bytes(client.module.params.get(param_name))) except ValueError as exc: self.fail("Failed to convert %s to bytes: %s" % (param_name, exc)) self.publish_all_ports = False self.published_ports = self._parse_publish_ports() if self.published_ports in ('all', 'ALL'): self.publish_all_ports = True self.published_ports = None self.ports = self._parse_exposed_ports(self.published_ports) self.log("expose ports:") self.log(self.ports, pretty_print=True) self.links = self._parse_links(self.links) if self.volumes: self.volumes = self._expand_host_paths() self.tmpfs = self._parse_tmpfs() self.env = self._get_environment() self.ulimits = self._parse_ulimits() self.sysctls = self._parse_sysctls() self.log_config = self._parse_log_config() try: self.healthcheck, self.disable_healthcheck = parse_healthcheck(self.healthcheck) except ValueError as e: self.fail(str(e)) self.exp_links = None self.volume_binds = self._get_volume_binds(self.volumes) self.pid_mode = self._replace_container_names(self.pid_mode) self.ipc_mode = self._replace_container_names(self.ipc_mode) self.network_mode = self._replace_container_names(self.network_mode) self.log("volumes:") self.log(self.volumes, pretty_print=True) self.log("volume binds:") self.log(self.volume_binds, pretty_print=True) if self.networks: for network in self.networks: network['id'] = self._get_network_id(network['name']) if not network['id']: self.fail("Parameter error: network named %s could not be found. Does it exist?" % network['name']) if network.get('links'): network['links'] = self._parse_links(network['links']) if self.mac_address: # Ensure the MAC address uses colons instead of hyphens for later comparison self.mac_address = self.mac_address.replace('-', ':') if self.entrypoint: # convert from list to str. self.entrypoint = ' '.join([str(x) for x in self.entrypoint]) if self.command: # convert from list to str if isinstance(self.command, list): self.command = ' '.join([str(x) for x in self.command]) self.mounts_opt, self.expected_mounts = self._process_mounts() self._check_mount_target_collisions() for param_name in ["device_read_bps", "device_write_bps"]: if client.module.params.get(param_name): self._process_rate_bps(option=param_name) for param_name in ["device_read_iops", "device_write_iops"]: if client.module.params.get(param_name): self._process_rate_iops(option=param_name) def fail(self, msg): self.client.fail(msg) @property def update_parameters(self): ''' Returns parameters used to update a container ''' update_parameters = dict( blkio_weight='blkio_weight', cpu_period='cpu_period', cpu_quota='cpu_quota', cpu_shares='cpu_shares', cpuset_cpus='cpuset_cpus', cpuset_mems='cpuset_mems', mem_limit='memory', mem_reservation='memory_reservation', memswap_limit='memory_swap', kernel_memory='kernel_memory', ) result = dict() for key, value in update_parameters.items(): if getattr(self, value, None) is not None: if self.client.option_minimal_versions[value]['supported']: result[key] = getattr(self, value) return result @property def create_parameters(self): ''' Returns parameters used to create a container ''' create_params = dict( command='command', domainname='domainname', hostname='hostname', user='user', detach='detach', stdin_open='interactive', tty='tty', ports='ports', environment='env', name='name', entrypoint='entrypoint', mac_address='mac_address', labels='labels', stop_signal='stop_signal', working_dir='working_dir', stop_timeout='stop_timeout', healthcheck='healthcheck', ) if self.client.docker_py_version < LooseVersion('3.0'): # cpu_shares and volume_driver moved to create_host_config in > 3 create_params['cpu_shares'] = 'cpu_shares' create_params['volume_driver'] = 'volume_driver' result = dict( host_config=self._host_config(), volumes=self._get_mounts(), ) for key, value in create_params.items(): if getattr(self, value, None) is not None: if self.client.option_minimal_versions[value]['supported']: result[key] = getattr(self, value) if self.networks_cli_compatible and self.networks: network = self.networks[0] params = dict() for para in ('ipv4_address', 'ipv6_address', 'links', 'aliases'): if network.get(para): params[para] = network[para] network_config = dict() network_config[network['name']] = self.client.create_endpoint_config(**params) result['networking_config'] = self.client.create_networking_config(network_config) return result def _expand_host_paths(self): new_vols = [] for vol in self.volumes: if ':' in vol: if len(vol.split(':')) == 3: host, container, mode = vol.split(':') if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) if re.match(r'[.~]', host): host = os.path.abspath(os.path.expanduser(host)) new_vols.append("%s:%s:%s" % (host, container, mode)) continue elif len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]) and re.match(r'[.~]', parts[0]): host = os.path.abspath(os.path.expanduser(parts[0])) new_vols.append("%s:%s:rw" % (host, parts[1])) continue new_vols.append(vol) return new_vols def _get_mounts(self): ''' Return a list of container mounts. :return: ''' result = [] if self.volumes: for vol in self.volumes: if ':' in vol: if len(vol.split(':')) == 3: dummy, container, dummy = vol.split(':') result.append(container) continue if len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]): result.append(parts[1]) continue result.append(vol) self.log("mounts:") self.log(result, pretty_print=True) return result def _host_config(self): ''' Returns parameters used to create a HostConfig object ''' host_config_params = dict( port_bindings='published_ports', publish_all_ports='publish_all_ports', links='links', privileged='privileged', dns='dns_servers', dns_opt='dns_opts', dns_search='dns_search_domains', binds='volume_binds', volumes_from='volumes_from', network_mode='network_mode', userns_mode='userns_mode', cap_add='capabilities', cap_drop='cap_drop', extra_hosts='etc_hosts', read_only='read_only', ipc_mode='ipc_mode', security_opt='security_opts', ulimits='ulimits', sysctls='sysctls', log_config='log_config', mem_limit='memory', memswap_limit='memory_swap', mem_swappiness='memory_swappiness', oom_score_adj='oom_score_adj', oom_kill_disable='oom_killer', shm_size='shm_size', group_add='groups', devices='devices', pid_mode='pid_mode', tmpfs='tmpfs', init='init', uts_mode='uts', runtime='runtime', auto_remove='auto_remove', device_read_bps='device_read_bps', device_write_bps='device_write_bps', device_read_iops='device_read_iops', device_write_iops='device_write_iops', pids_limit='pids_limit', mounts='mounts', nano_cpus='cpus', ) if self.client.docker_py_version >= LooseVersion('1.9') and self.client.docker_api_version >= LooseVersion('1.22'): # blkio_weight can always be updated, but can only be set on creation # when Docker SDK for Python and Docker API are new enough host_config_params['blkio_weight'] = 'blkio_weight' if self.client.docker_py_version >= LooseVersion('3.0'): # cpu_shares and volume_driver moved to create_host_config in > 3 host_config_params['cpu_shares'] = 'cpu_shares' host_config_params['volume_driver'] = 'volume_driver' params = dict() for key, value in host_config_params.items(): if getattr(self, value, None) is not None: if self.client.option_minimal_versions[value]['supported']: params[key] = getattr(self, value) if self.restart_policy: params['restart_policy'] = dict(Name=self.restart_policy, MaximumRetryCount=self.restart_retries) if 'mounts' in params: params['mounts'] = self.mounts_opt return self.client.create_host_config(**params) @property def default_host_ip(self): ip = '0.0.0.0' if not self.networks: return ip for net in self.networks: if net.get('name'): try: network = self.client.inspect_network(net['name']) if network.get('Driver') == 'bridge' and \ network.get('Options', {}).get('com.docker.network.bridge.host_binding_ipv4'): ip = network['Options']['com.docker.network.bridge.host_binding_ipv4'] break except NotFound as nfe: self.client.fail( "Cannot inspect the network '{0}' to determine the default IP: {1}".format(net['name'], nfe), exception=traceback.format_exc() ) return ip def _parse_publish_ports(self): ''' Parse ports from docker CLI syntax ''' if self.published_ports is None: return None if 'all' in self.published_ports: return 'all' default_ip = self.default_host_ip binds = {} for port in self.published_ports: parts = split_colon_ipv6(str(port), self.client) container_port = parts[-1] protocol = '' if '/' in container_port: container_port, protocol = parts[-1].split('/') container_ports = parse_port_range(container_port, self.client) p_len = len(parts) if p_len == 1: port_binds = len(container_ports) * [(default_ip,)] elif p_len == 2: port_binds = [(default_ip, port) for port in parse_port_range(parts[0], self.client)] elif p_len == 3: # We only allow IPv4 and IPv6 addresses for the bind address ipaddr = parts[0] if not re.match(r'^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$', parts[0]) and not re.match(r'^\[[0-9a-fA-F:]+\]$', ipaddr): self.fail(('Bind addresses for published ports must be IPv4 or IPv6 addresses, not hostnames. ' 'Use the dig lookup to resolve hostnames. (Found hostname: {0})').format(ipaddr)) if re.match(r'^\[[0-9a-fA-F:]+\]$', ipaddr): ipaddr = ipaddr[1:-1] if parts[1]: port_binds = [(ipaddr, port) for port in parse_port_range(parts[1], self.client)] else: port_binds = len(container_ports) * [(ipaddr,)] for bind, container_port in zip(port_binds, container_ports): idx = '{0}/{1}'.format(container_port, protocol) if protocol else container_port if idx in binds: old_bind = binds[idx] if isinstance(old_bind, list): old_bind.append(bind) else: binds[idx] = [old_bind, bind] else: binds[idx] = bind return binds def _get_volume_binds(self, volumes): ''' Extract host bindings, if any, from list of volume mapping strings. :return: dictionary of bind mappings ''' result = dict() if volumes: for vol in volumes: host = None if ':' in vol: parts = vol.split(':') if len(parts) == 3: host, container, mode = parts if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) elif len(parts) == 2: if not is_volume_permissions(parts[1]): host, container, mode = (vol.split(':') + ['rw']) if host is not None: result[host] = dict( bind=container, mode=mode ) return result def _parse_exposed_ports(self, published_ports): ''' Parse exposed ports from docker CLI-style ports syntax. ''' exposed = [] if self.exposed_ports: for port in self.exposed_ports: port = str(port).strip() protocol = 'tcp' match = re.search(r'(/.+$)', port) if match: protocol = match.group(1).replace('/', '') port = re.sub(r'/.+$', '', port) exposed.append((port, protocol)) if published_ports: # Any published port should also be exposed for publish_port in published_ports: match = False if isinstance(publish_port, string_types) and '/' in publish_port: port, protocol = publish_port.split('/') port = int(port) else: protocol = 'tcp' port = int(publish_port) for exposed_port in exposed: if exposed_port[1] != protocol: continue if isinstance(exposed_port[0], string_types) and '-' in exposed_port[0]: start_port, end_port = exposed_port[0].split('-') if int(start_port) <= port <= int(end_port): match = True elif exposed_port[0] == port: match = True if not match: exposed.append((port, protocol)) return exposed @staticmethod def _parse_links(links): ''' Turn links into a dictionary ''' if links is None: return None result = [] for link in links: parsed_link = link.split(':', 1) if len(parsed_link) == 2: result.append((parsed_link[0], parsed_link[1])) else: result.append((parsed_link[0], parsed_link[0])) return result def _parse_ulimits(self): ''' Turn ulimits into an array of Ulimit objects ''' if self.ulimits is None: return None results = [] for limit in self.ulimits: limits = dict() pieces = limit.split(':') if len(pieces) >= 2: limits['name'] = pieces[0] limits['soft'] = int(pieces[1]) limits['hard'] = int(pieces[1]) if len(pieces) == 3: limits['hard'] = int(pieces[2]) try: results.append(Ulimit(**limits)) except ValueError as exc: self.fail("Error parsing ulimits value %s - %s" % (limit, exc)) return results def _parse_sysctls(self): ''' Turn sysctls into an hash of Sysctl objects ''' return self.sysctls def _parse_log_config(self): ''' Create a LogConfig object ''' if self.log_driver is None: return None options = dict( Type=self.log_driver, Config=dict() ) if self.log_options is not None: options['Config'] = dict() for k, v in self.log_options.items(): if not isinstance(v, string_types): self.client.module.warn( "Non-string value found for log_options option '%s'. The value is automatically converted to '%s'. " "If this is not correct, or you want to avoid such warnings, please quote the value." % (k, str(v)) ) v = str(v) self.log_options[k] = v options['Config'][k] = v try: return LogConfig(**options) except ValueError as exc: self.fail('Error parsing logging options - %s' % (exc)) def _parse_tmpfs(self): ''' Turn tmpfs into a hash of Tmpfs objects ''' result = dict() if self.tmpfs is None: return result for tmpfs_spec in self.tmpfs: split_spec = tmpfs_spec.split(":", 1) if len(split_spec) > 1: result[split_spec[0]] = split_spec[1] else: result[split_spec[0]] = "" return result def _get_environment(self): """ If environment file is combined with explicit environment variables, the explicit environment variables take precedence. """ final_env = {} if self.env_file: parsed_env_file = utils.parse_env_file(self.env_file) for name, value in parsed_env_file.items(): final_env[name] = str(value) if self.env: for name, value in self.env.items(): if not isinstance(value, string_types): self.fail("Non-string value found for env option. Ambiguous env options must be " "wrapped in quotes to avoid them being interpreted. Key: %s" % (name, )) final_env[name] = str(value) return final_env def _get_network_id(self, network_name): network_id = None try: for network in self.client.networks(names=[network_name]): if network['Name'] == network_name: network_id = network['Id'] break except Exception as exc: self.fail("Error getting network id for %s - %s" % (network_name, str(exc))) return network_id def _process_mounts(self): if self.mounts is None: return None, None mounts_list = [] mounts_expected = [] for mount in self.mounts: target = mount['target'] datatype = mount['type'] mount_dict = dict(mount) # Sanity checks (so we don't wait for docker-py to barf on input) if mount_dict.get('source') is None and datatype != 'tmpfs': self.client.fail('source must be specified for mount "{0}" of type "{1}"'.format(target, datatype)) mount_option_types = dict( volume_driver='volume', volume_options='volume', propagation='bind', no_copy='volume', labels='volume', tmpfs_size='tmpfs', tmpfs_mode='tmpfs', ) for option, req_datatype in mount_option_types.items(): if mount_dict.get(option) is not None and datatype != req_datatype: self.client.fail('{0} cannot be specified for mount "{1}" of type "{2}" (needs type "{3}")'.format(option, target, datatype, req_datatype)) # Handle volume_driver and volume_options volume_driver = mount_dict.pop('volume_driver') volume_options = mount_dict.pop('volume_options') if volume_driver: if volume_options: volume_options = clean_dict_booleans_for_docker_api(volume_options) mount_dict['driver_config'] = docker_types.DriverConfig(name=volume_driver, options=volume_options) if mount_dict['labels']: mount_dict['labels'] = clean_dict_booleans_for_docker_api(mount_dict['labels']) if mount_dict.get('tmpfs_size') is not None: try: mount_dict['tmpfs_size'] = human_to_bytes(mount_dict['tmpfs_size']) except ValueError as exc: self.fail('Failed to convert tmpfs_size of mount "{0}" to bytes: {1}'.format(target, exc)) if mount_dict.get('tmpfs_mode') is not None: try: mount_dict['tmpfs_mode'] = int(mount_dict['tmpfs_mode'], 8) except Exception as dummy: self.client.fail('tmp_fs mode of mount "{0}" is not an octal string!'.format(target)) # Fill expected mount dict mount_expected = dict(mount) mount_expected['tmpfs_size'] = mount_dict['tmpfs_size'] mount_expected['tmpfs_mode'] = mount_dict['tmpfs_mode'] # Add result to lists mounts_list.append(docker_types.Mount(**mount_dict)) mounts_expected.append(omit_none_from_dict(mount_expected)) return mounts_list, mounts_expected def _process_rate_bps(self, option): """ Format device_read_bps and device_write_bps option """ devices_list = [] for v in getattr(self, option): device_dict = dict((x.title(), y) for x, y in v.items()) device_dict['Rate'] = human_to_bytes(device_dict['Rate']) devices_list.append(device_dict) setattr(self, option, devices_list) def _process_rate_iops(self, option): """ Format device_read_iops and device_write_iops option """ devices_list = [] for v in getattr(self, option): device_dict = dict((x.title(), y) for x, y in v.items()) devices_list.append(device_dict) setattr(self, option, devices_list) def _replace_container_names(self, mode): """ Parse IPC and PID modes. If they contain a container name, replace with the container's ID. """ if mode is None or not mode.startswith('container:'): return mode container_name = mode[len('container:'):] # Try to inspect container to see whether this is an ID or a # name (and in the latter case, retrieve it's ID) container = self.client.get_container(container_name) if container is None: # If we can't find the container, issue a warning and continue with # what the user specified. self.client.module.warn('Cannot find a container with name or ID "{0}"'.format(container_name)) return mode return 'container:{0}'.format(container['Id']) def _check_mount_target_collisions(self): last = dict() def f(t, name): if t in last: if name == last[t]: self.client.fail('The mount point "{0}" appears twice in the {1} option'.format(t, name)) else: self.client.fail('The mount point "{0}" appears both in the {1} and {2} option'.format(t, name, last[t])) last[t] = name if self.expected_mounts: for t in [m['target'] for m in self.expected_mounts]: f(t, 'mounts') if self.volumes: for v in self.volumes: vs = v.split(':') f(vs[0 if len(vs) == 1 else 1], 'volumes') class Container(DockerBaseClass): def __init__(self, container, parameters): super(Container, self).__init__() self.raw = container self.Id = None self.container = container if container: self.Id = container['Id'] self.Image = container['Image'] self.log(self.container, pretty_print=True) self.parameters = parameters self.parameters.expected_links = None self.parameters.expected_ports = None self.parameters.expected_exposed = None self.parameters.expected_volumes = None self.parameters.expected_ulimits = None self.parameters.expected_sysctls = None self.parameters.expected_etc_hosts = None self.parameters.expected_env = None self.parameters_map = dict() self.parameters_map['expected_links'] = 'links' self.parameters_map['expected_ports'] = 'expected_ports' self.parameters_map['expected_exposed'] = 'exposed_ports' self.parameters_map['expected_volumes'] = 'volumes' self.parameters_map['expected_ulimits'] = 'ulimits' self.parameters_map['expected_sysctls'] = 'sysctls' self.parameters_map['expected_etc_hosts'] = 'etc_hosts' self.parameters_map['expected_env'] = 'env' self.parameters_map['expected_entrypoint'] = 'entrypoint' self.parameters_map['expected_binds'] = 'volumes' self.parameters_map['expected_cmd'] = 'command' self.parameters_map['expected_devices'] = 'devices' self.parameters_map['expected_healthcheck'] = 'healthcheck' self.parameters_map['expected_mounts'] = 'mounts' def fail(self, msg): self.parameters.client.fail(msg) @property def exists(self): return True if self.container else False @property def running(self): if self.container and self.container.get('State'): if self.container['State'].get('Running') and not self.container['State'].get('Ghost', False): return True return False @property def paused(self): if self.container and self.container.get('State'): return self.container['State'].get('Paused', False) return False def _compare(self, a, b, compare): ''' Compare values a and b as described in compare. ''' return compare_generic(a, b, compare['comparison'], compare['type']) def _decode_mounts(self, mounts): if not mounts: return mounts result = [] empty_dict = dict() for mount in mounts: res = dict() res['type'] = mount.get('Type') res['source'] = mount.get('Source') res['target'] = mount.get('Target') res['read_only'] = mount.get('ReadOnly', False) # golang's omitempty for bool returns None for False res['consistency'] = mount.get('Consistency') res['propagation'] = mount.get('BindOptions', empty_dict).get('Propagation') res['no_copy'] = mount.get('VolumeOptions', empty_dict).get('NoCopy', False) res['labels'] = mount.get('VolumeOptions', empty_dict).get('Labels', empty_dict) res['volume_driver'] = mount.get('VolumeOptions', empty_dict).get('DriverConfig', empty_dict).get('Name') res['volume_options'] = mount.get('VolumeOptions', empty_dict).get('DriverConfig', empty_dict).get('Options', empty_dict) res['tmpfs_size'] = mount.get('TmpfsOptions', empty_dict).get('SizeBytes') res['tmpfs_mode'] = mount.get('TmpfsOptions', empty_dict).get('Mode') result.append(res) return result def has_different_configuration(self, image): ''' Diff parameters vs existing container config. Returns tuple: (True | False, List of differences) ''' self.log('Starting has_different_configuration') self.parameters.expected_entrypoint = self._get_expected_entrypoint() self.parameters.expected_links = self._get_expected_links() self.parameters.expected_ports = self._get_expected_ports() self.parameters.expected_exposed = self._get_expected_exposed(image) self.parameters.expected_volumes = self._get_expected_volumes(image) self.parameters.expected_binds = self._get_expected_binds(image) self.parameters.expected_ulimits = self._get_expected_ulimits(self.parameters.ulimits) self.parameters.expected_sysctls = self._get_expected_sysctls(self.parameters.sysctls) self.parameters.expected_etc_hosts = self._convert_simple_dict_to_list('etc_hosts') self.parameters.expected_env = self._get_expected_env(image) self.parameters.expected_cmd = self._get_expected_cmd() self.parameters.expected_devices = self._get_expected_devices() self.parameters.expected_healthcheck = self._get_expected_healthcheck() if not self.container.get('HostConfig'): self.fail("has_config_diff: Error parsing container properties. HostConfig missing.") if not self.container.get('Config'): self.fail("has_config_diff: Error parsing container properties. Config missing.") if not self.container.get('NetworkSettings'): self.fail("has_config_diff: Error parsing container properties. NetworkSettings missing.") host_config = self.container['HostConfig'] log_config = host_config.get('LogConfig', dict()) restart_policy = host_config.get('RestartPolicy', dict()) config = self.container['Config'] network = self.container['NetworkSettings'] # The previous version of the docker module ignored the detach state by # assuming if the container was running, it must have been detached. detach = not (config.get('AttachStderr') and config.get('AttachStdout')) # "ExposedPorts": null returns None type & causes AttributeError - PR #5517 if config.get('ExposedPorts') is not None: expected_exposed = [self._normalize_port(p) for p in config.get('ExposedPorts', dict()).keys()] else: expected_exposed = [] # Map parameters to container inspect results config_mapping = dict( expected_cmd=config.get('Cmd'), domainname=config.get('Domainname'), hostname=config.get('Hostname'), user=config.get('User'), detach=detach, init=host_config.get('Init'), interactive=config.get('OpenStdin'), capabilities=host_config.get('CapAdd'), cap_drop=host_config.get('CapDrop'), expected_devices=host_config.get('Devices'), dns_servers=host_config.get('Dns'), dns_opts=host_config.get('DnsOptions'), dns_search_domains=host_config.get('DnsSearch'), expected_env=(config.get('Env') or []), expected_entrypoint=config.get('Entrypoint'), expected_etc_hosts=host_config['ExtraHosts'], expected_exposed=expected_exposed, groups=host_config.get('GroupAdd'), ipc_mode=host_config.get("IpcMode"), labels=config.get('Labels'), expected_links=host_config.get('Links'), mac_address=network.get('MacAddress'), memory_swappiness=host_config.get('MemorySwappiness'), network_mode=host_config.get('NetworkMode'), userns_mode=host_config.get('UsernsMode'), oom_killer=host_config.get('OomKillDisable'), oom_score_adj=host_config.get('OomScoreAdj'), pid_mode=host_config.get('PidMode'), privileged=host_config.get('Privileged'), expected_ports=host_config.get('PortBindings'), read_only=host_config.get('ReadonlyRootfs'), restart_policy=restart_policy.get('Name'), runtime=host_config.get('Runtime'), shm_size=host_config.get('ShmSize'), security_opts=host_config.get("SecurityOpt"), stop_signal=config.get("StopSignal"), tmpfs=host_config.get('Tmpfs'), tty=config.get('Tty'), expected_ulimits=host_config.get('Ulimits'), expected_sysctls=host_config.get('Sysctls'), uts=host_config.get('UTSMode'), expected_volumes=config.get('Volumes'), expected_binds=host_config.get('Binds'), volume_driver=host_config.get('VolumeDriver'), volumes_from=host_config.get('VolumesFrom'), working_dir=config.get('WorkingDir'), publish_all_ports=host_config.get('PublishAllPorts'), expected_healthcheck=config.get('Healthcheck'), disable_healthcheck=(not config.get('Healthcheck') or config.get('Healthcheck').get('Test') == ['NONE']), device_read_bps=host_config.get('BlkioDeviceReadBps'), device_write_bps=host_config.get('BlkioDeviceWriteBps'), device_read_iops=host_config.get('BlkioDeviceReadIOps'), device_write_iops=host_config.get('BlkioDeviceWriteIOps'), pids_limit=host_config.get('PidsLimit'), # According to https://github.com/moby/moby/, support for HostConfig.Mounts # has been included at least since v17.03.0-ce, which has API version 1.26. # The previous tag, v1.9.1, has API version 1.21 and does not have # HostConfig.Mounts. I have no idea what about API 1.25... expected_mounts=self._decode_mounts(host_config.get('Mounts')), cpus=host_config.get('NanoCpus'), ) # Options which don't make sense without their accompanying option if self.parameters.restart_policy: config_mapping['restart_retries'] = restart_policy.get('MaximumRetryCount') if self.parameters.log_driver: config_mapping['log_driver'] = log_config.get('Type') config_mapping['log_options'] = log_config.get('Config') if self.parameters.client.option_minimal_versions['auto_remove']['supported']: # auto_remove is only supported in Docker SDK for Python >= 2.0.0; unfortunately # it has a default value, that's why we have to jump through the hoops here config_mapping['auto_remove'] = host_config.get('AutoRemove') if self.parameters.client.option_minimal_versions['stop_timeout']['supported']: # stop_timeout is only supported in Docker SDK for Python >= 2.1. Note that # stop_timeout has a hybrid role, in that it used to be something only used # for stopping containers, and is now also used as a container property. # That's why it needs special handling here. config_mapping['stop_timeout'] = config.get('StopTimeout') if self.parameters.client.docker_api_version < LooseVersion('1.22'): # For docker API < 1.22, update_container() is not supported. Thus # we need to handle all limits which are usually handled by # update_container() as configuration changes which require a container # restart. config_mapping.update(dict( blkio_weight=host_config.get('BlkioWeight'), cpu_period=host_config.get('CpuPeriod'), cpu_quota=host_config.get('CpuQuota'), cpu_shares=host_config.get('CpuShares'), cpuset_cpus=host_config.get('CpusetCpus'), cpuset_mems=host_config.get('CpusetMems'), kernel_memory=host_config.get("KernelMemory"), memory=host_config.get('Memory'), memory_reservation=host_config.get('MemoryReservation'), memory_swap=host_config.get('MemorySwap'), )) differences = DifferenceTracker() for key, value in config_mapping.items(): minimal_version = self.parameters.client.option_minimal_versions.get(key, {}) if not minimal_version.get('supported', True): continue compare = self.parameters.client.comparisons[self.parameters_map.get(key, key)] self.log('check differences %s %s vs %s (%s)' % (key, getattr(self.parameters, key), str(value), compare)) if getattr(self.parameters, key, None) is not None: match = self._compare(getattr(self.parameters, key), value, compare) if not match: # no match. record the differences p = getattr(self.parameters, key) c = value if compare['type'] == 'set': # Since the order does not matter, sort so that the diff output is better. if p is not None: p = sorted(p) if c is not None: c = sorted(c) elif compare['type'] == 'set(dict)': # Since the order does not matter, sort so that the diff output is better. if key == 'expected_mounts': # For selected values, use one entry as key def sort_key_fn(x): return x['target'] else: # We sort the list of dictionaries by using the sorted items of a dict as its key. def sort_key_fn(x): return sorted((a, str(b)) for a, b in x.items()) if p is not None: p = sorted(p, key=sort_key_fn) if c is not None: c = sorted(c, key=sort_key_fn) differences.add(key, parameter=p, active=c) has_differences = not differences.empty return has_differences, differences def has_different_resource_limits(self): ''' Diff parameters and container resource limits ''' if not self.container.get('HostConfig'): self.fail("limits_differ_from_container: Error parsing container properties. HostConfig missing.") if self.parameters.client.docker_api_version < LooseVersion('1.22'): # update_container() call not supported return False, [] host_config = self.container['HostConfig'] config_mapping = dict( blkio_weight=host_config.get('BlkioWeight'), cpu_period=host_config.get('CpuPeriod'), cpu_quota=host_config.get('CpuQuota'), cpu_shares=host_config.get('CpuShares'), cpuset_cpus=host_config.get('CpusetCpus'), cpuset_mems=host_config.get('CpusetMems'), kernel_memory=host_config.get("KernelMemory"), memory=host_config.get('Memory'), memory_reservation=host_config.get('MemoryReservation'), memory_swap=host_config.get('MemorySwap'), ) differences = DifferenceTracker() for key, value in config_mapping.items(): if getattr(self.parameters, key, None): compare = self.parameters.client.comparisons[self.parameters_map.get(key, key)] match = self._compare(getattr(self.parameters, key), value, compare) if not match: # no match. record the differences differences.add(key, parameter=getattr(self.parameters, key), active=value) different = not differences.empty return different, differences def has_network_differences(self): ''' Check if the container is connected to requested networks with expected options: links, aliases, ipv4, ipv6 ''' different = False differences = [] if not self.parameters.networks: return different, differences if not self.container.get('NetworkSettings'): self.fail("has_missing_networks: Error parsing container properties. NetworkSettings missing.") connected_networks = self.container['NetworkSettings']['Networks'] for network in self.parameters.networks: network_info = connected_networks.get(network['name']) if network_info is None: different = True differences.append(dict( parameter=network, container=None )) else: diff = False network_info_ipam = network_info.get('IPAMConfig') or {} if network.get('ipv4_address') and network['ipv4_address'] != network_info_ipam.get('IPv4Address'): diff = True if network.get('ipv6_address') and network['ipv6_address'] != network_info_ipam.get('IPv6Address'): diff = True if network.get('aliases'): if not compare_generic(network['aliases'], network_info.get('Aliases'), 'allow_more_present', 'set'): diff = True if network.get('links'): expected_links = [] for link, alias in network['links']: expected_links.append("%s:%s" % (link, alias)) if not compare_generic(expected_links, network_info.get('Links'), 'allow_more_present', 'set'): diff = True if diff: different = True differences.append(dict( parameter=network, container=dict( name=network['name'], ipv4_address=network_info_ipam.get('IPv4Address'), ipv6_address=network_info_ipam.get('IPv6Address'), aliases=network_info.get('Aliases'), links=network_info.get('Links') ) )) return different, differences def has_extra_networks(self): ''' Check if the container is connected to non-requested networks ''' extra_networks = [] extra = False if not self.container.get('NetworkSettings'): self.fail("has_extra_networks: Error parsing container properties. NetworkSettings missing.") connected_networks = self.container['NetworkSettings'].get('Networks') if connected_networks: for network, network_config in connected_networks.items(): keep = False if self.parameters.networks: for expected_network in self.parameters.networks: if expected_network['name'] == network: keep = True if not keep: extra = True extra_networks.append(dict(name=network, id=network_config['NetworkID'])) return extra, extra_networks def _get_expected_devices(self): if not self.parameters.devices: return None expected_devices = [] for device in self.parameters.devices: parts = device.split(':') if len(parts) == 1: expected_devices.append( dict( CgroupPermissions='rwm', PathInContainer=parts[0], PathOnHost=parts[0] )) elif len(parts) == 2: parts = device.split(':') expected_devices.append( dict( CgroupPermissions='rwm', PathInContainer=parts[1], PathOnHost=parts[0] ) ) else: expected_devices.append( dict( CgroupPermissions=parts[2], PathInContainer=parts[1], PathOnHost=parts[0] )) return expected_devices def _get_expected_entrypoint(self): if not self.parameters.entrypoint: return None return shlex.split(self.parameters.entrypoint) def _get_expected_ports(self): if not self.parameters.published_ports: return None expected_bound_ports = {} for container_port, config in self.parameters.published_ports.items(): if isinstance(container_port, int): container_port = "%s/tcp" % container_port if len(config) == 1: if isinstance(config[0], int): expected_bound_ports[container_port] = [{'HostIp': "0.0.0.0", 'HostPort': config[0]}] else: expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': ""}] elif isinstance(config[0], tuple): expected_bound_ports[container_port] = [] for host_ip, host_port in config: expected_bound_ports[container_port].append({'HostIp': host_ip, 'HostPort': str(host_port)}) else: expected_bound_ports[container_port] = [{'HostIp': config[0], 'HostPort': str(config[1])}] return expected_bound_ports def _get_expected_links(self): if self.parameters.links is None: return None self.log('parameter links:') self.log(self.parameters.links, pretty_print=True) exp_links = [] for link, alias in self.parameters.links: exp_links.append("/%s:%s/%s" % (link, ('/' + self.parameters.name), alias)) return exp_links def _get_expected_binds(self, image): self.log('_get_expected_binds') image_vols = [] if image: image_vols = self._get_image_binds(image[self.parameters.client.image_inspect_source].get('Volumes')) param_vols = [] if self.parameters.volumes: for vol in self.parameters.volumes: host = None if ':' in vol: if len(vol.split(':')) == 3: host, container, mode = vol.split(':') if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) if len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]): host, container, mode = vol.split(':') + ['rw'] if host: param_vols.append("%s:%s:%s" % (host, container, mode)) result = list(set(image_vols + param_vols)) self.log("expected_binds:") self.log(result, pretty_print=True) return result def _get_image_binds(self, volumes): ''' Convert array of binds to array of strings with format host_path:container_path:mode :param volumes: array of bind dicts :return: array of strings ''' results = [] if isinstance(volumes, dict): results += self._get_bind_from_dict(volumes) elif isinstance(volumes, list): for vol in volumes: results += self._get_bind_from_dict(vol) return results @staticmethod def _get_bind_from_dict(volume_dict): results = [] if volume_dict: for host_path, config in volume_dict.items(): if isinstance(config, dict) and config.get('bind'): container_path = config.get('bind') mode = config.get('mode', 'rw') results.append("%s:%s:%s" % (host_path, container_path, mode)) return results def _get_expected_volumes(self, image): self.log('_get_expected_volumes') expected_vols = dict() if image and image[self.parameters.client.image_inspect_source].get('Volumes'): expected_vols.update(image[self.parameters.client.image_inspect_source].get('Volumes')) if self.parameters.volumes: for vol in self.parameters.volumes: container = None if ':' in vol: if len(vol.split(':')) == 3: dummy, container, mode = vol.split(':') if not is_volume_permissions(mode): self.fail('Found invalid volumes mode: {0}'.format(mode)) if len(vol.split(':')) == 2: parts = vol.split(':') if not is_volume_permissions(parts[1]): dummy, container, mode = vol.split(':') + ['rw'] new_vol = dict() if container: new_vol[container] = dict() else: new_vol[vol] = dict() expected_vols.update(new_vol) if not expected_vols: expected_vols = None self.log("expected_volumes:") self.log(expected_vols, pretty_print=True) return expected_vols def _get_expected_env(self, image): self.log('_get_expected_env') expected_env = dict() if image and image[self.parameters.client.image_inspect_source].get('Env'): for env_var in image[self.parameters.client.image_inspect_source]['Env']: parts = env_var.split('=', 1) expected_env[parts[0]] = parts[1] if self.parameters.env: expected_env.update(self.parameters.env) param_env = [] for key, value in expected_env.items(): param_env.append("%s=%s" % (key, value)) return param_env def _get_expected_exposed(self, image): self.log('_get_expected_exposed') image_ports = [] if image: image_exposed_ports = image[self.parameters.client.image_inspect_source].get('ExposedPorts') or {} image_ports = [self._normalize_port(p) for p in image_exposed_ports.keys()] param_ports = [] if self.parameters.ports: param_ports = [str(p[0]) + '/' + p[1] for p in self.parameters.ports] result = list(set(image_ports + param_ports)) self.log(result, pretty_print=True) return result def _get_expected_ulimits(self, config_ulimits): self.log('_get_expected_ulimits') if config_ulimits is None: return None results = [] for limit in config_ulimits: results.append(dict( Name=limit.name, Soft=limit.soft, Hard=limit.hard )) return results def _get_expected_sysctls(self, config_sysctls): self.log('_get_expected_sysctls') if config_sysctls is None: return None result = dict() for key, value in config_sysctls.items(): result[key] = str(value) return result def _get_expected_cmd(self): self.log('_get_expected_cmd') if not self.parameters.command: return None return shlex.split(self.parameters.command) def _convert_simple_dict_to_list(self, param_name, join_with=':'): if getattr(self.parameters, param_name, None) is None: return None results = [] for key, value in getattr(self.parameters, param_name).items(): results.append("%s%s%s" % (key, join_with, value)) return results def _normalize_port(self, port): if '/' not in port: return port + '/tcp' return port def _get_expected_healthcheck(self): self.log('_get_expected_healthcheck') expected_healthcheck = dict() if self.parameters.healthcheck: expected_healthcheck.update([(k.title().replace("_", ""), v) for k, v in self.parameters.healthcheck.items()]) return expected_healthcheck class ContainerManager(DockerBaseClass): ''' Perform container management tasks ''' def __init__(self, client): super(ContainerManager, self).__init__() if client.module.params.get('log_options') and not client.module.params.get('log_driver'): client.module.warn('log_options is ignored when log_driver is not specified') if client.module.params.get('healthcheck') and not client.module.params.get('healthcheck').get('test'): client.module.warn('healthcheck is ignored when test is not specified') if client.module.params.get('restart_retries') is not None and not client.module.params.get('restart_policy'): client.module.warn('restart_retries is ignored when restart_policy is not specified') self.client = client self.parameters = TaskParameters(client) self.check_mode = self.client.check_mode self.results = {'changed': False, 'actions': []} self.diff = {} self.diff_tracker = DifferenceTracker() self.facts = {} state = self.parameters.state if state in ('stopped', 'started', 'present'): self.present(state) elif state == 'absent': self.absent() if not self.check_mode and not self.parameters.debug: self.results.pop('actions') if self.client.module._diff or self.parameters.debug: self.diff['before'], self.diff['after'] = self.diff_tracker.get_before_after() self.results['diff'] = self.diff if self.facts: self.results['ansible_facts'] = {'docker_container': self.facts} self.results['container'] = self.facts def present(self, state): container = self._get_container(self.parameters.name) was_running = container.running was_paused = container.paused container_created = False # If the image parameter was passed then we need to deal with the image # version comparison. Otherwise we handle this depending on whether # the container already runs or not; in the former case, in case the # container needs to be restarted, we use the existing container's # image ID. image = self._get_image() self.log(image, pretty_print=True) if not container.exists: # New container self.log('No container found') if not self.parameters.image: self.fail('Cannot create container when image is not specified!') self.diff_tracker.add('exists', parameter=True, active=False) new_container = self.container_create(self.parameters.image, self.parameters.create_parameters) if new_container: container = new_container container_created = True else: # Existing container different, differences = container.has_different_configuration(image) image_different = False if self.parameters.comparisons['image']['comparison'] == 'strict': image_different = self._image_is_different(image, container) if image_different or different or self.parameters.recreate: self.diff_tracker.merge(differences) self.diff['differences'] = differences.get_legacy_docker_container_diffs() if image_different: self.diff['image_different'] = True self.log("differences") self.log(differences.get_legacy_docker_container_diffs(), pretty_print=True) image_to_use = self.parameters.image if not image_to_use and container and container.Image: image_to_use = container.Image if not image_to_use: self.fail('Cannot recreate container when image is not specified or cannot be extracted from current container!') if container.running: self.container_stop(container.Id) self.container_remove(container.Id) new_container = self.container_create(image_to_use, self.parameters.create_parameters) if new_container: container = new_container container_created = True if container and container.exists: container = self.update_limits(container) container = self.update_networks(container, container_created) if state == 'started' and not container.running: self.diff_tracker.add('running', parameter=True, active=was_running) container = self.container_start(container.Id) elif state == 'started' and self.parameters.restart: self.diff_tracker.add('running', parameter=True, active=was_running) self.diff_tracker.add('restarted', parameter=True, active=False) container = self.container_restart(container.Id) elif state == 'stopped' and container.running: self.diff_tracker.add('running', parameter=False, active=was_running) self.container_stop(container.Id) container = self._get_container(container.Id) if state == 'started' and container.paused is not None and container.paused != self.parameters.paused: self.diff_tracker.add('paused', parameter=self.parameters.paused, active=was_paused) if not self.check_mode: try: if self.parameters.paused: self.client.pause(container=container.Id) else: self.client.unpause(container=container.Id) except Exception as exc: self.fail("Error %s container %s: %s" % ( "pausing" if self.parameters.paused else "unpausing", container.Id, str(exc) )) container = self._get_container(container.Id) self.results['changed'] = True self.results['actions'].append(dict(set_paused=self.parameters.paused)) self.facts = container.raw def absent(self): container = self._get_container(self.parameters.name) if container.exists: if container.running: self.diff_tracker.add('running', parameter=False, active=True) self.container_stop(container.Id) self.diff_tracker.add('exists', parameter=False, active=True) self.container_remove(container.Id) def fail(self, msg, **kwargs): self.client.fail(msg, **kwargs) def _output_logs(self, msg): self.client.module.log(msg=msg) def _get_container(self, container): ''' Expects container ID or Name. Returns a container object ''' return Container(self.client.get_container(container), self.parameters) def _get_image(self): if not self.parameters.image: self.log('No image specified') return None if is_image_name_id(self.parameters.image): image = self.client.find_image_by_id(self.parameters.image) else: repository, tag = utils.parse_repository_tag(self.parameters.image) if not tag: tag = "latest" image = self.client.find_image(repository, tag) if not image or self.parameters.pull: if not self.check_mode: self.log("Pull the image.") image, alreadyToLatest = self.client.pull_image(repository, tag) if alreadyToLatest: self.results['changed'] = False else: self.results['changed'] = True self.results['actions'].append(dict(pulled_image="%s:%s" % (repository, tag))) elif not image: # If the image isn't there, claim we'll pull. # (Implicitly: if the image is there, claim it already was latest.) self.results['changed'] = True self.results['actions'].append(dict(pulled_image="%s:%s" % (repository, tag))) self.log("image") self.log(image, pretty_print=True) return image def _image_is_different(self, image, container): if image and image.get('Id'): if container and container.Image: if image.get('Id') != container.Image: self.diff_tracker.add('image', parameter=image.get('Id'), active=container.Image) return True return False def update_limits(self, container): limits_differ, different_limits = container.has_different_resource_limits() if limits_differ: self.log("limit differences:") self.log(different_limits.get_legacy_docker_container_diffs(), pretty_print=True) self.diff_tracker.merge(different_limits) if limits_differ and not self.check_mode: self.container_update(container.Id, self.parameters.update_parameters) return self._get_container(container.Id) return container def update_networks(self, container, container_created): updated_container = container if self.parameters.comparisons['networks']['comparison'] != 'ignore' or container_created: has_network_differences, network_differences = container.has_network_differences() if has_network_differences: if self.diff.get('differences'): self.diff['differences'].append(dict(network_differences=network_differences)) else: self.diff['differences'] = [dict(network_differences=network_differences)] for netdiff in network_differences: self.diff_tracker.add( 'network.{0}'.format(netdiff['parameter']['name']), parameter=netdiff['parameter'], active=netdiff['container'] ) self.results['changed'] = True updated_container = self._add_networks(container, network_differences) if (self.parameters.comparisons['networks']['comparison'] == 'strict' and self.parameters.networks is not None) or self.parameters.purge_networks: has_extra_networks, extra_networks = container.has_extra_networks() if has_extra_networks: if self.diff.get('differences'): self.diff['differences'].append(dict(purge_networks=extra_networks)) else: self.diff['differences'] = [dict(purge_networks=extra_networks)] for extra_network in extra_networks: self.diff_tracker.add( 'network.{0}'.format(extra_network['name']), active=extra_network ) self.results['changed'] = True updated_container = self._purge_networks(container, extra_networks) return updated_container def _add_networks(self, container, differences): for diff in differences: # remove the container from the network, if connected if diff.get('container'): self.results['actions'].append(dict(removed_from_network=diff['parameter']['name'])) if not self.check_mode: try: self.client.disconnect_container_from_network(container.Id, diff['parameter']['id']) except Exception as exc: self.fail("Error disconnecting container from network %s - %s" % (diff['parameter']['name'], str(exc))) # connect to the network params = dict() for para in ('ipv4_address', 'ipv6_address', 'links', 'aliases'): if diff['parameter'].get(para): params[para] = diff['parameter'][para] self.results['actions'].append(dict(added_to_network=diff['parameter']['name'], network_parameters=params)) if not self.check_mode: try: self.log("Connecting container to network %s" % diff['parameter']['id']) self.log(params, pretty_print=True) self.client.connect_container_to_network(container.Id, diff['parameter']['id'], **params) except Exception as exc: self.fail("Error connecting container to network %s - %s" % (diff['parameter']['name'], str(exc))) return self._get_container(container.Id) def _purge_networks(self, container, networks): for network in networks: self.results['actions'].append(dict(removed_from_network=network['name'])) if not self.check_mode: try: self.client.disconnect_container_from_network(container.Id, network['name']) except Exception as exc: self.fail("Error disconnecting container from network %s - %s" % (network['name'], str(exc))) return self._get_container(container.Id) def container_create(self, image, create_parameters): self.log("create container") self.log("image: %s parameters:" % image) self.log(create_parameters, pretty_print=True) self.results['actions'].append(dict(created="Created container", create_parameters=create_parameters)) self.results['changed'] = True new_container = None if not self.check_mode: try: new_container = self.client.create_container(image, **create_parameters) self.client.report_warnings(new_container) except Exception as exc: self.fail("Error creating container: %s" % str(exc)) return self._get_container(new_container['Id']) return new_container def container_start(self, container_id): self.log("start container %s" % (container_id)) self.results['actions'].append(dict(started=container_id)) self.results['changed'] = True if not self.check_mode: try: self.client.start(container=container_id) except Exception as exc: self.fail("Error starting container %s: %s" % (container_id, str(exc))) if self.parameters.detach is False: if self.client.docker_py_version >= LooseVersion('3.0'): status = self.client.wait(container_id)['StatusCode'] else: status = self.client.wait(container_id) if self.parameters.auto_remove: output = "Cannot retrieve result as auto_remove is enabled" if self.parameters.output_logs: self.client.module.warn('Cannot output_logs if auto_remove is enabled!') else: config = self.client.inspect_container(container_id) logging_driver = config['HostConfig']['LogConfig']['Type'] if logging_driver in ('json-file', 'journald'): output = self.client.logs(container_id, stdout=True, stderr=True, stream=False, timestamps=False) if self.parameters.output_logs: self._output_logs(msg=output) else: output = "Result logged using `%s` driver" % logging_driver if status != 0: self.fail(output, status=status) if self.parameters.cleanup: self.container_remove(container_id, force=True) insp = self._get_container(container_id) if insp.raw: insp.raw['Output'] = output else: insp.raw = dict(Output=output) return insp return self._get_container(container_id) def container_remove(self, container_id, link=False, force=False): volume_state = (not self.parameters.keep_volumes) self.log("remove container container:%s v:%s link:%s force%s" % (container_id, volume_state, link, force)) self.results['actions'].append(dict(removed=container_id, volume_state=volume_state, link=link, force=force)) self.results['changed'] = True response = None if not self.check_mode: count = 0 while True: try: response = self.client.remove_container(container_id, v=volume_state, link=link, force=force) except NotFound as dummy: pass except APIError as exc: if 'Unpause the container before stopping or killing' in exc.explanation: # New docker daemon versions do not allow containers to be removed # if they are paused. Make sure we don't end up in an infinite loop. if count == 3: self.fail("Error removing container %s (tried to unpause three times): %s" % (container_id, str(exc))) count += 1 # Unpause try: self.client.unpause(container=container_id) except Exception as exc2: self.fail("Error unpausing container %s for removal: %s" % (container_id, str(exc2))) # Now try again continue if 'removal of container ' in exc.explanation and ' is already in progress' in exc.explanation: pass else: self.fail("Error removing container %s: %s" % (container_id, str(exc))) except Exception as exc: self.fail("Error removing container %s: %s" % (container_id, str(exc))) # We only loop when explicitly requested by 'continue' break return response def container_update(self, container_id, update_parameters): if update_parameters: self.log("update container %s" % (container_id)) self.log(update_parameters, pretty_print=True) self.results['actions'].append(dict(updated=container_id, update_parameters=update_parameters)) self.results['changed'] = True if not self.check_mode and callable(getattr(self.client, 'update_container')): try: result = self.client.update_container(container_id, **update_parameters) self.client.report_warnings(result) except Exception as exc: self.fail("Error updating container %s: %s" % (container_id, str(exc))) return self._get_container(container_id) def container_kill(self, container_id): self.results['actions'].append(dict(killed=container_id, signal=self.parameters.kill_signal)) self.results['changed'] = True response = None if not self.check_mode: try: if self.parameters.kill_signal: response = self.client.kill(container_id, signal=self.parameters.kill_signal) else: response = self.client.kill(container_id) except Exception as exc: self.fail("Error killing container %s: %s" % (container_id, exc)) return response def container_restart(self, container_id): self.results['actions'].append(dict(restarted=container_id, timeout=self.parameters.stop_timeout)) self.results['changed'] = True if not self.check_mode: try: if self.parameters.stop_timeout: dummy = self.client.restart(container_id, timeout=self.parameters.stop_timeout) else: dummy = self.client.restart(container_id) except Exception as exc: self.fail("Error restarting container %s: %s" % (container_id, str(exc))) return self._get_container(container_id) def container_stop(self, container_id): if self.parameters.force_kill: self.container_kill(container_id) return self.results['actions'].append(dict(stopped=container_id, timeout=self.parameters.stop_timeout)) self.results['changed'] = True response = None if not self.check_mode: count = 0 while True: try: if self.parameters.stop_timeout: response = self.client.stop(container_id, timeout=self.parameters.stop_timeout) else: response = self.client.stop(container_id) except APIError as exc: if 'Unpause the container before stopping or killing' in exc.explanation: # New docker daemon versions do not allow containers to be removed # if they are paused. Make sure we don't end up in an infinite loop. if count == 3: self.fail("Error removing container %s (tried to unpause three times): %s" % (container_id, str(exc))) count += 1 # Unpause try: self.client.unpause(container=container_id) except Exception as exc2: self.fail("Error unpausing container %s for removal: %s" % (container_id, str(exc2))) # Now try again continue self.fail("Error stopping container %s: %s" % (container_id, str(exc))) except Exception as exc: self.fail("Error stopping container %s: %s" % (container_id, str(exc))) # We only loop when explicitly requested by 'continue' break return response def detect_ipvX_address_usage(client): ''' Helper function to detect whether any specified network uses ipv4_address or ipv6_address ''' for network in client.module.params.get("networks") or []: if network.get('ipv4_address') is not None or network.get('ipv6_address') is not None: return True return False class AnsibleDockerClientContainer(AnsibleDockerClient): # A list of module options which are not docker container properties __NON_CONTAINER_PROPERTY_OPTIONS = tuple([ 'env_file', 'force_kill', 'keep_volumes', 'ignore_image', 'name', 'pull', 'purge_networks', 'recreate', 'restart', 'state', 'trust_image_content', 'networks', 'cleanup', 'kill_signal', 'output_logs', 'paused' ] + list(DOCKER_COMMON_ARGS.keys())) def _parse_comparisons(self): comparisons = {} comp_aliases = {} # Put in defaults explicit_types = dict( command='list', devices='set(dict)', dns_search_domains='list', dns_servers='list', env='set', entrypoint='list', etc_hosts='set', mounts='set(dict)', networks='set(dict)', ulimits='set(dict)', device_read_bps='set(dict)', device_write_bps='set(dict)', device_read_iops='set(dict)', device_write_iops='set(dict)', ) all_options = set() # this is for improving user feedback when a wrong option was specified for comparison default_values = dict( stop_timeout='ignore', ) for option, data in self.module.argument_spec.items(): all_options.add(option) for alias in data.get('aliases', []): all_options.add(alias) # Ignore options which aren't used as container properties if option in self.__NON_CONTAINER_PROPERTY_OPTIONS and option != 'networks': continue # Determine option type if option in explicit_types: datatype = explicit_types[option] elif data['type'] == 'list': datatype = 'set' elif data['type'] == 'dict': datatype = 'dict' else: datatype = 'value' # Determine comparison type if option in default_values: comparison = default_values[option] elif datatype in ('list', 'value'): comparison = 'strict' else: comparison = 'allow_more_present' comparisons[option] = dict(type=datatype, comparison=comparison, name=option) # Keep track of aliases comp_aliases[option] = option for alias in data.get('aliases', []): comp_aliases[alias] = option # Process legacy ignore options if self.module.params['ignore_image']: comparisons['image']['comparison'] = 'ignore' if self.module.params['purge_networks']: comparisons['networks']['comparison'] = 'strict' # Process options if self.module.params.get('comparisons'): # If '*' appears in comparisons, process it first if '*' in self.module.params['comparisons']: value = self.module.params['comparisons']['*'] if value not in ('strict', 'ignore'): self.fail("The wildcard can only be used with comparison modes 'strict' and 'ignore'!") for option, v in comparisons.items(): if option == 'networks': # `networks` is special: only update if # some value is actually specified if self.module.params['networks'] is None: continue v['comparison'] = value # Now process all other comparisons. comp_aliases_used = {} for key, value in self.module.params['comparisons'].items(): if key == '*': continue # Find main key key_main = comp_aliases.get(key) if key_main is None: if key_main in all_options: self.fail("The module option '%s' cannot be specified in the comparisons dict, " "since it does not correspond to container's state!" % key) self.fail("Unknown module option '%s' in comparisons dict!" % key) if key_main in comp_aliases_used: self.fail("Both '%s' and '%s' (aliases of %s) are specified in comparisons dict!" % (key, comp_aliases_used[key_main], key_main)) comp_aliases_used[key_main] = key # Check value and update accordingly if value in ('strict', 'ignore'): comparisons[key_main]['comparison'] = value elif value == 'allow_more_present': if comparisons[key_main]['type'] == 'value': self.fail("Option '%s' is a value and not a set/list/dict, so its comparison cannot be %s" % (key, value)) comparisons[key_main]['comparison'] = value else: self.fail("Unknown comparison mode '%s'!" % value) # Add implicit options comparisons['publish_all_ports'] = dict(type='value', comparison='strict', name='published_ports') comparisons['expected_ports'] = dict(type='dict', comparison=comparisons['published_ports']['comparison'], name='expected_ports') comparisons['disable_healthcheck'] = dict(type='value', comparison='ignore' if comparisons['healthcheck']['comparison'] == 'ignore' else 'strict', name='disable_healthcheck') # Check legacy values if self.module.params['ignore_image'] and comparisons['image']['comparison'] != 'ignore': self.module.warn('The ignore_image option has been overridden by the comparisons option!') if self.module.params['purge_networks'] and comparisons['networks']['comparison'] != 'strict': self.module.warn('The purge_networks option has been overridden by the comparisons option!') self.comparisons = comparisons def _get_additional_minimal_versions(self): stop_timeout_supported = self.docker_api_version >= LooseVersion('1.25') stop_timeout_needed_for_update = self.module.params.get("stop_timeout") is not None and self.module.params.get('state') != 'absent' if stop_timeout_supported: stop_timeout_supported = self.docker_py_version >= LooseVersion('2.1') if stop_timeout_needed_for_update and not stop_timeout_supported: # We warn (instead of fail) since in older versions, stop_timeout was not used # to update the container's configuration, but only when stopping a container. self.module.warn("Docker SDK for Python's version is %s. Minimum version required is 2.1 to update " "the container's stop_timeout configuration. " "If you use the 'docker-py' module, you have to switch to the 'docker' Python package." % (docker_version,)) else: if stop_timeout_needed_for_update and not stop_timeout_supported: # We warn (instead of fail) since in older versions, stop_timeout was not used # to update the container's configuration, but only when stopping a container. self.module.warn("Docker API version is %s. Minimum version required is 1.25 to set or " "update the container's stop_timeout configuration." % (self.docker_api_version_str,)) self.option_minimal_versions['stop_timeout']['supported'] = stop_timeout_supported def __init__(self, **kwargs): option_minimal_versions = dict( # internal options log_config=dict(), publish_all_ports=dict(), ports=dict(), volume_binds=dict(), name=dict(), # normal options device_read_bps=dict(docker_py_version='1.9.0', docker_api_version='1.22'), device_read_iops=dict(docker_py_version='1.9.0', docker_api_version='1.22'), device_write_bps=dict(docker_py_version='1.9.0', docker_api_version='1.22'), device_write_iops=dict(docker_py_version='1.9.0', docker_api_version='1.22'), dns_opts=dict(docker_api_version='1.21', docker_py_version='1.10.0'), ipc_mode=dict(docker_api_version='1.25'), mac_address=dict(docker_api_version='1.25'), oom_score_adj=dict(docker_api_version='1.22'), shm_size=dict(docker_api_version='1.22'), stop_signal=dict(docker_api_version='1.21'), tmpfs=dict(docker_api_version='1.22'), volume_driver=dict(docker_api_version='1.21'), memory_reservation=dict(docker_api_version='1.21'), kernel_memory=dict(docker_api_version='1.21'), auto_remove=dict(docker_py_version='2.1.0', docker_api_version='1.25'), healthcheck=dict(docker_py_version='2.0.0', docker_api_version='1.24'), init=dict(docker_py_version='2.2.0', docker_api_version='1.25'), runtime=dict(docker_py_version='2.4.0', docker_api_version='1.25'), sysctls=dict(docker_py_version='1.10.0', docker_api_version='1.24'), userns_mode=dict(docker_py_version='1.10.0', docker_api_version='1.23'), uts=dict(docker_py_version='3.5.0', docker_api_version='1.25'), pids_limit=dict(docker_py_version='1.10.0', docker_api_version='1.23'), mounts=dict(docker_py_version='2.6.0', docker_api_version='1.25'), cpus=dict(docker_py_version='2.3.0', docker_api_version='1.25'), # specials ipvX_address_supported=dict(docker_py_version='1.9.0', docker_api_version='1.22', detect_usage=detect_ipvX_address_usage, usage_msg='ipv4_address or ipv6_address in networks'), stop_timeout=dict(), # see _get_additional_minimal_versions() ) super(AnsibleDockerClientContainer, self).__init__( option_minimal_versions=option_minimal_versions, option_minimal_versions_ignore_params=self.__NON_CONTAINER_PROPERTY_OPTIONS, **kwargs ) self.image_inspect_source = 'Config' if self.docker_api_version < LooseVersion('1.21'): self.image_inspect_source = 'ContainerConfig' self._get_additional_minimal_versions() self._parse_comparisons() if self.module.params['container_default_behavior'] is None: self.module.params['container_default_behavior'] = 'compatibility' self.module.deprecate( 'The container_default_behavior option will change its default value from "compatibility" to ' '"no_defaults" in Ansible 2.14. To remove this warning, please specify an explicit value for it now', version='2.14' ) if self.module.params['container_default_behavior'] == 'compatibility': old_default_values = dict( auto_remove=False, detach=True, init=False, interactive=False, memory="0", paused=False, privileged=False, read_only=False, tty=False, ) for param, value in old_default_values.items(): if self.module.params[param] is None: self.module.params[param] = value def main(): argument_spec = dict( auto_remove=dict(type='bool'), blkio_weight=dict(type='int'), capabilities=dict(type='list', elements='str'), cap_drop=dict(type='list', elements='str'), cleanup=dict(type='bool', default=False), command=dict(type='raw'), comparisons=dict(type='dict'), container_default_behavior=dict(type='str', choices=['compatibility', 'no_defaults']), cpu_period=dict(type='int'), cpu_quota=dict(type='int'), cpus=dict(type='float'), cpuset_cpus=dict(type='str'), cpuset_mems=dict(type='str'), cpu_shares=dict(type='int'), detach=dict(type='bool'), devices=dict(type='list', elements='str'), device_read_bps=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='str'), )), device_write_bps=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='str'), )), device_read_iops=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='int'), )), device_write_iops=dict(type='list', elements='dict', options=dict( path=dict(required=True, type='str'), rate=dict(required=True, type='int'), )), dns_servers=dict(type='list', elements='str'), dns_opts=dict(type='list', elements='str'), dns_search_domains=dict(type='list', elements='str'), domainname=dict(type='str'), entrypoint=dict(type='list', elements='str'), env=dict(type='dict'), env_file=dict(type='path'), etc_hosts=dict(type='dict'), exposed_ports=dict(type='list', elements='str', aliases=['exposed', 'expose']), force_kill=dict(type='bool', default=False, aliases=['forcekill']), groups=dict(type='list', elements='str'), healthcheck=dict(type='dict', options=dict( test=dict(type='raw'), interval=dict(type='str'), timeout=dict(type='str'), start_period=dict(type='str'), retries=dict(type='int'), )), hostname=dict(type='str'), ignore_image=dict(type='bool', default=False), image=dict(type='str'), init=dict(type='bool'), interactive=dict(type='bool'), ipc_mode=dict(type='str'), keep_volumes=dict(type='bool', default=True), kernel_memory=dict(type='str'), kill_signal=dict(type='str'), labels=dict(type='dict'), links=dict(type='list', elements='str'), log_driver=dict(type='str'), log_options=dict(type='dict', aliases=['log_opt']), mac_address=dict(type='str'), memory=dict(type='str'), memory_reservation=dict(type='str'), memory_swap=dict(type='str'), memory_swappiness=dict(type='int'), mounts=dict(type='list', elements='dict', options=dict( target=dict(type='str', required=True), source=dict(type='str'), type=dict(type='str', choices=['bind', 'volume', 'tmpfs', 'npipe'], default='volume'), read_only=dict(type='bool'), consistency=dict(type='str', choices=['default', 'consistent', 'cached', 'delegated']), propagation=dict(type='str', choices=['private', 'rprivate', 'shared', 'rshared', 'slave', 'rslave']), no_copy=dict(type='bool'), labels=dict(type='dict'), volume_driver=dict(type='str'), volume_options=dict(type='dict'), tmpfs_size=dict(type='str'), tmpfs_mode=dict(type='str'), )), name=dict(type='str', required=True), network_mode=dict(type='str'), networks=dict(type='list', elements='dict', options=dict( name=dict(type='str', required=True), ipv4_address=dict(type='str'), ipv6_address=dict(type='str'), aliases=dict(type='list', elements='str'), links=dict(type='list', elements='str'), )), networks_cli_compatible=dict(type='bool'), oom_killer=dict(type='bool'), oom_score_adj=dict(type='int'), output_logs=dict(type='bool', default=False), paused=dict(type='bool'), pid_mode=dict(type='str'), pids_limit=dict(type='int'), privileged=dict(type='bool'), published_ports=dict(type='list', elements='str', aliases=['ports']), pull=dict(type='bool', default=False), purge_networks=dict(type='bool', default=False), read_only=dict(type='bool'), recreate=dict(type='bool', default=False), restart=dict(type='bool', default=False), restart_policy=dict(type='str', choices=['no', 'on-failure', 'always', 'unless-stopped']), restart_retries=dict(type='int'), runtime=dict(type='str'), security_opts=dict(type='list', elements='str'), shm_size=dict(type='str'), state=dict(type='str', default='started', choices=['absent', 'present', 'started', 'stopped']), stop_signal=dict(type='str'), stop_timeout=dict(type='int'), sysctls=dict(type='dict'), tmpfs=dict(type='list', elements='str'), trust_image_content=dict(type='bool', default=False, removed_in_version='2.14'), tty=dict(type='bool'), ulimits=dict(type='list', elements='str'), user=dict(type='str'), userns_mode=dict(type='str'), uts=dict(type='str'), volume_driver=dict(type='str'), volumes=dict(type='list', elements='str'), volumes_from=dict(type='list', elements='str'), working_dir=dict(type='str'), ) required_if = [ ('state', 'present', ['image']) ] client = AnsibleDockerClientContainer( argument_spec=argument_spec, required_if=required_if, supports_check_mode=True, min_docker_api_version='1.20', ) if client.module.params['networks_cli_compatible'] is None and client.module.params['networks']: client.module.deprecate( 'Please note that docker_container handles networks slightly different than docker CLI. ' 'If you specify networks, the default network will still be attached as the first network. ' '(You can specify purge_networks to remove all networks not explicitly listed.) ' 'This behavior will change in Ansible 2.12. You can change the behavior now by setting ' 'the new `networks_cli_compatible` option to `yes`, and remove this warning by setting ' 'it to `no`', version='2.12' ) if client.module.params['networks_cli_compatible'] is True and client.module.params['networks'] and client.module.params['network_mode'] is None: client.module.deprecate( 'Please note that the default value for `network_mode` will change from not specified ' '(which is equal to `default`) to the name of the first network in `networks` if ' '`networks` has at least one entry and `networks_cli_compatible` is `true`. You can ' 'change the behavior now by explicitly setting `network_mode` to the name of the first ' 'network in `networks`, and remove this warning by setting `network_mode` to `default`. ' 'Please make sure that the value you set to `network_mode` equals the inspection result ' 'for existing containers, otherwise the module will recreate them. You can find out the ' 'correct value by running "docker inspect --format \'{{.HostConfig.NetworkMode}}\' <container_name>"', version='2.14' ) try: cm = ContainerManager(client) client.module.exit_json(**sanitize_result(cm.results)) except DockerException as e: client.fail('An unexpected docker error occurred: {0}'.format(e), exception=traceback.format_exc()) except RequestException as e: client.fail('An unexpected requests error occurred when docker-py tried to talk to the docker daemon: {0}'.format(e), exception=traceback.format_exc()) if __name__ == '__main__': main()
Lujeni/ansible
lib/ansible/modules/cloud/docker/docker_container.py
Python
gpl-3.0
143,393
/* * WebSocketMessage.cpp * * Created on: Sep 10, 2015 * Author: lion */ #include "object.h" #include "ifs/io.h" #include "WebSocketMessage.h" #include "Buffer.h" #include "MemoryStream.h" namespace fibjs { result_t WebSocketMessage_base::_new(int32_t type, bool masked, int32_t maxSize, obj_ptr<WebSocketMessage_base>& retVal, v8::Local<v8::Object> This) { retVal = new WebSocketMessage(type, masked, maxSize); return 0; } result_t WebSocketMessage::get_value(exlib::string& retVal) { return m_message->get_value(retVal); } result_t WebSocketMessage::set_value(exlib::string newVal) { return m_message->set_value(newVal); } result_t WebSocketMessage::get_params(obj_ptr<List_base>& retVal) { return m_message->get_params(retVal); } result_t WebSocketMessage::set_params(List_base* newVal) { return m_message->set_params(newVal); } result_t WebSocketMessage::get_body(obj_ptr<SeekableStream_base>& retVal) { return m_message->get_body(retVal); } result_t WebSocketMessage::set_body(SeekableStream_base* newVal) { return m_message->set_body(newVal); } result_t WebSocketMessage::read(int32_t bytes, obj_ptr<Buffer_base>& retVal, AsyncEvent* ac) { return m_message->read(bytes, retVal, ac); } result_t WebSocketMessage::readAll(obj_ptr<Buffer_base>& retVal, AsyncEvent* ac) { return m_message->readAll(retVal, ac); } result_t WebSocketMessage::write(Buffer_base* data, AsyncEvent* ac) { return m_message->write(data, ac); } result_t WebSocketMessage::get_length(int64_t& retVal) { return m_message->get_length(retVal); } result_t WebSocketMessage::get_lastError(exlib::string& retVal) { return m_message->get_lastError(retVal); } result_t WebSocketMessage::set_lastError(exlib::string newVal) { return m_message->set_lastError(newVal); } result_t WebSocketMessage::end() { return m_message->end(); } result_t WebSocketMessage::isEnded(bool& retVal) { return m_message->isEnded(retVal); } result_t WebSocketMessage::clear() { m_message = new Message(m_bRep); return 0; } result_t WebSocketMessage::copy(Stream_base* from, Stream_base* to, int64_t bytes, uint32_t mask, AsyncEvent* ac) { class asyncCopy : public AsyncState { public: asyncCopy(Stream_base* from, Stream_base* to, int64_t bytes, uint32_t mask, AsyncEvent* ac) : AsyncState(ac) , m_from(from) , m_to(to) , m_bytes(bytes) , m_mask(mask) , m_copyed(0) { set(read); } static int32_t read(AsyncState* pState, int32_t n) { asyncCopy* pThis = (asyncCopy*)pState; int64_t len; pThis->set(write); if (pThis->m_bytes == 0) return pThis->done(); if (pThis->m_bytes > STREAM_BUFF_SIZE) len = STREAM_BUFF_SIZE; else len = pThis->m_bytes; pThis->m_buf.Release(); return pThis->m_from->read((int32_t)len, pThis->m_buf, pThis); } static int32_t write(AsyncState* pState, int32_t n) { asyncCopy* pThis = (asyncCopy*)pState; int32_t blen; pThis->set(read); if (n == CALL_RETURN_NULL) return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed.")); if (pThis->m_mask != 0) { exlib::string strBuffer; int32_t i, n; uint8_t* mask = (uint8_t*)&pThis->m_mask; pThis->m_buf->toString(strBuffer); n = (int32_t)strBuffer.length(); for (i = 0; i < n; i++) strBuffer[i] ^= mask[(pThis->m_copyed + i) & 3]; pThis->m_buf = new Buffer(strBuffer); } pThis->m_buf->get_length(blen); pThis->m_copyed += blen; if (pThis->m_bytes > 0) pThis->m_bytes -= blen; return pThis->m_to->write(pThis->m_buf, pThis); } public: obj_ptr<Stream_base> m_from; obj_ptr<Stream_base> m_to; int64_t m_bytes; uint32_t m_mask; int64_t m_copyed; obj_ptr<Buffer_base> m_buf; }; if (!ac) return CHECK_ERROR(CALL_E_NOSYNC); return (new asyncCopy(from, to, bytes, mask, ac))->post(0); } result_t WebSocketMessage::sendTo(Stream_base* stm, AsyncEvent* ac) { class asyncSendTo : public AsyncState { public: asyncSendTo(WebSocketMessage* pThis, Stream_base* stm, AsyncEvent* ac) : AsyncState(ac) , m_pThis(pThis) , m_stm(stm) , m_mask(0) { m_pThis->get_body(m_body); m_body->rewind(); m_body->size(m_size); m_ms = new MemoryStream(); set(head); } static int32_t head(AsyncState* pState, int32_t n) { asyncSendTo* pThis = (asyncSendTo*)pState; uint8_t buf[16]; int32_t pos = 0; int32_t type; pThis->m_pThis->get_type(type); buf[0] = 0x80 | (type & 0x0f); int64_t size = pThis->m_size; if (size < 126) { buf[1] = (uint8_t)size; pos = 2; } else if (size < 65536) { buf[1] = 126; buf[2] = (uint8_t)(size >> 8); buf[3] = (uint8_t)(size & 0xff); pos = 4; } else { buf[1] = 127; buf[2] = (uint8_t)((size >> 56) & 0xff); buf[3] = (uint8_t)((size >> 48) & 0xff); buf[4] = (uint8_t)((size >> 40) & 0xff); buf[5] = (uint8_t)((size >> 32) & 0xff); buf[6] = (uint8_t)((size >> 24) & 0xff); buf[7] = (uint8_t)((size >> 16) & 0xff); buf[8] = (uint8_t)((size >> 8) & 0xff); buf[9] = (uint8_t)(size & 0xff); pos = 10; } if (pThis->m_pThis->m_masked) { buf[1] |= 0x80; uint32_t r = 0; while (r == 0) r = rand(); pThis->m_mask = r; buf[pos++] = (uint8_t)(r & 0xff); buf[pos++] = (uint8_t)((r >> 8) & 0xff); buf[pos++] = (uint8_t)((r >> 16) & 0xff); buf[pos++] = (uint8_t)((r >> 24) & 0xff); } pThis->m_buffer = new Buffer((const char*)buf, pos); pThis->set(sendData); return pThis->m_ms->write(pThis->m_buffer, pThis); } static int32_t sendData(AsyncState* pState, int32_t n) { asyncSendTo* pThis = (asyncSendTo*)pState; pThis->set(sendToStream); return copy(pThis->m_body, pThis->m_ms, pThis->m_size, pThis->m_mask, pThis); } static int32_t sendToStream(AsyncState* pState, int32_t n) { asyncSendTo* pThis = (asyncSendTo*)pState; pThis->m_ms->rewind(); pThis->set(NULL); return io_base::copyStream(pThis->m_ms, pThis->m_stm, -1, pThis->m_size, pThis); } public: obj_ptr<MemoryStream_base> m_ms; WebSocketMessage* m_pThis; obj_ptr<Stream_base> m_stm; obj_ptr<SeekableStream_base> m_body; int64_t m_size; uint32_t m_mask; obj_ptr<Buffer_base> m_buffer; }; if (!ac) return CHECK_ERROR(CALL_E_NOSYNC); return (new asyncSendTo(this, stm, ac))->post(0); } result_t WebSocketMessage::readFrom(Stream_base* stm, AsyncEvent* ac) { class asyncReadFrom : public AsyncState { public: asyncReadFrom(WebSocketMessage* pThis, Stream_base* stm, AsyncEvent* ac) : AsyncState(ac) , m_pThis(pThis) , m_stm(stm) , m_fin(false) , m_masked(false) , m_fragmented(false) , m_size(0) , m_fullsize(0) , m_mask(0) { m_pThis->get_body(m_body); set(head); } static int32_t head(AsyncState* pState, int32_t n) { asyncReadFrom* pThis = (asyncReadFrom*)pState; pThis->set(extHead); return pThis->m_stm->read(2, pThis->m_buffer, pThis); } static int32_t extHead(AsyncState* pState, int32_t n) { asyncReadFrom* pThis = (asyncReadFrom*)pState; if (n == CALL_RETURN_NULL) { pThis->m_pThis->m_error = 1001; return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed.")); } exlib::string strBuffer; char ch; int32_t sz = 0; pThis->m_buffer->toString(strBuffer); pThis->m_buffer.Release(); ch = strBuffer[0]; if (ch & 0x70) { pThis->m_pThis->m_error = 1007; return CHECK_ERROR(Runtime::setError("WebSocketMessage: non-zero RSV values.")); } pThis->m_fin = (ch & 0x80) != 0; if (pThis->m_fragmented) { if ((ch & 0x0f) != ws_base::_CONTINUE) { pThis->m_pThis->m_error = 1007; return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed.")); } } else pThis->m_pThis->set_type(ch & 0x0f); ch = strBuffer[1]; if (pThis->m_fragmented) { if (pThis->m_masked != (pThis->m_pThis->m_masked = (ch & 0x80) != 0)) { pThis->m_pThis->m_error = 1007; return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed.")); } } else pThis->m_masked = pThis->m_pThis->m_masked = (ch & 0x80) != 0; if (pThis->m_masked) sz += 4; pThis->m_size = ch & 0x7f; if (pThis->m_size == 126) sz += 2; else if (pThis->m_size == 127) sz += 8; if (sz) { pThis->set(extReady); return pThis->m_stm->read(sz, pThis->m_buffer, pThis); } pThis->set(body); return 0; } static int32_t extReady(AsyncState* pState, int32_t n) { asyncReadFrom* pThis = (asyncReadFrom*)pState; if (n == CALL_RETURN_NULL) { pThis->m_pThis->m_error = 1007; return CHECK_ERROR(Runtime::setError("WebSocketMessage: payload processing failed.")); } exlib::string strBuffer; int32_t pos = 0; pThis->m_buffer->toString(strBuffer); pThis->m_buffer.Release(); if (pThis->m_size == 126) { pThis->m_size = ((uint32_t)(uint8_t)strBuffer[0] << 8) + (uint8_t)strBuffer[1]; pos += 2; } else if (pThis->m_size == 127) { pThis->m_size = ((int64_t)(uint8_t)strBuffer[0] << 56) + ((int64_t)(uint8_t)strBuffer[1] << 48) + ((int64_t)(uint8_t)strBuffer[2] << 40) + ((int64_t)(uint8_t)strBuffer[3] << 32) + ((int64_t)(uint8_t)strBuffer[4] << 24) + ((int64_t)(uint8_t)strBuffer[5] << 16) + ((int64_t)(uint8_t)strBuffer[6] << 8) + (int64_t)(uint8_t)strBuffer[7]; pos += 8; } if (pThis->m_masked) memcpy(&pThis->m_mask, &strBuffer[pos], 4); pThis->set(body); return 0; } static int32_t body(AsyncState* pState, int32_t n) { asyncReadFrom* pThis = (asyncReadFrom*)pState; if (pThis->m_fullsize + pThis->m_size > pThis->m_pThis->m_maxSize) { pThis->m_pThis->m_error = 1009; return CHECK_ERROR(Runtime::setError("WebSocketMessage: Message Too Big.")); } pThis->set(body_end); return copy(pThis->m_stm, pThis->m_body, pThis->m_size, pThis->m_mask, pThis); } static int32_t body_end(AsyncState* pState, int32_t n) { asyncReadFrom* pThis = (asyncReadFrom*)pState; if (!pThis->m_fin) { pThis->m_fragmented = true; pThis->m_mask = 0; pThis->m_fullsize += pThis->m_size; pThis->set(head); return 0; } pThis->m_body->rewind(); return pThis->done(); } public: WebSocketMessage* m_pThis; obj_ptr<Stream_base> m_stm; obj_ptr<SeekableStream_base> m_body; obj_ptr<Buffer_base> m_buffer; bool m_fin; bool m_masked; bool m_fragmented; int64_t m_size; int64_t m_fullsize; uint32_t m_mask; }; if (!ac) return CHECK_ERROR(CALL_E_NOSYNC); m_stm = stm; return (new asyncReadFrom(this, stm, ac))->post(0); } result_t WebSocketMessage::get_stream(obj_ptr<Stream_base>& retVal) { if (!m_stm) return CALL_RETURN_NULL; retVal = m_stm; return 0; } result_t WebSocketMessage::get_response(obj_ptr<Message_base>& retVal) { if (m_bRep) return CHECK_ERROR(CALL_E_INVALID_CALL); if (!m_message->m_response) { int32_t type; get_type(type); if (type == ws_base::_PING) type = ws_base::_PONG; m_message->m_response = new WebSocketMessage(type, false, m_maxSize, true); } return m_message->get_response(retVal); } result_t WebSocketMessage::get_type(int32_t& retVal) { return m_message->get_type(retVal); } result_t WebSocketMessage::set_type(int32_t newVal) { return m_message->set_type(newVal); } result_t WebSocketMessage::get_data(v8::Local<v8::Value>& retVal) { return m_message->get_data(retVal); } result_t WebSocketMessage::get_masked(bool& retVal) { retVal = m_masked; return 0; } result_t WebSocketMessage::set_masked(bool newVal) { m_masked = newVal; return 0; } result_t WebSocketMessage::get_maxSize(int32_t& retVal) { retVal = m_maxSize; return 0; } result_t WebSocketMessage::set_maxSize(int32_t newVal) { if (newVal < 0) return CHECK_ERROR(CALL_E_OUTRANGE); m_maxSize = newVal; return 0; } } /* namespace fibjs */
ngot/nightly-test
fibjs/src/websocket/WebSocketMessage.cpp
C++
gpl-3.0
14,485
# This file is part of GxSubOS. # Copyright (C) 2014 Christopher Kyle Horton <christhehorton@gmail.com> # GxSubOS 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. # GxSubOS 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 GxSubOS. If not, see <http://www.gnu.org/licenses/>. import sys, pygame from indicator import Indicator import glass, shadow transparent = pygame.color.Color(0, 0, 0, 0) class IndicatorTray(): '''A class implementing a tray where various Indicators are displayed.''' tray_color = glass.glass_color tray_color_opaque = glass.glass_color tray_color.a = glass.glass_alpha tray_height = 24 shadow_height = 10 def __init__(self, screenw, screenh, wm=None): self.indicator_list = [] self.surface = glass.MakeTransparentSurface(screenw, self.tray_height + self.shadow_height) if glass.enable_transparency: self.surface.fill(self.tray_color) self.color_surface = pygame.Surface((screenw, self.tray_height), pygame.SRCALPHA) self.color_surface.fill(self.tray_color) else: self.surface.fill(self.tray_color_opaque) self.color_surface = pygame.Surface((screenw, self.tray_height)) self.color_surface.fill(self.tray_color_opaque) self.update_rect = pygame.Rect(0, 0, 0, 0) self.wm = wm def SetWindowManager(self, windowmanager): '''Sets the WindowManager that this IndicatorTray will connect to.''' self.wm = windowmanager def GetIndicatorsWidth(self): '''Returns the total width in pixels of all the Indicators currently stored in the indicator_list.''' width = 0 for indicator in self.indicator_list: width += indicator.width return width def UpdateIndicatorPositions(self): '''Updates the positions of all the Indicators in the list.''' next_right = 0 for indicator in self.indicator_list: new_x = pygame.display.Info().current_w - next_right - indicator.width self.update_rect.union_ip(indicator.UpdatePosition(new_x)) next_right += indicator.width def RedrawBackground(self, screen): '''Redraw the background behind the Indicators.''' tray_width = self.GetIndicatorsWidth() tray_left = pygame.display.Info().current_w - tray_width glass.DrawBackground(screen, self.surface, self.surface.get_rect()) if glass.enable_transparency: self.surface = glass.Blur(self.surface) self.surface.blit(self.color_surface, [0, 0, 0, 0]) triangle_points = [(tray_left - self.tray_height, 0), (tray_left - self.tray_height, self.tray_height), (tray_left, self.tray_height)] pygame.draw.polygon(self.surface, transparent, triangle_points) pygame.draw.rect(self.surface, transparent, pygame.Rect(0, 0, tray_left - self.tray_height, self.tray_height)) pygame.draw.rect(self.surface, transparent, pygame.Rect(0, self.tray_height, self.surface.get_width(), self.surface.get_height() - self.tray_height)) shadow.DrawIndicatorTrayShadow(self) def DrawTray(self, screen): '''Draws this IndicatorTray onto the provided Surface. Returns a Rect containing the area which was drawn to.''' screen.blit(self.surface, (0, 0)) for indicator in self.indicator_list: screen.blit(indicator.image, indicator.rect) return self.update_rect def UpdateWholeTray(self, screen): '''Update the whole IndicatorTray and its Indicators.''' self.UpdateIndicatorPositions() for indicator in self.indicator_list: indicator.RunFrameCode() self.RemoveClosedIndicators() self.RedrawBackground(screen) def AddIndicator(self, indicator_name): '''Adds the given Indicator based on the provided name. Returns a reference to the Indicator added.''' indicator = Indicator(len(self.indicator_list), indicator_name, self.wm) self.indicator_list.append(indicator) return indicator def RemoveClosedIndicators(self): '''Removes any Indicators which indicate that they are closed.''' for indicator in self.indicator_list: if indicator.closed == True: self.indicator_list.remove(indicator) # Maintain indicator order new_number = 0 for indicator in self.indicator_list: indicator.number = new_number def HandleMouseButtonDownEvent(self, mouse_event, mouse_button): '''Pass MOUSEDOWN events to the Indicators this holds.''' for indicator in self.indicator_list: indicator.HandleMouseButtonDownEvent(mouse_event, mouse_button)
WarriorIng64/GxSubOS
indicatortray.py
Python
gpl-3.0
4,871
package com.glue.feed.youtube; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Properties; import java.util.TimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.glue.domain.Event; import com.glue.domain.Link; import com.glue.domain.LinkType; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.youtube.YouTube; import com.google.api.services.youtube.model.SearchListResponse; import com.google.api.services.youtube.model.SearchResult; import com.google.api.services.youtube.model.Video; import com.google.api.services.youtube.model.VideoListResponse; public class YoutubeRequester { static final Logger LOG = LoggerFactory.getLogger(YoutubeRequester.class); /** Global instance properties filename. */ private static String PROPERTIES_FILENAME = "/com/glue/feed/youtube.properties"; /** Global instance of the HTTP transport. */ private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); /** Global instance of the JSON factory. */ private static final JsonFactory JSON_FACTORY = new JacksonFactory(); /** * Global instance of the max number of videos we want returned (50 = upper * limit per page). */ private static final long NUMBER_OF_VIDEOS_RETURNED = 25; /** Global instance of Youtube object to make all API requests. */ private static YouTube youtube; /** Properties */ private Properties properties; private DateFormat formater = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'"); private Calendar calendar = Calendar.getInstance(TimeZone .getTimeZone("UTC")); // Current research private YouTube.Search.List search; // Videos details private YouTube.Videos.List searchForVideos; private YoutubeRequester() { initialize(); } /** Singleton Holder */ private static class YoutubeRequesterHolder { /** Singleton */ private final static YoutubeRequester instance = new YoutubeRequester(); } /** Get Singleton */ public static YoutubeRequester getInstance() { return YoutubeRequesterHolder.instance; } private void initialize() { // youtube.properties properties = new Properties(); try { InputStream in = YoutubeRequester.class .getResourceAsStream(PROPERTIES_FILENAME); properties.load(in); } catch (IOException e) { System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : " + e.getMessage()); System.exit(1); } try { /* * The YouTube object is used to make all API requests. The last * argument is required, but because we don't need anything * initialized when the HttpRequest is initialized, we override the * interface and provide a no-op function. */ youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() { public void initialize(HttpRequest request) throws IOException { } }).setApplicationName("Glue").build(); } catch (Throwable t) { t.printStackTrace(); System.exit(1); } calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")); } public Event search(Event event) throws IOException { // Create a youtube search list search = youtube.search().list("id,snippet"); String apiKey = properties.getProperty("youtube.apikey"); search.setKey(apiKey); search.set("safeSearch", "moderate"); search.set("videoEmbeddable", "true"); search.setType("video"); search.setFields("items(id/videoId,snippet/title)"); search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED); // Set calendar to enddate calendar.setTime(event.getStopTime()); // Query stream title + stream venue + day + month (january = 0) search.setQ(event.getTitle() + " " + event.getVenue().getName()); // Published after stream end_date search.set("publishedAfter", formater.format(calendar.getTime())); // Published before enddate +30 calendar.add(Calendar.DATE, +30); search.set("publishedBefore", formater.format(calendar.getTime())); // Search SearchListResponse searchResponse = search.execute(); // If videos found if (!searchResponse.getItems().isEmpty()) { // Create a string a videos ids separated by comma List<String> videosIds = new ArrayList<>(); for (SearchResult video : searchResponse.getItems()) { videosIds.add(video.getId().getVideoId()); } String ids = ""; for (String vId : videosIds) { ids += vId + ","; } // Remove last comma ids = ids.substring(0, ids.lastIndexOf(",")); // Search for videos details searchForVideos = youtube.videos().list(ids, "snippet"); searchForVideos.setKey(properties.getProperty("youtube.apikey")); search.setFields("items(snippet/title,snippet/description)"); VideoListResponse videosResponse = searchForVideos.execute(); // for each videos, check similarity and create media for (Video video : videosResponse.getItems()) { if (checkSimilarity(event, video)) { LOG.info(video.getSnippet().getTitle()); Link link = new Link(); link.setType(LinkType.WEBCAST); link.setUrl("http://www.youtube.com/embed/" + video.getId()); event.getLinks().add(link); } } } return event; } // Check similarity between youtube video and stream private boolean checkSimilarity(Event event, Video video) { // Get title and description from video String vTitle = video.getSnippet().getTitle().toLowerCase().trim(); String vDescription = video.getSnippet().getDescription().toLowerCase() .trim(); // Stream title String sTitle = event.getTitle().toLowerCase(); // Stream description, remove "le" "la" String venue = event.getVenue().getName().toLowerCase(); if (venue.startsWith("le ")) { venue = venue.substring(3); } else if (venue.startsWith("la ")) { venue = venue.substring(3); } // Video title must contain stream title boolean filterOne = vTitle.matches(".*\\b" + sTitle + "\\b.*"); // Title or description must contain venue name boolean filterTwo = (vTitle.contains(venue)) || (vDescription.contains(venue)); return filterOne && filterTwo; } }
pgillet/Glue
glue-feed/src/main/java/com/glue/feed/youtube/YoutubeRequester.java
Java
gpl-3.0
6,629
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Identity.EntityFramework; using System.Security.Claims; using Microsoft.AspNet.Identity; namespace LanAdeptData.Model { public class User : IdentityUser { [Required] [Display(Name = "Nom complet")] public string CompleteName { get; set; } public string Barcode { get; set; } #region Navigation properties public virtual ICollection<Reservation> Reservations { get; set; } public virtual ICollection<Team> Teams { get; set; } public virtual ICollection<Order> Orders { get; set; } #endregion #region Calculated properties public Reservation LastReservation { get { return Reservations.OrderBy(r => r.CreationDate).LastOrDefault(); } } #endregion #region Identity Methods public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager) { var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); return userIdentity; } #endregion } }
ADEPT-Informatique/LanAdept
LanAdeptData/Model/Users/User.cs
C#
gpl-3.0
1,133
package to.oa.qha98.ballisticCalculator.test; import static org.junit.Assert.*; import org.bukkit.util.Vector; import org.junit.Test; public class VectorDefaultConstructorTest { @Test public void test() { Vector v=new Vector(); assertEquals(0d, v.length(), 0.0000001d); } }
qha98/BallisticCalculator
BalisticCalculator/BallisticCalculator/to/oa/qha98/ballisticCalculator/test/VectorDefaultConstructorTest.java
Java
gpl-3.0
298
<?php use Phalcon\Di\FactoryDefault; error_reporting(E_ALL); define('APP_PATH', realpath('..')); try { /** * The FactoryDefault Dependency Injector automatically register the right services providing a full stack framework */ $di = new FactoryDefault(); /** * Read services */ include APP_PATH . "/app/config/services.php"; /** * Call the autoloader service. We don't need to keep the results. */ $di->getLoader(); /** * Handle the request */ $application = new \Phalcon\Mvc\Application($di); echo $application->handle()->getContent(); } catch (\Exception $e) { echo $e->getMessage() . '<br>'; echo '<pre>' . $e->getTraceAsString() . '</pre>'; }
acidopal/crud_phalcon
public/index.php
PHP
gpl-3.0
740
# Copyright (C) 2015-2016 Daniel Sel # # 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 # __all__ = [ "__author__", "__copyright__", "__email__", "__license__", "__summary__", "__title__", "__uri__", "__version__", ] __version__ = "0.0.1" __title__ = "KNOCK Server" __uri__ = "https://github.com/DanielSel/knock" __summary__ = "Transparent server service for the secure authenticated scalable port-knocking implementation \"KNOCK\"" __author__ = "Daniel Sel" __license__ = "GNU General Public License" __copyright__ = "Copyright 2015-2016 {0}".format(__author__)
tumi8/sKnock
server/version.py
Python
gpl-3.0
1,225
//////////////////////////////////////////////////////////////////// // // // Part of this source file is taken from Virtual Choreographer // http://virchor.sourceforge.net/ // // File pg-draw.cpp // // // 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 2.1 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA. //////////////////////////////////////////////////////////////////// #include "pg-all_include.h" int user_id; #define NB_ATTACHMENTS 3 extern char currentFilename[512]; ///////////////////////////////////////////////////////////////// // config variables float mouse_x; float mouse_y; float mouse_x_prev; float mouse_y_prev; float mouse_x_deviation; float mouse_y_deviation; // PG_NB_TRACKS tacks + external tablet float tracks_x[PG_NB_TRACKS + 1]; float tracks_y[PG_NB_TRACKS + 1]; float tracks_x_prev[PG_NB_TRACKS + 1]; float tracks_y_prev[PG_NB_TRACKS + 1]; // PG_NB_TRACKS tacks float tracks_Color_r[PG_NB_TRACKS]; float tracks_Color_g[PG_NB_TRACKS]; float tracks_Color_b[PG_NB_TRACKS]; float tracks_Color_a[PG_NB_TRACKS]; int tracks_BrushID[PG_NB_TRACKS]; // PG_NB_TRACKS tacks + external tablet float tracks_RadiusX[PG_NB_TRACKS + 1]; float tracks_RadiusY[PG_NB_TRACKS + 1]; ///////////////////////////////////////////////////////////////// // Projection and view matrices for the shader GLfloat projMatrix[16]; GLfloat doubleProjMatrix[16]; GLfloat viewMatrix[16]; GLfloat modelMatrix[16]; GLfloat modelMatrixSensor[16]; ///////////////////////////////////////////////////////////////// // textures bitmaps and associated IDs GLuint pg_screenMessageBitmap_ID = NULL_ID; // nb_attachments=1 GLubyte *pg_screenMessageBitmap = NULL; GLuint pg_tracks_Pos_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_Pos_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_tracks_Col_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_Col_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_tracks_RadBrushRendmode_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_RadBrushRendmode_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_tracks_Pos_target_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_Pos_target_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_tracks_Col_target_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_Col_target_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_tracks_RadBrushRendmode_target_Texture_ID[PG_NB_TRACKS] = { NULL_ID , NULL_ID , NULL_ID }; GLfloat *pg_tracks_RadBrushRendmode_target_Texture[PG_NB_TRACKS] = { NULL , NULL , NULL }; GLuint pg_CA_data_table_ID = NULL_ID; GLubyte *pg_CA_data_table = NULL; GLuint Font_texture_Rectangle = NULL_ID; cv::Mat Font_image; GLuint Pen_texture_2D = NULL_ID; cv::Mat Pen_image; GLuint Sensor_texture_rectangle = NULL_ID; cv::Mat Sensor_image; GLuint LYMlogo_texture_rectangle = NULL_ID; cv::Mat LYMlogo_image; GLuint trackBrush_texture_2D = NULL_ID; cv::Mat trackBrush_image; // GLuint trackNoise_texture_Rectangle = NULL_ID; // cv::Mat trackNoise_image; GLuint Particle_acceleration_texture_3D = NULL_ID; const char *TextureEncodingString[EmptyTextureEncoding + 1] = { "jpeg" , "png" , "pnga" , "png_gray" , "pnga_gray" , "rgb", "raw" , "emptyimagetype" }; //////////////////////////////////////// // geometry: quads int nbFaces = 2; // 6 squares made of 2 triangles unsigned int quadDraw_vao = 0; unsigned int quadFinal_vao = 0; unsigned int quadSensor_vao = 0; // quad for first and second pass (drawing and compositing) float quadDraw_points[] = { 0.0f, 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; float quadDraw_texCoords[] = { 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f }; // quad for third pass (display - possibly double screen) float quadFinal_points[] = { 0.0f, 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; float quadFinal_texCoords[] = { 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f }; // quad for sensors float quadSensor_points[] = { 0.0f, 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; float quadSensor_texCoords[] = { 0.0f, 0.0f, //1st triangle 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, //2nd triangle 0.0f, 0.0f, 0.0f, 0.0f }; //////////////////////////////////////// // geometry: track lines unsigned int line_tracks_vao[PG_NB_TRACKS] = {0,0,0}; unsigned int line_tracks_target_vao[PG_NB_TRACKS] = {0,0,0}; float *line_tracks_points[PG_NB_TRACKS] = { NULL , NULL , NULL }; float *line_tracks_target_points[PG_NB_TRACKS] = { NULL , NULL , NULL }; ////////////////////////////////////////////////////////////////////// // SENSORS ////////////////////////////////////////////////////////////////////// // sensor translations // current sensor layout float sensorPositions[ 3 * PG_NB_SENSORS]; // all possible sensor layouts float sensorLayouts[ 3 * PG_NB_SENSORS * PG_NB_MAX_SENSOR_LAYOUTS]; // sensor on off // current sensor activation pattern bool sensor_onOff[ PG_NB_SENSORS]; double sensor_last_activation_time; // all sensor activation patterns bool sensorActivations[ PG_NB_SENSORS * PG_NB_MAX_SENSOR_ACTIVATIONS]; // sample choice // current sample choice int sample_choice[ PG_NB_SENSORS]; // all possible sensor layouts int sample_setUps[ PG_NB_MAX_SAMPLE_SETUPS][ PG_NB_SENSORS ] = {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}, {26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50}, {51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75}}; // groups of samples for aliasing with additive samples int sample_groups[ 18 ][ 4 ] = { { 1, 2, 6, 7 }, { 4, 5, 9, 10 }, { 16, 17, 21, 22 }, { 19, 20, 24, 25 }, { 8, 12, 14, 18 }, { 3, 11, 15, 23 }, { 26, 27, 31, 32 }, { 29, 30, 34, 35 }, { 41, 42, 46, 48 }, { 44, 45, 49, 50 }, { 33, 37, 39, 43 }, { 28, 36, 40, 48 }, { 51, 52, 56, 57 }, { 54, 55, 59, 60 }, { 66, 67, 71, 72 }, { 69, 70, 74, 75 }, { 58, 62, 64, 68 }, { 53, 61, 65, 73 } }; // current sensor int currentSensor = 0; // sensor follows mouse bool sensorFollowMouse_onOff = false; ////////////////////////////////////////////////////////////////////// // TEXT ////////////////////////////////////////////////////////////////////// GLbyte stb__arial_10_usascii_x[95]={ 0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; GLubyte stb__arial_10_usascii_y[95]={ 8,1,1,1,1,1,1,1,1,1,1,2,7,5, 7,1,1,1,1,1,1,1,1,1,1,1,3,3,2,3,2,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,1,3,1,3,1,3,1,3,1,1, 1,1,1,3,3,3,3,3,3,3,1,3,3,3,3,3,3,1,1,1,4, }; GLubyte stb__arial_10_usascii_w[95]={ 0,2,3,5,5,8,6,2,3,3,4,5,2,3, 2,3,5,4,5,5,5,5,5,5,5,5,2,2,5,5,5,5,9,7,6,7,6,6,6,7,6,2,4,6, 5,7,6,7,6,7,7,6,6,6,6,9,6,6,6,3,3,2,4,7,3,5,5,5,5,5,3,5,5,2, 3,5,2,7,5,5,5,5,4,5,3,5,5,7,5,5,5,3,2,3,5, }; GLubyte stb__arial_10_usascii_h[95]={ 0,7,3,8,8,8,8,3,9,9,4,5,3,2, 1,8,8,7,7,8,7,8,8,7,8,8,5,7,6,4,6,7,9,7,7,8,7,7,7,8,7,7,8,7, 7,7,7,8,7,8,7,8,7,8,7,7,7,7,7,9,8,9,4,1,2,6,8,6,8,6,7,7,7,7, 9,7,7,5,5,6,7,7,5,6,8,6,5,5,5,7,5,9,9,9,2, }; GLubyte stb__arial_10_usascii_s[95]={ 127,80,80,58,76,82,91,84,1,37,72, 95,77,93,101,110,24,104,13,36,109,70,98,60,114,104,73,123,25,121,31, 7,20,115,66,46,97,90,83,9,73,29,53,53,47,39,32,41,22,1,14, 120,1,17,113,103,96,89,82,30,42,34,67,104,97,37,64,49,30,43,66, 70,60,120,16,8,123,113,107,61,54,76,76,19,49,55,101,87,67,1,81, 12,9,5,87, }; GLubyte stb__arial_10_usascii_t[95]={ 1,20,34,1,1,1,1,34,1,1,34, 28,34,34,34,1,11,20,28,11,20,1,1,20,1,1,28,20,28,28,28, 28,1,20,20,11,20,20,20,11,20,20,1,20,20,20,20,1,20,11,20, 1,20,11,11,11,11,11,11,1,11,1,34,34,34,28,1,28,11,28,11, 11,11,11,1,20,11,28,28,28,11,11,28,28,1,28,28,28,28,28,28, 1,1,1,34, }; GLubyte stb__arial_10_usascii_a[95]={ 40,40,51,80,80,127,96,27, 48,48,56,84,40,48,40,40,80,80,80,80,80,80,80,80, 80,80,40,40,84,84,84,80,145,96,96,103,103,96,87,111, 103,40,72,96,80,119,103,111,96,111,103,96,87,103,96,135, 96,96,87,40,40,40,67,80,48,80,80,72,80,80,40,80, 80,32,32,72,32,119,80,80,80,80,48,72,40,80,72,103, 72,72,72,48,37,48,84, }; GLbyte stb__arial_11_usascii_x[95]={ 0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; GLubyte stb__arial_11_usascii_y[95]={ 8,0,0,0,0,0,0,0,0,0,0,2,7,5, 7,0,0,0,0,0,0,1,0,1,0,0,2,2,2,3,2,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,9,0,2,0,2,0,2,0,2,0,0, 0,0,0,2,2,2,2,2,2,2,1,2,2,2,2,2,2,0,0,0,3, }; GLubyte stb__arial_11_usascii_w[95]={ 0,2,4,6,6,9,7,2,3,3,4,6,2,3, 2,3,6,3,5,6,6,6,6,6,6,6,2,2,6,6,6,5,10,8,7,7,7,7,6,8,7,2,5,7, 6,8,7,8,7,8,7,7,6,7,7,10,7,7,6,3,3,3,5,7,3,6,6,5,5,6,4,5,5,2, 3,5,2,8,5,6,6,5,4,5,3,5,5,8,5,5,5,4,2,4,6, }; GLubyte stb__arial_11_usascii_h[95]={ 0,8,4,9,10,9,9,4,11,11,4,5,3,1, 1,9,9,8,8,9,8,8,9,7,9,9,6,8,5,3,5,8,11,8,8,9,8,8,8,9,8,8,9,8, 8,8,8,9,8,9,8,9,8,9,8,8,8,8,8,10,9,10,5,1,3,7,9,7,9,7,8,9,8,8, 11,8,8,6,6,7,8,8,6,7,8,7,6,6,6,9,6,11,11,11,3, }; GLubyte stb__arial_11_usascii_s[95]={ 125,88,95,67,41,88,98,100,1,33,90, 76,107,124,125,106,39,9,36,52,29,22,81,60,110,1,125,122,69,110,83, 42,22,13,107,117,1,91,115,69,99,53,63,80,73,64,56,58,45,30,37, 8,24,16,12,1,117,109,102,48,59,37,63,103,103,73,74,67,46,87,78, 24,83,125,18,31,125,100,115,80,89,96,121,48,20,54,94,48,109,52,57, 13,10,5,117, }; GLubyte stb__arial_11_usascii_t[95]={ 10,23,40,1,1,1,1,40,1,1,40, 40,40,40,30,1,13,32,32,13,32,32,1,32,1,13,23,23,40,40,40, 32,1,32,23,1,32,23,23,13,23,23,13,23,23,23,23,1,23,13,23, 13,23,13,23,23,13,13,13,1,13,1,40,44,40,32,1,32,13,32,13, 13,13,1,1,23,13,32,32,32,13,13,32,32,23,32,32,40,32,1,40, 1,1,1,40, }; GLubyte stb__arial_11_usascii_a[95]={ 44,44,56,88,88,140,105,30, 52,52,61,92,44,52,44,44,88,88,88,88,88,88,88,88, 88,88,44,44,92,92,92,88,160,105,105,114,114,105,96,123, 114,44,79,105,88,131,114,123,105,123,114,105,96,114,105,149, 105,105,96,44,44,44,74,88,52,88,88,79,88,88,44,88, 88,35,35,79,35,131,88,88,88,88,52,79,44,88,79,114, 79,79,79,53,41,53,92, }; GLbyte stb__arial_12_usascii_x[95]={ 0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; GLubyte stb__arial_12_usascii_y[95]={ 9,1,1,1,0,1,1,1,1,1,1,2,7,5, 7,1,1,1,1,1,1,1,1,1,1,1,3,3,2,3,2,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,10,1,3,1,3,1,3,1,3,1,1, 1,1,1,3,3,3,3,3,3,3,1,3,3,3,3,3,3,1,1,1,4, }; GLubyte stb__arial_12_usascii_w[95]={ 0,3,4,6,6,9,7,2,4,4,4,6,3,4, 3,3,6,4,6,6,6,6,6,6,6,6,3,3,6,6,6,6,11,9,7,8,8,7,7,8,7,2,5,8, 6,9,7,8,7,8,8,7,7,7,8,11,8,8,7,3,3,3,5,8,3,6,6,6,6,6,4,6,6,2, 3,6,2,9,6,6,6,6,4,5,3,6,6,8,6,6,6,4,2,4,6, }; GLubyte stb__arial_12_usascii_h[95]={ 0,8,4,9,11,9,9,4,11,11,4,6,4,2, 2,9,9,8,8,9,8,9,9,8,9,9,6,8,6,4,6,8,11,8,8,9,8,8,8,9,8,8,9,8, 8,8,8,9,8,9,8,9,8,9,8,8,8,8,8,11,9,11,5,2,2,7,9,7,9,7,8,9,8,8, 11,8,8,6,6,7,9,9,6,7,9,7,6,6,6,9,6,11,11,11,3, }; GLubyte stb__arial_12_usascii_s[95]={ 125,116,98,89,1,96,106,95,50,29,86, 55,91,110,123,121,41,1,56,55,70,69,114,31,85,10,62,77,66,79,18, 63,34,46,38,1,22,14,6,76,120,113,100,104,97,87,79,66,71,17,55, 33,47,92,31,19,10,1,115,46,106,21,73,114,110,88,62,101,48,115,110, 26,40,125,25,64,123,8,1,108,82,75,122,95,55,81,41,25,48,59,34, 16,13,8,103, }; GLubyte stb__arial_12_usascii_t[95]={ 10,21,41,1,1,1,1,41,1,1,41, 41,41,44,41,1,13,32,32,11,32,11,1,32,11,13,41,32,41,41,41, 32,1,32,32,13,32,32,32,11,21,21,11,21,21,21,21,1,21,13,21, 13,23,11,23,23,23,23,11,1,11,1,41,41,41,32,11,32,13,32,11, 13,23,1,1,21,11,41,41,32,1,1,32,32,1,32,41,41,41,1,41, 1,1,1,41, }; GLubyte stb__arial_12_usascii_a[95]={ 48,48,61,96,96,153,115,33, 57,57,67,100,48,57,48,48,96,96,96,96,96,96,96,96, 96,96,48,48,100,100,100,96,174,115,115,124,124,115,105,134, 124,48,86,115,96,143,124,134,115,134,124,115,105,124,115,162, 115,115,105,48,48,48,81,96,57,96,96,86,96,96,48,96, 96,38,38,86,38,143,96,96,96,96,57,86,48,96,86,124, 86,86,86,57,45,57,100, }; GLbyte stb__arial_13_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,0,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_13_usascii_y[95]={ 10,1,1,1,0,1,1,1,1,1,1,3,8,6, 8,1,1,1,1,1,1,1,1,1,1,1,3,3,3,4,3,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,11,1,3,1,3,1,3,1,3,1,1, 1,1,1,3,3,3,3,3,3,3,1,3,3,3,3,3,3,1,1,1,4, }; GLubyte stb__arial_13_usascii_w[95]={ 0,2,4,7,6,10,8,2,4,4,5,7,3,4, 2,4,6,4,6,6,6,7,6,6,6,6,2,3,7,7,7,6,12,9,8,8,8,8,7,9,8,2,5,8, 7,9,8,9,8,9,9,8,7,8,8,11,8,8,7,4,4,3,6,8,3,6,6,6,6,6,4,6,6,2, 3,6,2,9,6,7,7,6,5,6,4,6,6,9,6,6,6,4,1,4,7, }; GLubyte stb__arial_13_usascii_h[95]={ 0,9,4,10,12,10,10,4,12,12,5,6,4,2, 2,10,10,9,9,10,9,10,10,9,10,10,7,9,6,4,6,9,12,9,9,10,9,9,9,10,9,9,10,9, 9,9,9,10,9,10,9,10,9,10,9,9,9,9,9,12,10,12,6,2,3,8,10,8,10,8,9,10,9,9, 12,9,9,7,7,8,10,10,7,8,10,8,7,7,7,10,7,12,12,12,3, }; GLubyte stb__arial_13_usascii_s[95]={ 56,125,1,93,1,101,112,123,51,28,105, 97,111,30,27,10,48,19,76,62,90,76,121,50,94,15,47,97,89,115,81, 83,33,66,57,1,41,32,24,84,10,122,110,1,114,104,95,68,83,22,66, 39,55,101,39,27,18,9,1,46,116,20,74,18,6,108,69,1,55,16,121, 32,48,63,24,76,92,30,23,8,85,78,122,115,56,101,40,50,67,61,60, 15,13,8,10, }; GLubyte stb__arial_13_usascii_t[95]={ 12,25,54,1,1,1,1,45,1,1,45, 45,45,54,54,14,14,35,35,14,35,14,1,35,14,14,45,35,45,45,45, 35,1,35,35,14,35,35,35,14,35,25,14,35,25,25,25,1,25,14,25, 14,25,14,25,25,25,25,25,1,14,1,45,54,54,35,14,45,14,45,14, 14,25,25,1,25,25,45,45,45,1,1,35,35,1,35,45,45,45,1,45, 1,1,1,54, }; GLubyte stb__arial_13_usascii_a[95]={ 52,52,66,104,104,166,124,36, 62,62,72,109,52,62,52,52,104,104,104,104,104,104,104,104, 104,104,52,52,109,109,109,104,189,124,124,134,134,124,114,145, 134,52,93,124,104,155,134,145,124,145,134,124,114,134,124,176, 124,124,114,52,52,52,87,104,62,104,104,93,104,104,52,104, 104,41,41,93,41,155,104,104,104,104,62,93,52,104,93,134, 93,93,93,62,48,62,109, }; GLbyte stb__arial_14_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,-1,0,0,0,0,1,0,1,1,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_14_usascii_y[95]={ 11,2,2,1,1,1,1,2,1,1,1,3,9,7, 9,1,1,1,1,1,2,2,1,2,1,1,4,4,3,4,3,1,1,2,2,1,2,2,2,1,2,2,2,2, 2,2,2,1,2,1,2,1,2,2,2,2,2,2,2,2,1,2,1,12,1,4,2,4,2,4,1,4,2,2, 2,2,2,4,4,4,4,4,4,4,2,4,4,4,4,4,4,1,1,1,5, }; GLubyte stb__arial_14_usascii_w[95]={ 0,2,4,7,7,11,9,2,4,4,5,7,2,4, 2,4,7,4,7,7,7,7,7,7,7,7,2,2,7,7,7,7,13,10,8,9,9,8,7,9,8,2,6,9, 7,10,9,10,8,10,9,8,8,9,9,12,9,9,8,4,4,3,6,9,3,7,7,7,7,7,4,7,7,2, 3,7,2,10,7,7,7,7,5,6,4,7,7,9,7,7,6,4,2,4,7, }; GLubyte stb__arial_14_usascii_h[95]={ 0,9,4,11,12,11,11,4,13,13,5,7,4,2, 2,11,11,10,10,11,9,10,11,9,11,11,7,9,7,5,7,10,13,9,9,11,9,9,9,11,9,9,10,9, 9,9,9,11,9,11,9,11,9,10,9,9,9,9,9,12,11,12,6,2,3,8,10,8,10,8,10,10,9,9, 12,9,9,7,7,8,10,10,7,8,10,8,7,7,7,10,7,13,13,13,3, }; GLubyte stb__arial_14_usascii_s[95]={ 59,120,123,70,42,78,108,57,1,19,48, 104,54,123,72,118,1,9,22,9,1,1,17,110,90,45,59,107,62,40,88, 115,24,49,98,98,80,71,63,53,40,123,108,30,22,11,1,59,111,25,88, 36,69,30,49,98,78,59,40,50,123,55,33,75,60,27,84,51,76,12,71, 63,90,60,38,118,9,112,12,35,92,100,20,20,123,43,70,78,96,14,26, 14,11,6,64, }; GLubyte stb__arial_14_usascii_t[95]={ 13,27,48,1,1,1,1,57,1,1,57, 48,57,53,57,1,15,27,27,15,48,27,15,37,1,15,48,37,48,57,48, 15,1,37,37,1,37,37,37,15,37,27,15,38,38,38,38,1,27,15,27, 15,27,27,27,27,27,27,27,1,1,1,57,57,57,48,15,48,15,48,15, 15,37,37,1,37,48,48,57,48,15,15,57,48,15,48,48,48,48,27,57, 1,1,1,57, }; GLubyte stb__arial_14_usascii_a[95]={ 56,56,71,112,112,178,134,38, 67,67,78,117,56,67,56,56,112,112,112,112,112,112,112,112, 112,112,56,56,117,117,117,112,204,134,134,145,145,134,122,156, 145,56,100,134,112,167,145,156,134,156,145,134,122,145,134,189, 134,134,122,56,56,56,94,112,67,112,112,100,112,112,56,112, 112,45,45,100,45,167,112,112,112,112,67,100,56,112,100,145, 100,100,100,67,52,67,117, }; GLbyte stb__arial_15_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,-1,0,0,1,1,1,0,1,1,0,0, 0,0,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_15_usascii_y[95]={ 12,2,2,2,1,2,2,2,2,2,2,4,10,7, 10,2,2,2,2,2,2,2,2,2,2,2,5,5,4,5,4,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,13,2,4,2,4,2,4,2,4,2,2, 2,2,2,4,4,4,4,4,4,4,2,5,5,5,5,5,5,2,2,2,6, }; GLubyte stb__arial_15_usascii_w[95]={ 0,2,5,8,7,12,9,2,4,4,5,8,2,5, 2,4,7,5,7,7,7,7,7,7,7,7,2,2,8,8,8,7,14,10,9,10,8,8,7,10,8,2,6,9, 7,11,8,10,8,10,9,9,8,8,9,13,9,9,8,4,4,3,6,9,4,7,7,7,7,7,5,7,7,3, 4,7,3,11,7,7,7,7,5,7,4,7,7,10,7,7,7,5,2,5,8, }; GLubyte stb__arial_15_usascii_h[95]={ 0,10,4,11,13,11,11,4,13,13,5,7,4,3, 2,11,11,10,10,11,10,11,11,10,11,11,7,9,7,5,7,10,13,10,10,11,10,10,10,11,10,10,11,10, 10,10,10,11,10,11,10,11,10,11,10,10,10,10,10,13,11,13,6,2,3,9,11,9,11,9,10,11,10,10, 13,10,10,8,8,9,11,11,8,9,11,8,7,7,7,10,7,13,13,13,3, }; GLubyte stb__arial_15_usascii_s[95]={ 127,68,60,79,1,104,117,66,58,29,54, 1,69,72,102,1,25,12,105,67,97,83,59,43,109,33,100,123,21,45,103, 18,34,1,113,14,88,79,71,10,59,1,102,33,25,13,4,68,117,91,103, 41,86,1,72,58,48,38,29,49,117,54,38,92,78,42,6,34,75,58,122, 51,21,82,24,95,113,66,92,50,96,88,78,26,63,84,30,10,112,51,120, 18,15,9,83, }; GLubyte stb__arial_15_usascii_t[95]={ 1,39,61,1,1,1,1,61,1,1,61, 61,61,61,61,15,15,50,39,15,39,15,15,39,15,15,50,39,61,61,50, 50,1,50,39,15,39,39,39,27,39,39,15,39,39,39,39,1,27,15,27, 15,27,27,27,27,27,27,27,1,15,1,61,61,61,50,15,50,15,50,15, 15,27,27,1,27,27,50,50,50,1,1,50,50,1,50,61,61,50,39,50, 1,1,1,61, }; GLubyte stb__arial_15_usascii_a[95]={ 60,60,76,119,119,191,143,41, 72,72,84,125,60,72,60,60,119,119,119,119,119,119,119,119, 119,119,60,60,125,125,125,119,218,143,143,155,155,143,131,167, 155,60,107,143,119,179,155,167,143,167,155,143,131,155,143,203, 143,143,131,60,60,60,101,119,72,119,119,107,119,119,60,119, 119,48,48,107,48,179,119,119,119,119,72,107,60,119,107,155, 107,107,107,72,56,72,125, }; GLbyte stb__arial_16_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,-1,1,0,1,1,1,0,1,1,0,1, 1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,0,0,0,0,-1,0,0,0,0,0,0,0,0,0,0, -1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_16_usascii_y[95]={ 12,1,1,1,0,1,1,1,1,1,1,3,10,7, 10,1,1,1,1,1,1,1,1,1,1,1,4,4,3,4,3,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,13,1,4,1,4,1,4,1,4,1,1, 1,1,1,4,4,4,4,4,4,4,1,4,4,4,4,4,4,1,1,1,5, }; GLubyte stb__arial_16_usascii_w[95]={ 0,2,5,8,8,12,10,3,5,5,6,8,2,5, 2,4,8,5,8,8,8,8,8,8,8,8,2,2,8,8,8,8,15,11,8,10,9,8,8,11,9,2,7,9, 7,10,9,11,8,11,10,9,9,9,10,14,10,10,9,4,4,4,7,10,4,8,8,8,7,8,5,8,7,3, 4,8,3,12,7,8,8,7,5,7,4,7,7,11,8,8,7,5,2,5,8, }; GLubyte stb__arial_16_usascii_h[95]={ 0,11,5,12,14,12,12,5,15,15,5,8,5,2, 2,12,12,11,11,12,11,12,12,11,12,12,8,11,8,6,8,11,15,11,11,12,11,11,11,12,11,11,12,11, 11,11,11,12,11,12,11,12,11,12,11,11,11,11,11,14,12,14,7,2,3,9,12,9,12,9,11,12,11,11, 15,11,11,8,8,9,11,11,8,9,12,9,8,8,8,12,8,15,15,15,4, }; GLubyte stb__arial_16_usascii_s[95]={ 125,125,109,111,54,1,14,105,1,43,95, 60,102,82,79,120,85,93,31,102,49,13,94,1,25,45,124,125,69,86,14, 40,27,19,10,34,117,108,99,1,83,125,103,73,65,54,44,82,31,54,11, 75,1,22,102,87,76,65,55,63,120,49,78,68,115,66,111,83,94,101,41, 66,113,121,22,22,40,1,110,92,32,47,118,75,68,58,43,23,51,73,35, 16,13,7,115, }; GLubyte stb__arial_16_usascii_t[95]={ 13,17,67,1,1,17,17,67,1,1,67, 67,67,14,14,1,17,43,55,17,55,30,1,55,17,17,55,29,67,67,67, 55,1,55,55,17,43,43,43,30,43,1,1,43,43,43,43,1,43,17,43, 17,43,30,30,30,30,30,30,1,17,1,67,14,72,55,17,55,17,55,30, 17,30,30,1,43,43,67,55,55,30,30,55,55,1,55,67,67,67,1,67, 1,1,1,67, }; GLubyte stb__arial_16_usascii_a[95]={ 64,64,81,127,127,204,153,44, 76,76,89,134,64,76,64,64,127,127,127,127,127,127,127,127, 127,127,64,64,134,134,134,127,233,153,153,165,165,153,140,178, 165,64,115,153,127,191,165,178,153,178,165,153,140,165,153,216, 153,153,140,64,64,64,108,127,76,127,127,115,127,127,64,127, 127,51,51,115,51,191,127,127,127,127,76,115,64,127,115,165, 115,115,115,77,60,77,134, }; GLbyte stb__arial_17_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,-1,1,0,1,1,1,0,1,1,0,1, 1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,1,0,0,0,-1,0,0,0,0,0,0,0,0,1,1, -1,1,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_17_usascii_y[95]={ 13,2,2,1,1,1,1,2,1,1,1,4,11,8, 11,1,2,2,2,2,2,2,2,2,2,2,5,5,3,5,3,1,1,2,2,1,2,2,2,1,2,2,2,2, 2,2,2,1,2,1,2,1,2,2,2,2,2,2,2,2,1,2,1,15,2,4,2,4,2,4,1,4,2,2, 2,2,2,4,4,4,4,4,4,4,2,5,5,5,5,5,5,1,1,1,6, }; GLubyte stb__arial_17_usascii_w[95]={ 0,2,5,9,8,13,10,3,5,5,6,9,2,5, 2,5,8,5,8,8,8,8,8,8,8,8,2,2,9,9,9,8,15,12,9,11,10,9,8,11,9,2,7,10, 7,11,9,12,9,12,10,10,9,9,11,15,11,11,9,3,5,4,7,10,4,8,8,8,8,8,5,8,7,2, 4,7,3,11,7,8,7,8,6,8,5,8,8,11,8,8,8,5,2,5,9, }; GLubyte stb__arial_17_usascii_h[95]={ 0,11,4,13,14,13,13,4,16,16,6,8,5,2, 2,13,12,11,11,12,11,12,12,11,12,12,8,11,9,5,9,12,16,11,11,13,11,11,11,13,11,11,12,11, 11,11,11,13,11,13,11,13,11,12,11,11,11,11,11,15,13,15,7,2,3,10,12,10,12,10,12,13,11,11, 15,11,11,9,9,10,13,13,9,10,12,9,8,8,8,12,8,16,16,16,3, }; GLubyte stb__arial_17_usascii_s[95]={ 127,71,121,80,58,90,1,11,1,22,114, 78,125,30,125,69,62,42,45,19,63,43,89,54,107,1,125,122,1,1,20, 28,28,32,22,21,11,1,113,33,99,124,75,78,70,58,89,67,32,45,13, 58,114,52,102,86,74,1,48,54,121,49,106,36,25,116,116,107,98,98,83, 12,72,125,44,24,109,30,49,89,113,104,42,80,37,11,97,66,57,10,88, 16,13,7,15, }; GLubyte stb__arial_17_usascii_t[95]={ 1,32,69,1,1,1,18,79,1,1,69, 69,54,79,60,18,32,45,57,32,57,32,18,57,18,32,45,45,69,79,69, 32,1,57,57,18,57,57,45,18,45,32,18,45,45,45,45,1,45,18,45, 18,32,32,32,32,32,45,45,1,1,1,69,79,79,57,18,57,18,57,18, 18,57,18,1,45,45,69,69,57,1,1,69,57,32,69,69,69,69,32,69, 1,1,1,79, }; GLubyte stb__arial_17_usascii_a[95]={ 68,68,86,135,135,216,162,46, 81,81,95,142,68,81,68,68,135,135,135,135,135,135,135,135, 135,135,68,68,142,142,142,135,247,162,162,176,176,162,149,189, 176,68,122,162,135,203,176,189,162,189,176,162,149,176,162,230, 162,162,149,68,68,68,114,135,81,135,135,122,135,135,68,135, 135,54,54,122,54,203,135,135,135,135,81,122,68,135,122,176, 122,122,122,81,63,81,142, }; GLbyte stb__arial_18_usascii_x[95]={ 0,1,0,0,0,0,0,0,0,0,0,0,1,0, 1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,-1,1,0,1,1,1,0,1,1,0,1, 1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,1,0,0,0,-1,0,0,1,0,0,0,0,0,1,1, -1,1,1,1,1,0,1,0,1,0,0,1,0,0,0,0,0,0,1,0,0, }; GLubyte stb__arial_18_usascii_y[95]={ 14,2,2,2,1,2,2,2,2,2,2,4,12,9, 12,2,2,2,2,2,2,2,2,2,2,2,5,5,4,5,4,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,16,2,5,2,5,2,5,2,5,2,2, 2,2,2,5,5,5,5,5,5,5,2,5,5,5,5,5,5,2,2,2,7, }; GLubyte stb__arial_18_usascii_w[95]={ 0,3,5,9,9,14,11,3,5,5,6,9,3,5, 3,5,9,6,9,9,9,9,9,9,9,9,3,3,9,9,9,9,16,12,9,11,10,9,9,12,10,3,7,10, 8,12,10,12,10,12,11,10,10,10,11,16,11,11,10,4,5,4,8,11,4,9,8,8,8,9,6,8,7,2, 4,7,2,12,7,9,8,8,5,8,5,7,8,12,8,8,8,6,2,5,9, }; GLubyte stb__arial_18_usascii_h[95]={ 0,12,5,13,15,13,13,5,16,16,6,9,5,2, 2,13,13,12,12,13,12,13,13,12,13,13,9,12,9,6,9,12,16,12,12,13,12,12,12,13,12,12,13,12, 12,12,12,13,12,13,12,13,12,13,12,12,12,12,12,16,13,16,7,2,3,10,13,10,13,10,12,13,12,12, 16,12,12,9,9,10,13,13,9,10,13,10,9,9,9,13,9,16,16,16,3, }; GLubyte stb__arial_18_usascii_s[95]={ 127,117,49,117,61,1,16,45,1,38,34, 116,41,86,82,50,99,121,76,118,96,10,28,43,33,56,1,106,5,24,66, 86,44,63,53,38,32,22,12,20,1,113,54,102,93,80,69,86,55,66,35, 88,21,43,1,110,98,86,75,33,62,23,15,70,55,118,1,10,109,29,68, 79,13,32,28,47,66,47,39,19,108,99,60,1,71,110,98,76,107,77,89, 16,13,7,60, }; GLubyte stb__arial_18_usascii_t[95]={ 1,46,83,1,1,18,18,83,1,1,83, 72,83,83,83,18,18,46,59,18,59,32,18,59,32,18,83,59,83,83,72, 59,1,59,59,18,59,59,59,32,59,46,32,46,46,46,46,1,46,18,46, 18,46,32,46,32,32,32,32,1,32,1,83,83,83,59,32,72,18,72,32, 18,46,46,1,46,46,72,72,72,1,1,72,72,1,59,72,72,72,1,72, 1,1,1,83, }; GLubyte stb__arial_18_usascii_a[95]={ 72,72,92,143,143,229,172,49, 86,86,100,151,72,86,72,72,143,143,143,143,143,143,143,143, 143,143,72,72,151,151,151,143,255,172,172,186,186,172,157,201, // 143,143,72,72,151,151,151,143,262,172,172,186,186,172,157,201, 186,72,129,172,143,215,186,201,172,201,186,172,157,186,172,243, 172,172,157,72,72,72,121,143,86,143,143,129,143,143,72,143, 143,57,57,129,57,215,143,143,143,143,86,129,72,143,129,186, 129,129,129,86,67,86,151, }; ///////////////////////////////////////////////////////////////// // GEOMETRY INITIALIZATION ///////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////// // INTIALIZATION OF THE TWO QUADS USED FOR DISPLAY: DRAWING AND COMPOSITION QUADS void pg_initGeometry_quads( void ) { ///////////////////////////////////////////////////////////////////// // QUAD FOR DRAWING AND COMPOSITION // point positions and texture coordinates quadDraw_points[1] = (float)windowHeight; quadDraw_points[3] = (float)singleWindowWidth; quadDraw_points[10] = (float)windowHeight; quadDraw_points[12] = (float)singleWindowWidth; quadDraw_points[13] = (float)windowHeight; quadDraw_points[15] = (float)singleWindowWidth; quadDraw_texCoords[1] = (float)windowHeight; quadDraw_texCoords[2] = (float)singleWindowWidth; quadDraw_texCoords[7] = (float)windowHeight; quadDraw_texCoords[8] = (float)singleWindowWidth; quadDraw_texCoords[9] = (float)windowHeight; quadDraw_texCoords[10] = (float)singleWindowWidth; // vertex buffer objects and vertex array unsigned int quadDraw_points_vbo = 0; glGenBuffers (1, &quadDraw_points_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadDraw_points_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * 3 * nbFaces * sizeof (float), quadDraw_points, GL_STATIC_DRAW); unsigned int quadDraw_texCoord_vbo = 0; glGenBuffers (1, &quadDraw_texCoord_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadDraw_texCoord_vbo); glBufferData (GL_ARRAY_BUFFER, 2 * 3 * nbFaces * sizeof (float), quadDraw_texCoords, GL_STATIC_DRAW); quadDraw_vao = 0; glGenVertexArrays (1, &quadDraw_vao); glBindVertexArray (quadDraw_vao); // vertex positions are location 0 glBindBuffer (GL_ARRAY_BUFFER, quadDraw_points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (0); // texture coordinates are location 1 glBindBuffer (GL_ARRAY_BUFFER, quadDraw_texCoord_vbo); glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (1); // don't forget this! printOglError( 22 ); ///////////////////////////////////////////////////////////////////// // QUAD FOR FINAL RENDERING (POSSIBLY DOUBLE) // point positions and texture coordinates quadFinal_points[1] = (float)windowHeight; quadFinal_points[3] = (float)doubleWindowWidth; quadFinal_points[10] = (float)windowHeight; quadFinal_points[12] = (float)doubleWindowWidth; quadFinal_points[13] = (float)windowHeight; quadFinal_points[15] = (float)doubleWindowWidth; quadFinal_texCoords[1] = (float)windowHeight; quadFinal_texCoords[2] = (float)doubleWindowWidth; quadFinal_texCoords[7] = (float)windowHeight; quadFinal_texCoords[8] = (float)doubleWindowWidth; quadFinal_texCoords[9] = (float)windowHeight; quadFinal_texCoords[10] = (float)doubleWindowWidth; // vertex buffer objects and vertex array unsigned int quadFinal_points_vbo = 0; glGenBuffers (1, &quadFinal_points_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadFinal_points_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * 3 * nbFaces * sizeof (float), quadFinal_points, GL_STATIC_DRAW); unsigned int quadFinal_texCoord_vbo = 0; glGenBuffers (1, &quadFinal_texCoord_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadFinal_texCoord_vbo); glBufferData (GL_ARRAY_BUFFER, 2 * 3 * nbFaces * sizeof (float), quadFinal_texCoords, GL_STATIC_DRAW); quadFinal_vao = 0; glGenVertexArrays (1, &quadFinal_vao); glBindVertexArray (quadFinal_vao); // vertex positions are location 0 glBindBuffer (GL_ARRAY_BUFFER, quadFinal_points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (0); // texture coordinates are location 1 glBindBuffer (GL_ARRAY_BUFFER, quadFinal_texCoord_vbo); glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (1); // don't forget this! printf("Geometry initialized %dx%d & %dx%d\n" , singleWindowWidth , windowHeight , doubleWindowWidth , windowHeight ); printOglError( 23 ); ///////////////////////////////////////////////////////////////////// // QUADS FOR SENSORS // point positions and texture coordinates quadSensor_points[0] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[1] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[3] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[4] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[6] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[7] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[9] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[10] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[12] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[13] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[15] = (float)PG_SENSOR_GEOMETRY_WIDTH; quadSensor_points[16] = (float)-PG_SENSOR_GEOMETRY_WIDTH; quadSensor_texCoords[1] = (float)PG_SENSOR_TEXTURE_WIDTH; quadSensor_texCoords[2] = (float)PG_SENSOR_TEXTURE_WIDTH; quadSensor_texCoords[7] = (float)PG_SENSOR_TEXTURE_WIDTH; quadSensor_texCoords[8] = (float)PG_SENSOR_TEXTURE_WIDTH; quadSensor_texCoords[9] = (float)PG_SENSOR_TEXTURE_WIDTH; quadSensor_texCoords[10] = (float)PG_SENSOR_TEXTURE_WIDTH; /////////////////////////////////////////////////////////////////////////////////////// // vertex buffer objects and vertex array /////////////////////////////////////////////////////////////////////////////////////// unsigned int quadSensor_points_vbo = 0; glGenBuffers (1, &quadSensor_points_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadSensor_points_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * 3 * nbFaces * sizeof (float), quadSensor_points, GL_STATIC_DRAW); unsigned int quadSensor_texCoord_vbo = 0; glGenBuffers (1, &quadSensor_texCoord_vbo); glBindBuffer (GL_ARRAY_BUFFER, quadSensor_texCoord_vbo); glBufferData (GL_ARRAY_BUFFER, 2 * 3 * nbFaces * sizeof (float), quadSensor_texCoords, GL_STATIC_DRAW); quadSensor_vao = 0; glGenVertexArrays (1, &quadSensor_vao); glBindVertexArray (quadSensor_vao); // vertex positions are location 0 glBindBuffer (GL_ARRAY_BUFFER, quadSensor_points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (0); // texture coordinates are location 1 glBindBuffer (GL_ARRAY_BUFFER, quadSensor_texCoord_vbo); glVertexAttribPointer (1, 2, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (1); // don't forget this! // printf("Sensor size %d\n" , PG_SENSOR_GEOMETRY_WIDTH ); printOglError( 23 ); /////////////////////////////////////////////////////////////////////////////////////// // sensor layouts /////////////////////////////////////////////////////////////////////////////////////// int indLayout; int indSens; // square grid indLayout = 0; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { int heightInt = indSens / 5 - 2; int widthInt = indSens % 5 - 2; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f + widthInt * 150.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f + heightInt * 150.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; } // circular grid indLayout = 1; // central sensor indSens = 0; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; for( indSens = 1 ; indSens < 9 ; indSens++ ) { float radius = windowHeight / 5.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f + radius * (float)cos( indSens * 2.0 * M_PI / 8.0f ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f + radius * (float)sin( indSens * 2.0 * M_PI / 8.0f ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; } for( indSens = 9 ; indSens < PG_NB_SENSORS ; indSens++ ) { float radius = windowHeight / 3.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f + radius * (float)cos( indSens * 2.0 * M_PI / 16.0f ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f + radius * (float)sin( indSens * 2.0 * M_PI / 16.0f ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; } // radial grid indLayout = 2; // central sensor indSens = 0; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; for( int indRay = 0 ; indRay < 6 ; indRay++ ) { float angle = indRay * 2.0f * (float)M_PI / 6.0f; for( indSens = 1 + indRay * 4 ; indSens < 1 + indRay * 4 + 4 ; indSens++ ) { float radius = ((indSens - 1) % 4 + 1) * windowHeight / 10.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f + radius * (float)cos( angle ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f + radius * (float)sin( angle ); sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; } } // conflated in the center // will be transformed into a random layout each time it is invoked indLayout = 3; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens ] = singleWindowWidth/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 1 ] = windowHeight/2.0f; sensorLayouts[ indLayout * 3 * PG_NB_SENSORS + 3 * indSens + 2 ] = 0.1f; } /////////////////////////////////////////////////////////////////////////////////////// // sensor activations /////////////////////////////////////////////////////////////////////////////////////// int indActivation; // central activation indActivation = 0; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = false; } sensorActivations[ indActivation * PG_NB_SENSORS + 12 ] = true; // corners activation indActivation = 1; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = false; } sensorActivations[ indActivation * PG_NB_SENSORS + 0 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 4 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 20 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 24 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 12 ] = true; // central square activation indActivation = 2; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = false; } sensorActivations[ indActivation * PG_NB_SENSORS + 6 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 7 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 8 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 11 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 12 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 13 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 16 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 17 ] = true; sensorActivations[ indActivation * PG_NB_SENSORS + 18 ] = true; // every second activation indActivation = 3; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { if( indSens % 2 == 0 ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = true; } else { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = false; } } // full activation indActivation = 4; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = true; } // central activation and activation of an additional sensor each 10 seconds indActivation = 5; for( indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { sensorActivations[ indActivation * PG_NB_SENSORS + indSens ] = false; } sensorActivations[ indActivation * PG_NB_SENSORS + 12 ] = true; /////////////////////////////////////////////////////////////////////////////////////// // sample setup /////////////////////////////////////////////////////////////////////////////////////// // sample choice sample_setUp_interpolation(); // float sample_choice[ PG_NB_SENSORS]; // // all possible sensor layouts // float sample_setUps[ PG_NB_MAX_SAMPLE_SETUPS][ PG_NB_SENSORS ] = // {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}, // {26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50}, // {51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75}}; } void sample_setUp_interpolation( void ) { float indSetUp = std::max( 0.0f , std::min( sample_setUp , (float)(PG_NB_MAX_SAMPLE_SETUPS - 1) ) ); float sample_setUp_integerPart = floor( indSetUp ); float sample_setUp_floatPart = indSetUp - sample_setUp_integerPart; int intIndSetup = (int)(sample_setUp_integerPart); // copies the setup that corresponds to the integer part for( int ind = 0 ; ind < PG_NB_SENSORS ; ind++ ) { sample_choice[ ind ] = sample_setUps[ intIndSetup ][ ind ]; } // for the decimal part, copies hybrid sensors of upper level with a ratio // proportional to the ratio between floor and current value if( sample_setUp_floatPart > 0.0f ) { int nbhybridSensors = (int)round( sample_setUp_floatPart * PG_NB_SENSORS ); // book keeping of hybridized sensors bool hybridized[PG_NB_SENSORS]; for( int ind = 0 ; ind < PG_NB_SENSORS ; ind++ ) { hybridized[ ind ] = false; } for( int indSensor = 0 ; indSensor < std::min( PG_NB_SENSORS , nbhybridSensors ) ; indSensor++ ) { int count = (int)round( ((float)rand()/(float)RAND_MAX) * PG_NB_SENSORS ); for( int ind = 0 ; ind < PG_NB_SENSORS ; ind++ ) { int translatedIndex = (count + PG_NB_SENSORS) % PG_NB_SENSORS; if( !hybridized[ translatedIndex ] ) { sample_choice[ translatedIndex ] = sample_setUps[ intIndSetup + 1 ][ translatedIndex ]; hybridized[ translatedIndex ] = true; } } } } std::string message = "/sample_setUp"; std::string format = ""; for( int indSens = 0 ; indSens < PG_NB_SENSORS - 1 ; indSens++ ) { format += "i "; } format += "i"; // sensor readback for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { std::string float_str = std::to_string((long long)sample_choice[indSens]); // float_str.resize(4); message += " " + float_str; } pg_send_message_udp( (char *)format.c_str() , (char *)message.c_str() , (char *)"udp_SC_send" ); // std::cout << "format: " << format << "\n"; // std::cout << "msg: " << message << "\n"; } ///////////////////////////////////////////////////////////////// // INTIALIZATION OF THE TACK LINES USED TO DISPLAY A TRACK AS A STRIP void pg_initGeometry_track_line( int indTrack , bool is_target ) { // source track if( !is_target && TrackStatus_source[ indTrack ].nbRecordedFrames > 0 ) { if( line_tracks_points[indTrack] ) { // memory release delete [] line_tracks_points[indTrack]; } line_tracks_points[indTrack] = new float[TrackStatus_source[ indTrack ].nbRecordedFrames * 3]; if(line_tracks_points[indTrack] == NULL) { strcpy( ErrorStr , "Track line point allocation error!" ); ReportError( ErrorStr ); throw 425; } // assigns the index to the coordinates to be able to recover the coordinates from the texture through the point index for(int indFrame = 0 ; indFrame < TrackStatus_source[ indTrack ].nbRecordedFrames ; indFrame++ ) { line_tracks_points[indTrack][ indFrame * 3 ] = (float)indFrame; } printOglError( 41 ); // vertex buffer objects unsigned int line_tracks_points_vbo = 0; glGenBuffers (1, &line_tracks_points_vbo); glBindBuffer (GL_ARRAY_BUFFER, line_tracks_points_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * TrackStatus_source[ indTrack ].nbRecordedFrames * sizeof (float), line_tracks_points[indTrack], GL_STATIC_DRAW); line_tracks_vao[indTrack] = 0; glGenVertexArrays (1, &(line_tracks_vao[indTrack])); glBindVertexArray (line_tracks_vao[indTrack]); // vertex positions are location 0 glBindBuffer (GL_ARRAY_BUFFER, line_tracks_points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (0); printf("Source track geometry initialized track %d: size %d\n" , indTrack , TrackStatus_source[ indTrack ].nbRecordedFrames ); printOglError( 42 ); } // target track if( is_target && TrackStatus_target[ indTrack ].nbRecordedFrames > 0 ) { if( line_tracks_target_points[indTrack] ) { // memory release delete [] line_tracks_target_points[indTrack]; } line_tracks_target_points[indTrack] = new float[TrackStatus_target[ indTrack ].nbRecordedFrames * 3]; if(line_tracks_target_points[indTrack] == NULL) { strcpy( ErrorStr , "Target track line point allocation error!" ); ReportError( ErrorStr ); throw 425; } // assigns the index to the coordinates to be able to recover the coordinates from the texture through the point index for(int indFrame = 0 ; indFrame < TrackStatus_target[ indTrack ].nbRecordedFrames ; indFrame++ ) { line_tracks_target_points[indTrack][ indFrame * 3 ] = (float)indFrame; } printOglError( 43 ); // vertex buffer objects unsigned int line_tracks_target_points_vbo = 0; glGenBuffers (1, &line_tracks_target_points_vbo); glBindBuffer (GL_ARRAY_BUFFER, line_tracks_target_points_vbo); glBufferData (GL_ARRAY_BUFFER, 3 * TrackStatus_target[ indTrack ].nbRecordedFrames * sizeof (float), line_tracks_target_points[indTrack], GL_STATIC_DRAW); line_tracks_target_vao[indTrack] = 0; glGenVertexArrays (1, &(line_tracks_target_vao[indTrack])); glBindVertexArray (line_tracks_target_vao[indTrack]); // vertex positions are location 0 glBindBuffer (GL_ARRAY_BUFFER, line_tracks_target_points_vbo); glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, (GLubyte*)NULL); glEnableVertexAttribArray (0); printf("Target track geometry initialized track %d: size %d\n" , indTrack , TrackStatus_target[ indTrack ].nbRecordedFrames ); printOglError( 44 ); } } ///////////////////////////////////////////////////////////////// // TEXTURE INITIALIZATION ///////////////////////////////////////////////////////////////// // general texture allocation void *pg_generateTexture( GLuint *textureID , pg_TextureFormat texture_format , int sizeX , int sizeY ) { glGenTextures( 1, textureID ); // rgb POT raw image allocation (without alpha channel) // printf( "Texture %dx%d nb_attachments %d\n" , // sizeX , sizeY , nb_attachments ); void *returnvalue = NULL; // Return from the function if no file name was passed in // Load the image and store the data if( texture_format == pg_byte_tex_format ) { GLubyte *ptr = new GLubyte[ sizeX * sizeY * 4 ]; // If we can't load the file, quit! if(ptr == NULL) { strcpy( ErrorStr , "Texture allocation error!" ); ReportError( ErrorStr ); throw 425; } int indTex = 0; for( int i = 0 ; i < sizeX * sizeY ; i++ ) { ptr[ indTex ] = 0; ptr[ indTex + 1 ] = 0; ptr[ indTex + 2 ] = 0; ptr[ indTex + 3 ] = 0; indTex += 4; } returnvalue = (void *)ptr; } else if( texture_format == pg_float_tex_format ) { float *ptr = new float[ sizeX * sizeY * 4 ]; // If we can't load the file, quit! if(ptr == NULL) { strcpy( ErrorStr , "Texture allocation error!" ); ReportError( ErrorStr ); throw 425; } int indTex = 0; for( int i = 0 ; i < sizeX * sizeY ; i++ ) { ptr[ indTex ] = 0.0f; ptr[ indTex + 1 ] = 0.0f; ptr[ indTex + 2 ] = 0.0f; ptr[ indTex + 3 ] = 0.0f; indTex += 4; } returnvalue = (void *)ptr; } return returnvalue; } ///////////////////////////////////////////// // texture loading bool pg_loadTexture3D( string filePrefixName , string fileSuffixName , int nbTextures , int bytesperpixel , bool invert , GLuint *textureID , GLint components, GLenum format , GLenum texturefilter , int width , int height , int depth ) { // data type is assumed to be GL_UNSIGNED_BYTE char filename[1024]; long size = width * height * bytesperpixel; GLubyte * bitmap = new unsigned char[size * nbTextures]; long ind = 0; glEnable(GL_TEXTURE_3D); glGenTextures( 1, textureID ); for( int indTex = 0 ; indTex < nbTextures ; indTex++ ) { sprintf( filename , "%s_%03d%s" , filePrefixName.c_str() , indTex + 1 , fileSuffixName.c_str() ); printf( "Loading %s\n" , filename ); // texture load through OpenCV #ifndef OPENCV_3 cv::Mat img = cv::imread( filename, CV_LOAD_IMAGE_UNCHANGED); // Read the file int colorTransform = (img.channels() == 4) ? CV_BGRA2RGBA : (img.channels() == 3) ? CV_BGR2RGB : CV_GRAY2RGB; // int glColorType = (img.channels() == 4) ? GL_RGBA : GL_RGB; cv::cvtColor(img, img, colorTransform); cv::Mat result; if( invert ) cv::flip(img, result , 0); // vertical flip else result = img; #else cv::Mat img = cv::imread( filename, cv::IMREAD_UNCHANGED ); // Read the file int colorTransform = (img.channels() == 4) ? cv::COLOR_BGRA2RGBA : (img.channels() == 3) ? cv::COLOR_BGR2RGB : cv::COLOR_GRAY2RGB; // int glColorType = (img.channels() == 4) ? GL_RGBA : GL_RGB; cv::cvtColor(img, img, colorTransform); cv::Mat result; if( invert ) cv::flip(img, result , 0); // vertical flip else result = img; #endif if(! result.data ) { // Check for invalid input sprintf( ErrorStr , "Could not open or find the image %s!" , filename ); ReportError( ErrorStr ); throw 425; return false; } if( result.cols != width || result.rows != height ) { // Check for invalid input sprintf( ErrorStr , "Unexpected image size %s %d/%d %d/%d!" , filename , result.cols , width , result.rows , height); ReportError( ErrorStr ); throw 425; return false; } GLubyte * ptr = result.data; for(long int i = 0; i < size ; i++) bitmap[ind++] = ptr[i]; } // printf("Final index %ld / %ld\n" , ind , size * nbTextures ); // glActiveTexture (GL_TEXTURE0 + index); glBindTexture(GL_TEXTURE_3D, *textureID ); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, (float)texturefilter); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, (float)texturefilter); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S , GL_REPEAT ); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT ); glTexImage3D(GL_TEXTURE_3D, // Type of texture 0, // Pyramid level (for mip-mapping) - 0 is the top level components, // Components: Internal colour format to convert to width, // Image width height, // Image heigh depth, // Image S 0, // Border width in pixels (can either be 1 or 0) format, // Format: Input image format (i.e. GL_RGB, GL_RGBA, GL_BGR etc.) GL_UNSIGNED_BYTE, // Image data type bitmap ); // The actual image data itself printOglError( 0 ); // memory release delete [] bitmap; // glGenerateMipmap(GL_TEXTURE_2D); return true; } bool pg_loadTexture( string fileName , cv::Mat *image , GLuint *textureID , bool is_rectangle , bool invert , GLint components , GLenum format , GLenum datatype , GLenum texturefilter, int width , int height ) { printf( "Loading %s\n" , fileName.c_str() ); glEnable(GL_TEXTURE_2D); glGenTextures( 1, textureID ); // texture load through OpenCV #ifndef OPENCV_3 cv::Mat img = cv::imread( fileName, CV_LOAD_IMAGE_UNCHANGED); // Read the file int colorTransform = (img.channels() == 4) ? CV_BGRA2RGBA : (img.channels() == 3) ? CV_BGR2RGB : CV_GRAY2RGB; // int glColorType = (img.channels() == 4) ? GL_RGBA : GL_RGB; if( img.channels() >= 3 ) { cv::cvtColor(img, img, colorTransform); } if( invert ) cv::flip(img, *image , 0); // vertical flip else *image = img; #else cv::Mat img = cv::imread( fileName, cv::IMREAD_UNCHANGED); // Read the file int colorTransform = (img.channels() == 4) ? cv::COLOR_BGRA2RGBA : (img.channels() == 3) ? cv::COLOR_BGR2RGB : cv::COLOR_GRAY2RGB; // int glColorType = (img.channels() == 4) ? GL_RGBA : GL_RGB; if( img.channels() >= 3 ) { cv::cvtColor(img, img, colorTransform); } if( invert ) cv::flip(img, *image , 0); // vertical flip else *image = img; #endif if(! image->data ) { // Check for invalid input sprintf( ErrorStr , "Could not open or find the image %s!" , fileName.c_str() ); ReportError( ErrorStr ); throw 425; return false; } if( image->cols != width || image->rows != height ) { // Check for invalid input sprintf( ErrorStr , "Unexpected image size %s %d/%d %d/%d!" , fileName.c_str() , image->cols , width , image->rows , height); ReportError( ErrorStr ); throw 425; return false; } // glActiveTexture (GL_TEXTURE0 + index); if( is_rectangle ) { glEnable(GL_TEXTURE_RECTANGLE); glBindTexture( GL_TEXTURE_RECTANGLE, *textureID ); glTexParameterf(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MIN_FILTER, (GLfloat)texturefilter); glTexParameterf(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MAG_FILTER, (GLfloat)texturefilter); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); glTexImage2D(GL_TEXTURE_RECTANGLE, // Type of texture 0, // Pyramid level (for mip-mapping) - 0 is the top level components, // Components: Internal colour format to convert to image->cols, // Image width image->rows, // Image heigh 0, // Border width in pixels (can either be 1 or 0) format, // Format: Input image format (i.e. GL_RGB, GL_RGBA, GL_BGR etc.) datatype, // Image data type image->ptr()); // The actual image data itself printOglError( 4 ); } else { glEnable(GL_TEXTURE_2D); glBindTexture( GL_TEXTURE_2D, *textureID ); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, (float)texturefilter); glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, (float)texturefilter); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S , GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); glTexImage2D(GL_TEXTURE_2D, // Type of texture 0, // Pyramid level (for mip-mapping) - 0 is the top level components, // Components: Internal colour format to convert to image->cols, // Image width image->rows, // Image height 0, // Border width in pixels (can either be 1 or 0) format, // Format: Input image format (i.e. GL_RGB, GL_RGBA, GL_BGR etc.) datatype, // Image data type image->ptr()); // The actual image data itself printOglError( 5 ); } // glGenerateMipmap(GL_TEXTURE_2D); return true; } void pg_CA_data_table_values( GLuint textureID , GLubyte * data_table , int width , int height ) { GLubyte *ptr = data_table; //vec4 GOL_params[9] //=vec4[9](vec4(0,0,0,0),vec4(3,3,2,3), // vec4(3,6,2,3),vec4(1,1,1,2), // vec4(1,2,3,4),vec4(1,2,4,6), // vec4(2,10,4,6),vec4(2,6,5,6), // vec4(2,7,5,7)); //////////////////////////////////////////// // GAME OF LIFE FAMILY: 1 neutral + 8 variants GLubyte transition_tableGOL[9*2*10] = { 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,0,0,0,0,0, 0,0,1,1,0,0,0,0,0,0, 0,0,0,1,1,1,1,0,0,0, 0,0,1,1,0,0,0,0,0,0, 0,1,0,0,0,0,0,0,0,0, 0,1,1,0,0,0,0,0,0,0, 0,1,1,0,0,0,0,0,0,0, 0,0,0,1,1,0,0,0,0,0, 0,1,1,0,0,0,0,0,0,0, 0,0,0,0,1,1,1,0,0,0, 0,0,1,1,1,1,1,1,1,1, 0,0,0,0,1,1,1,0,0,0, 0,0,1,1,1,1,1,0,0,0, 0,0,0,0,0,1,1,0,0,0, 0,0,1,1,1,1,1,1,0,0, 0,0,0,0,0,1,1,1,0,0, }; for( int indGOL = 0 ; indGOL < 9 ; indGOL++ ) { ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 2*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableGOL[indGOL * 2*10 + ind - 1]; } ptr += 4 * width; } //////////////////////////////////////////// // TOTALISTIC FAMILY: 1 neutral + 8 variants // SubType 0: neutral ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = 0; } ptr += 4 * width; // SubType 1: CARS GLubyte transition_tableCARS[16*10] = { 0,2,15,6,8,2,4,6,8,0, 0,0,0,0,0,0,0,0,0,0, 4,4,4,4,4,4,4,4,4,0, 0,0,0,0,0,0,0,0,0,0, 0,6,6,6,6,6,6,6,6,0, 0,0,0,0,0,0,0,0,0,0, 8,8,8,8,8,8,8,8,8,0, 0,0,0,0,0,0,0,0,0,0, 10,10,10,10,10,10,10,10,10,0, 0,0,0,0,0,0,0,0,0,0, 12,12,12,12,12,12,12,12,12,0, 0,0,0,0,0,0,0,0,0,0, 14,14,14,14,14,14,14,14,14,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableCARS[ind-1]; } ptr += 4 * width; // SubType 2: EcoLiBra GLubyte transition_tableEcoLiBra[16*10] = { 0,0,7,0,0,0,15,15,0,0, 0,0,0,0,0,0,0,0,0,0, 15,15,15,15,15,2,2,15,15,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 12,12,12,12,12,12,12,12,12,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 15,0,15,15,15,2,15,15,15,0 }; ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableEcoLiBra[ind-1]; } ptr += 4 * width; // SubType 3: Ladders GLubyte transition_tableLadders[16*10] = { 0,6,5,0,0,2,15,5,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,8,7,15,0,15,0,0, 0,0,6,0,0,0,0,0,3,0, 0,0,0,0,0,0,0,0,0,0, 8,0,0,0,0,0,0,0,0,0, 8,4,2,5,6,0,0,0,0,0, 4,0,11,0,0,0,0,0,0,0, 0,0,0,0,0,0,15,4,0,0, 0,8,0,15,5,0,0,0,0,0, 4,10,0,0,4,5,0,0,4,0, 0,8,8,0,0,12,4,6,0,0, 0,0,0,10,2,10,6,6,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,9,0,11,3,0,0, 9,0,0,0,14,0,0,6 }; ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableLadders[ind-1]; } ptr += 4 * width; // SubType 4: Wire World GLubyte transition_tableWire[4*10] = { 0,0,0,0,0,0,0,0,0,0, 2,2,2,2,2,2,2,2,2,0, 3,3,3,3,3,3,3,3,3,0, 3,1,1,3,3,3,3,3,3,3, }; ptr[ 0 ] = 4; for( int ind = 1 ; ind < std::min( width , 4*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableWire[ind-1]; } ptr += 4 * width; // SubType 5: Busy Brain GLubyte transition_tableBusyBrain[3*10] = { 0,0,1,2,0,2,2,2,2,0, 2,2,2,1,0,2,2,2,2, 0,0,0,0,0,1,2,2,1,2, }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 3*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableBusyBrain[ind-1]; } ptr += 4 * width; // SubType 6: Balloons GLubyte transition_tableBalloons[16*10] = { 0,0,15,0,0,0,5,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 4,4,8,4,4,4,4,4,4,0, 5,5,5,5,5,7,7,9,11, 0,2,2,2,2,2,2,2,2,2, 0,5,5,5,5,5,13,13,9,11, 0,8,8,10,8,8,8,8,8,8,0, 2,2,2,2,2,9,13,9,11,0, 10,10,0,10,10,10,10,10,10,0, 4,14,14,14,14,14,14,14,11,0, 2,12,4,12,12,12,12,12,12,0, 6,6,6,6,13,13,13,9,11,0, 14,14,14,12,14,14,14,14,14,0, 2,2,2,2,2,2,2,2,2 }; ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableBalloons[ind-1]; } ptr += 4 * width; // SubType 7: Ran Brain GLubyte transition_tableRanBrain[16*10] = { 0,0,5,10,0,0,5,10,0,0, 0,0,5,10,0,0,0,0,15,0, 0,0,0,0,0,15,15,0,0,0, 0,0,14,0,0,0,0,0,0,0, 0,0,4,0,0,0,0,0,0,0, 2,6,2,6,2,6,2,6,2,0, 2,6,2,6,2,6,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,12,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,12,0,0, 0,2,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, 0,0,14,7 }; ptr[ 0 ] = 16; for( int ind = 1 ; ind < std::min( width , 16*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableRanBrain[ind-1]; } ptr += 4 * width; // SubType 8: Brian's Brain GLubyte transition_tableBriansBrain[3*10] = { 0,0,1,0,0,0,0,0,0,0, 2,2,2,2,2,2,2,2,2,2, 0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 3*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableBriansBrain[ind-1]; } ptr += 4 * width; //////////////////////////////////////////// // GENERATION FAMILY: 1 neutral + 19 variants // SubType 0: neutral #define nbStatesNeutral 8 ptr[ 0 ] = nbStatesNeutral; for( int ind = 1 ; ind < std::min( width , nbStatesNeutral*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = 0; } ptr += 4 * width; // SubType 1: TwoStates #define nbStatesTwoStates 2 GLubyte TwoStates[nbStatesTwoStates*10] = { 0,0,1,0,1,0,0,1,1,0, // TwoStates 0,0,0,0,0,0,0,0,0,0, // TwoStates }; // TwoStates ptr[ 0 ] = nbStatesTwoStates; for( int ind = 1 ; ind < std::min( width , nbStatesTwoStates*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = TwoStates[ind-1]; } ptr += 4 * width; // SubType 2: Caterpillars #define nbStatesCaterpillars 4 GLubyte Caterpillars[nbStatesCaterpillars*10] = { 0,0,0,1,0,0,0,1,1,0, // Caterpillars 2,1,1,2,1,1,1,1,2,2, // Caterpillars 3,1,1,3,1,1,1,1,3,3, // Caterpillars 0,1,1,0,1,1,1,1,0,0, }; // Caterpillars ptr[ 0 ] = nbStatesCaterpillars; for( int ind = 1 ; ind < std::min( width , nbStatesCaterpillars*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Caterpillars[ind-1]; } ptr += 4 * width; // SubType 3: SoftFreeze #define nbStatesSoftFreeze 6 GLubyte SoftFreeze[nbStatesSoftFreeze*10] = { 0,0,0,1,0,0,0,0,1,0, // SoftFreeze 2,1,2,1,1,1,2,2,1,2, // SoftFreeze 3,1,3,1,1,1,3,3,1,3, // SoftFreeze 4,1,4,1,1,1,4,4,1,4, // SoftFreeze 5,1,5,1,1,1,5,5,1,5, // SoftFreeze 0,1,0,1,1,1,0,0,1,0, }; // SoftFreeze ptr[ 0 ] = nbStatesSoftFreeze; for( int ind = 1 ; ind < std::min( width , nbStatesSoftFreeze*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = SoftFreeze[ind-1]; } ptr += 4 * width; // SubType 4: LOTE #define nbStatesLOTE 6 GLubyte LOTE[nbStatesLOTE*10] = { 0,0,0,1,0,0,0,0,0,0, // LOTE 2,2,2,1,1,1,2,2,2,2, // LOTE 3,3,3,1,1,1,3,3,3,3, // LOTE 4,4,4,1,1,1,4,4,4,4, // LOTE 5,5,5,1,1,1,5,5,5,5, // LOTE 0,0,0,1,1,1,0,0,0,0, }; // LOTE ptr[ 0 ] = nbStatesLOTE; for( int ind = 1 ; ind < std::min( width , nbStatesLOTE*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = LOTE[ind-1]; } ptr += 4 * width; // SubType 5: MeterGuns #define nbStatesMeterGuns 8 GLubyte MeterGuns[nbStatesMeterGuns*10] = { 0,0,0,1,0,0,0,0,0,0, // MeterGuns 1,1,1,2,1,1,1,1,1,2, // MeterGuns 1,1,1,3,1,1,1,1,1,3, // MeterGuns 1,1,1,4,1,1,1,1,1,4, // MeterGuns 1,1,1,5,1,1,1,1,1,5, // MeterGuns 1,1,1,6,1,1,1,1,1,6, // MeterGuns 1,1,1,7,1,1,1,1,1,7, // MeterGuns 1,1,1,0,1,1,1,1,1,0, }; // MeterGuns ptr[ 0 ] = nbStatesMeterGuns; for( int ind = 1 ; ind < std::min( width , nbStatesMeterGuns*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = MeterGuns[ind-1]; } ptr += 4 * width; // SubType 6: EbbFlow #define nbStatesEbbFlow 18 GLubyte EbbFlow[nbStatesEbbFlow*10] = { 0,0,0,1,0,0,1,0,0,0, // EbbFlow 1,1,1,2,1,2,2,1,1,2, // EbbFlow 1,1,1,3,1,3,3,1,1,3, // EbbFlow 1,1,1,4,1,4,4,1,1,4, // EbbFlow 1,1,1,5,1,5,5,1,1,5, // EbbFlow 1,1,1,6,1,6,6,1,1,6, // EbbFlow 1,1,1,7,1,7,7,1,1,7, // EbbFlow 1,1,1,8,1,8,8,1,1,8, // EbbFlow 1,1,1,9,1,9,9,1,1,9, // EbbFlow 1,1,1,10,1,10,10,1,1,10, // EbbFlow 1,1,1,11,1,11,11,1,1,11, // EbbFlow 1,1,1,12,1,12,12,1,1,12, // EbbFlow 1,1,1,13,1,13,13,1,1,13, // EbbFlow 1,1,1,14,1,14,14,1,1,14, // EbbFlow 1,1,1,15,1,15,15,1,1,15, // EbbFlow 1,1,1,16,1,16,16,1,1,16, // EbbFlow 1,1,1,17,1,17,17,1,1,17, // EbbFlow 1,1,1,0,1,0,0,1,1,0, }; // EbbFlow ptr[ 0 ] = nbStatesEbbFlow; for( int ind = 1 ; ind < std::min( width , nbStatesEbbFlow*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = EbbFlow[ind-1]; } ptr += 4 * width; // SubType 7: EbbFlow2 #define nbStatesEbbFlow2 18 GLubyte EbbFlow2[nbStatesEbbFlow2*10] = { 0,0,0,1,0,0,0,1,0,0, // EbbFlow2 1,1,1,2,1,2,1,2,1,2, // EbbFlow2 1,1,1,3,1,3,1,3,1,3, // EbbFlow2 1,1,1,4,1,4,1,4,1,4, // EbbFlow2 1,1,1,5,1,5,1,5,1,5, // EbbFlow2 1,1,1,6,1,6,1,6,1,6, // EbbFlow2 1,1,1,7,1,7,1,7,1,7, // EbbFlow2 1,1,1,8,1,8,1,8,1,8, // EbbFlow2 1,1,1,9,1,9,1,9,1,9, // EbbFlow2 1,1,1,10,1,10,1,10,1,10, // EbbFlow2 1,1,1,11,1,11,1,11,1,11, // EbbFlow2 1,1,1,12,1,12,1,12,1,12, // EbbFlow2 1,1,1,13,1,13,1,13,1,13, // EbbFlow2 1,1,1,14,1,14,1,14,1,14, // EbbFlow2 1,1,1,15,1,15,1,15,1,15, // EbbFlow2 1,1,1,16,1,16,1,16,1,16, // EbbFlow2 1,1,1,17,1,17,1,17,1,17, // EbbFlow2 1,1,1,0,1,0,1,0,1,0, // EbbFlow2 }; // EbbFlow2 ptr[ 0 ] = nbStatesEbbFlow2; for( int ind = 1 ; ind < std::min( width , nbStatesEbbFlow2*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = EbbFlow2[ind-1]; } ptr += 4 * width; // SubType 8: SediMental #define nbStatesSediMental 4 GLubyte SediMental[nbStatesSediMental*10] = { 0,0,1,0,0,1,1,1,1,0, // SediMental 2,2,2,2,1,1,1,1,1,2, // SediMental 3,3,3,3,1,1,1,1,1,3, // SediMental 0,0,0,0,1,1,1,1,1,0, }; // SediMental ptr[ 0 ] = nbStatesSediMental; for( int ind = 1 ; ind < std::min( width , nbStatesSediMental*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = SediMental[ind-1]; } ptr += 4 * width; // SubType 9: Brain6 #define nbStatesBrain6 3 GLubyte Brain6[nbStatesBrain6*10] = { 0,0,1,0,1,0,1,0,0,0, // Brain6 2,2,2,2,2,2,1,2,2,2, // Brain6 0,0,0,0,0,0,1,0,0,0, // Brain6 }; // Brain64 ptr[ 0 ] = nbStatesBrain6; for( int ind = 1 ; ind < std::min( width , nbStatesBrain6*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Brain6[ind-1]; } ptr += 4 * width; // SubType 10: OrthoGo #define nbStatesOrthoGo 4 GLubyte OrthoGo[nbStatesOrthoGo*10] = { 0,0,1,0,0,0,0,0,0,0, // OrthoGo 2,2,2,1,2,2,2,2,2,2, // OrthoGo 3,3,3,1,3,3,3,3,3,3, // OrthoGo }; // OrthoGo ptr[ 0 ] = nbStatesOrthoGo; for( int ind = 1 ; ind < std::min( width , nbStatesOrthoGo*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = OrthoGo[ind-1]; } ptr += 4 * width; // SubType 11: StarWars #define nbStatesStarWars 4 GLubyte StarWars[nbStatesStarWars*10] = { 0,0,1,0,0,0,0,0,0,0, // StarWars 2,2,2,1,1,1,2,2,2,2, // StarWars 3,3,3,1,1,1,3,3,3,3, // StarWars 0,0,0,1,1,1,0,0,0,0, }; // StarWars ptr[ 0 ] = nbStatesStarWars; for( int ind = 1 ; ind < std::min( width , nbStatesStarWars*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = StarWars[ind-1]; } ptr += 4 * width; // SubType 12: Transers #define nbStatesTransers 5 GLubyte Transers[nbStatesTransers*10] = { 0,0,1,0,0,0,1,0,0,0, // Transers 2,2,2,1,1,1,2,2,2,2, // Transers 3,3,3,1,1,1,3,3,3,3, // Transers 4,4,4,1,1,1,4,4,4,4, // Transers 0,0,0,1,1,1,0,0,0,0, }; // Transers ptr[ 0 ] = nbStatesTransers; for( int ind = 1 ; ind < std::min( width , nbStatesTransers*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Transers[ind-1]; } ptr += 4 * width; // SubType 13: Snake #define nbStatesSnake 6 GLubyte Snake[nbStatesSnake*10] = { 0,0,1,0,0,1,0,0,0,0, // Snake 1,2,2,1,1,2,1,1,2,2, // Snake 1,3,3,1,1,3,1,1,3,3, // Snake 1,4,4,1,1,4,1,1,4,4, // Snake 1,5,5,1,1,5,1,1,5,5, // Snake 1,0,0,1,1,0,1,1,0,0, }; // Snake ptr[ 0 ] = nbStatesSnake; for( int ind = 1 ; ind < std::min( width , nbStatesSnake*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Snake[ind-1]; } ptr += 4 * width; // SubType 14: Sticks #define nbStatesSticks 6 GLubyte Sticks[nbStatesSticks*10] = { 0,0,1,0,0,0,0,0,0,0, // Sticks 2,2,2,1,1,1,1,2,2,2, // Sticks 3,3,3,1,1,1,1,3,3,3, // Sticks 4,4,4,1,1,1,1,4,4,4, // Sticks 5,5,5,1,1,1,1,5,5,5, // Sticks 0,0,0,1,1,1,1,0,0,0, }; // Sticks ptr[ 0 ] = nbStatesSticks; for( int ind = 1 ; ind < std::min( width , nbStatesSticks*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Sticks[ind-1]; } ptr += 4 * width; // SubType 15: Transers2 #define nbStatesTransers2 6 GLubyte Transers2[nbStatesTransers2*10] = { 0,0,1,0,0,0,1,0,0,0, // Transers2 1,2,2,1,1,1,2,2,2,2, // Transers2 1,3,3,1,1,1,3,3,3,3, // Transers2 1,4,4,1,1,1,4,4,4,4, // Transers2 1,5,5,1,1,1,5,5,5,5, // Transers2 1,0,0,1,1,1,0,0,0,0, // Transers2 }; // Transers2 ptr[ 0 ] = nbStatesTransers2; for( int ind = 1 ; ind < std::min( width , nbStatesTransers2*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Transers2[ind-1]; } ptr += 4 * width; // SubType 16: Worms #define nbStatesWorms 6 GLubyte Worms[nbStatesWorms*10] = { 0,0,1,0,0,1,0,0,0,0, // Worms 2,2,2,1,1,2,1,1,2,2, // Worms 3,3,3,1,1,3,1,1,3,3, // Worms 4,4,4,1,1,4,1,1,4,4, // Worms 5,5,5,1,1,5,1,1,5,5, // Worms 0,0,0,1,1,0,1,1,0,0, }; // Worms ptr[ 0 ] = nbStatesWorms; for( int ind = 1 ; ind < std::min( width , nbStatesWorms*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Worms[ind-1]; } ptr += 4 * width; // SubType 17: Cooties #define nbStatesCooties 9 GLubyte Cooties[nbStatesCooties*10] = { 0,0,1,0,0,0,0,0,0,0, // Cooties 2,2,1,1,2,2,2,2,2,2, // Cooties 3,3,1,1,3,3,3,3,3,3, // Cooties 4,4,1,1,4,4,4,4,4,4, // Cooties 5,5,1,1,5,5,5,5,5,5, // Cooties 6,6,1,1,6,6,6,6,6,6, // Cooties 7,7,1,1,7,7,7,7,7,7, // Cooties 8,8,1,1,8,8,8,8,8,8, // Cooties 0,0,1,1,0,0,0,0,0,0, }; // Cooties ptr[ 0 ] = nbStatesCooties; for( int ind = 1 ; ind < std::min( width , nbStatesCooties*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Cooties[ind-1]; } ptr += 4 * width; // SubType 18: Faders #define nbStatesFaders 25 GLubyte Faders[nbStatesFaders*10] = { 0,0,1,0,0,0,0,0,0,0, // Faders 2,2,1,2,2,2,2,2,2,2, // Faders 3,3,1,3,3,3,3,3,3,3, // Faders 4,4,1,4,4,4,4,4,4,4, // Faders 5,5,1,5,5,5,5,5,5,5, // Faders 6,6,1,6,6,6,6,6,6,6, // Faders 7,7,1,7,7,7,7,7,7,7, // Faders 8,8,1,8,8,8,8,8,8,8, // Faders 9,9,1,9,9,9,9,9,9,9, // Faders 10,10,1,10,10,10,10,10,10,10, // Faders 11,11,1,11,11,11,11,11,11,11, // Faders 12,12,1,12,12,12,12,12,12,12, // Faders 13,13,1,13,13,13,13,13,13,13, // Faders 14,14,1,14,14,14,14,14,14,14, // Faders 15,15,1,15,15,15,15,15,15,15, // Faders 16,16,1,16,16,16,16,16,16,16, // Faders 17,17,1,17,17,17,17,17,17,17, // Faders 18,18,1,18,18,18,18,18,18,18, // Faders 19,19,1,19,19,19,19,19,19,19, // Faders 20,20,1,20,20,20,20,20,20,20, // Faders 21,21,1,21,21,21,21,21,21,21, // Faders 22,22,1,22,22,22,22,22,22,22, // Faders 23,23,1,23,23,23,23,23,23,23, // Faders 24,24,1,24,24,24,24,24,24,24, // Faders 0,0,1,0,0,0,0,0,0,0, }; // Faders ptr[ 0 ] = nbStatesFaders; for( int ind = 1 ; ind < std::min( width , nbStatesFaders*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Faders[ind-1]; } ptr += 4 * width; // SubType 19: Fireworks #define nbStatesFireworks 21 GLubyte Fireworks[nbStatesFireworks*10] = { 0,1,0,1,0,0,0,0,0,0, // Fireworks 2,2,1,2,2,2,2,2,2,2, // Fireworks 3,3,1,3,3,3,3,3,3,3, // Fireworks 4,4,1,4,4,4,4,4,4,4, // Fireworks 5,5,1,5,5,5,5,5,5,5, // Fireworks 6,6,1,6,6,6,6,6,6,6, // Fireworks 7,7,1,7,7,7,7,7,7,7, // Fireworks 8,8,1,8,8,8,8,8,8,8, // Fireworks 9,9,1,9,9,9,9,9,9,9, // Fireworks 10,10,1,10,10,10,10,10,10,10, // Fireworks 11,11,1,11,11,11,11,11,11,11, // Fireworks 12,12,1,12,12,12,12,12,12,12, // Fireworks 13,13,1,13,13,13,13,13,13,13, // Fireworks 14,14,1,14,14,14,14,14,14,14, // Fireworks 15,15,1,15,15,15,15,15,15,15, // Fireworks 16,16,1,16,16,16,16,16,16,16, // Fireworks 17,17,1,17,17,17,17,17,17,17, // Fireworks 18,18,1,18,18,18,18,18,18,18, // Fireworks 19,19,1,19,19,19,19,19,19,19, // Fireworks 20,20,1,20,20,20,20,20,20,20, // Fireworks 0,0,1,0,0,0,0,0,0,0, }; // Fireworks ptr[ 0 ] = nbStatesFireworks; for( int ind = 1 ; ind < std::min( width , nbStatesFireworks*10+1 ) ; ind++ ) { ptr[ ind * 4 ] = Fireworks[ind-1]; } ptr += 4 * width; //////////////////////////////////////////// // GENERAL BINARY FAMILY Moore Neighborhood: 1 neutral + 7 variants // Example: Fallski // C48,NM,Sb255a,Babb189ab63a // 48 states 0-47 // Moore neihborhood Order N,NE,E,SE,S,SW,W,NW // states are encoded: S_N + 2 * S_NE + 4 * S_E + 8 * S_SE ... + 128 * S_NW // 00000000 0 neighbor // 10000000 N neighbor // 01000000 NE neighbor // 192 = 00000011 W and NW neighbors // Survive b255a survival on no alive neighbors: // 1 x one 255 x zeros // Birth abb189ab63a birth on a single N or NE neighbor, or on W and NW neighbors: // 0 1 1 189 x zeros 1 63 x zeros // Encoding of Survival and Birth // 256 0/1 digits encode // SubType 0: neutral ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = 0; } ptr += 4 * width; // Subtype 1: Fallski GLubyte transition_tableFallski[256*2] = { 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 48; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableFallski[ind-1]; } ptr += 4 * width; // Subtype 2: JustFriends GLubyte transition_tableJustFriends[256*2] = { 0,1,1,1,1,1,1,0,1,1,1,0,1,0,0,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableJustFriends[ind-1]; } ptr += 4 * width; // Subtype 3: LogicRule GLubyte transition_tableLogicRule[256*2] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,1,0,1,1,0,0,0,0,0,1,0,0,1,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableLogicRule[ind-1]; } ptr += 4 * width; // Subtype 4: Meteorama GLubyte transition_tableMeteorama[256*2] = { 0,0,0,1,0,0,1,0,0,0,1,1,1,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,1,1,0,0,1,0,0,0,1,1,0,1,1,0,1,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,0,1,1,1,1,0,0,1,0,0,0,0,0,1,1,1,0,0,0,1,1,0,0,0,0,0,1,1,0,1,0,1,0,1,1,0,0,0,1,0,1,0,0,1,1,0,0,0,1,1,0,1,0,1,0,0,1,0,0,0,1,1,1,1,1,1,0,1,0,0,0,1,0,1,0,0,0,0,1,1,0,1,1,1,1,1,0,0,1,0,0,0,1,0,1,1,1,0,0,0,0,0,0,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,1,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,1,1,1,1,0,0,0,1,1,0,1,1,1,0,0,0,1,0,0,0,0,1,0,0,1,0,0,1,1,0,1,0,1,0,1,0,1,0,0,1,0,0,0,0,1,0,0,0, 0,0,0,0,0,1,0,1,1,1,1,1,0,0,0,1,0,1,0,1,0,1,0,0,0,0,0,0,1,1,1,0,0,1,0,0,0,1,0,1,0,1,1,1,0,0,0,1,1,0,0,0,0,1,1,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,1,1,0,0,1,1,1,1,1,0,1,1,1,0,1,0,1,0,1,0,0,0,0,0,0,1,0,0,1,0,1,1,0,1,0,0,0,0,0,0,1,0,1,0,0,1,0,0,1,1,1,1,1,0,0,1,0,0,1,1,0,0,1,0,0,0,0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1,0,1,0,0,0,0,1,0,1,0,1,1,0,0,1,1,1,1,0,0,1,0,0,0,1,1,1,0,0,1,1,0,1,0,0,0,0,0,0,0,1,0,0,1,0,0,1,0,0,0,1,1,1,0,1,1,1,0,1,1,0,1,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,1,1,0,1,1, }; ptr[ 0 ] = 24; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableMeteorama[ind-1]; } ptr += 4 * width; // Subtype 5: Slugfest GLubyte transition_tableSlugfest[256*2] = { 1,1,1,1,0,0,0,1,0,0,1,1,0,0,1,1,1,1,0,1,0,1,1,0,1,0,0,0,0,0,0,1,1,0,0,1,0,0,0,1,0,1,0,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,1,0,0,1,1,1,0,0,1,0,1,1,0,1,0,1,1,0,0,0,0,0,0,1,0,0,1,0,0,1,1,0,1,1,0,1,0,1,1,1,0,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0,1,0,0,1,1,0,1,1,0,0,1,1,0,0,0,1,1,0,0,0,1,0,1,1,1,0,0,0,1,0,1,0,0,0,1,1,0,1,1,1,0,0,0,1,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,1,0,1,1,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,1,0,0,0,0,1,1,0,1,0,1,1,0,1,1,1,0,0,0,1,1,0,0,1,1,0,0,1,1,1,0,1,0, 0,0,0,0,0,0,1,1,0,0,0,0,0,0,1,0,0,1,1,1,0,1,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0,1,1,1,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,1,1,0,0,1,0,1,0,0,0,0,0,0,1,1,1,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,1,0,1,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,0,0,0,0,1,1,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,1,1,1,1,0,0,1,0,0,1,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,1,1,1,1,0,0,1,0,1,1,1,0,1,0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,0,1,1,0,1,1,1,1,0,1,0,1,1,0,0,0,1,0,0,0,0,0,1,1,0,0,0,1,0,0,1,0,0,0,1,1,1,1,0,1,0,1,1,1,1,0,0,0,0,0,0,0,1,1,0,0,1,1,0, }; ptr[ 0 ] = 20; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableSlugfest[ind-1]; } ptr += 4 * width; // Subtype 6: Snowflakes GLubyte transition_tableSnowflakes[256*2] = { 0,1,1,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,1,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,1,0,0,0,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,1,1,0,0,0,0,0,0,0,0,1,0,0,1,0,1,1,0,0,0,0,1,0,0,1,0,0,1,1,0,0,0,1,1,0,0,0,1,0,1,1,1,0,1,1,0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,0,1,0,0,0,0,1,1,1,0,0,1,0,1,0,0,1,0,1,0,0,0,0,1,1,0,1,0,0,1,1,0,0,0,0,1,0,1,0,0,1,0,1,0,0,1,1,1,0,0,0,0,1,0,0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,1,1,0,1,1,1,0,1,0,0,0,1,0,0,0,0,1,1,0,0,1,1,0,1,0,0,0,0,1,1,0,1,0,0,1,0,0,0,0,0,0,0,0,1,1,1,1,0,1,0,0,1,0,1,1,0,0,1,1,0,0,0,0,0,1,1,0,0,1,1,0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,1, }; ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableSnowflakes[ind-1]; } ptr += 4 * width; // Subtype 7: Springski GLubyte transition_tableSpringski[256*2] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 78; for( int ind = 1 ; ind < std::min( width , 256*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableSpringski[ind-1]; } ptr += 4 * width; //////////////////////////////////////////// // GENERAL BINARY FAMILY von Neumann Neighborhood: 1 neutral + 3 variants // SubType 0: neutral ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 16*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = 0; } ptr += 4 * width; // Subtype 1: Banks GLubyte transition_tableBanks[16*2] = { 1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1, 0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,1, }; ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 16*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableBanks[ind-1]; } ptr += 4 * width; // Subtype 2: FractalBeads GLubyte transition_tableFractalBeads[16*2] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0, }; ptr[ 0 ] = 4; for( int ind = 1 ; ind < std::min( width , 16*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableFractalBeads[ind-1]; } ptr += 4 * width; // Subtype 3: Sierpinski GLubyte transition_tableSierpinski[16*2] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0, }; ptr[ 0 ] = 2; for( int ind = 1 ; ind < std::min( width , 16*2+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableSierpinski[ind-1]; } ptr += 4 * width; //////////////////////////////////////////// // NEUMANNN BINARY FAMILY : 1 neutral + 18 variants // Fredkin2 rule has the following definition: 2,01101001100101101001011001101001 // The first digit, '2', tells the rule has 2 states (it's a 1 bit rule). // The second digit, '0', tells a cell in a configuration ME=0,N=0,E=0,S=0,W=0 will get the state 0. // The third digit, '1', tells a cell in a configuration ME=0,N=0,E=0,S=0,W=1 will get the state 1. // The fourth digit, '1', tells a cell in a configuration ME=0,N=0,E=0,S=1,W=0 will get the state 1. // The fifth digit, '0', tells a cell in a configuration ME=0,N=0,E=0,S=1,W=1 will get the state 0. // . . . // binary rules are extended to ternary for a uniform rule system // SubType 0: neutral ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = 0; } ptr += 4 * width; // Subtype 1: Crystal2 GLubyte transition_tableCrystal2[243] = { 0,1,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableCrystal2[ind-1]; } ptr += 4 * width; // Subtype 2: Fredkin2 GLubyte transition_tableFredkin2[243] = { 0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableFredkin2[ind-1]; } ptr += 4 * width; // Subtype 3: Aggregation GLubyte transition_tableAggregation[243] = { 0,0,2,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,2,0,2,0,0,0,0,0,0,0,0,0,2,0,2,0,0,0,2,0,2,0,0,1,0,0,1,1,1,1,0,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1,1,0,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,2,0,2,1,2,2,2,0,2,0,2,0,1,0,1,0,2,2,2,2,2,1,2,2,2,0,1,2,0,1,2,0,1,0,1,2,2,0,1,1,2,1,1,0,0,0,1,1,1,1,1,1,2,0,2,1,2,2,2,1,2,1,2,1,1,1,1,1,1,1,2,0,2,1,1,1,2,1,1 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableAggregation[ind-1]; } ptr += 4 * width; // Subtype 4: Birds GLubyte transition_tableBirds[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,2,0,2,0,2,2,2,0,2,0,1,1,2,1,1,2,2,2,2,1,1,2,1,0,2,2,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,0,2,2,2,2,1,0,2,0,0,0,2,0,0,2,2,2,2,0,0,2,0,2,1,0,2,0,0,0,2,0,0,0,0,0,0,1,2,0,2,0,2,0,0,0,2,0,0,0,0,2,2,2,2,0,0,2,0,2,2,0,0,0,2,0,0,0,0,2,0,2,0,0,0,2,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,2,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableBirds[ind-1]; } ptr += 4 * width; // Subtype 5: Colony GLubyte transition_tableColony[243] = { 0,1,0,1,0,2,0,2,0,1,0,2,0,1,1,2,1,0,0,2,0,2,1,0,0,0,0,1,0,2,0,1,1,2,1,0,0,1,1,1,0,2,1,2,0,2,1,0,1,2,0,0,0,0,0,2,0,2,1,0,0,0,0,2,1,0,1,2,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,2,1,1,1,2,1,2,1,1,1,1,1,0,1,0,0,2,1,2,1,0,0,2,0,0,1,1,1,1,1,0,1,0,0,1,1,0,1,0,2,0,2,1,1,0,0,0,2,1,0,1,2,2,1,2,1,0,0,2,0,0,1,0,0,0,2,1,0,1,2,2,0,0,0,1,2,0,2,0,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableColony[ind-1]; } ptr += 4 * width; // Subtype 6: Crystal3a GLubyte transition_tableCrystal3a[243] = { 0,1,2,1,0,1,2,2,0,1,0,0,0,1,0,1,0,0,2,1,0,2,0,0,0,0,2,1,0,2,0,1,0,0,0,0,0,1,0,1,2,1,0,1,0,1,0,0,0,1,1,0,0,2,2,1,0,0,0,0,0,0,2,2,0,0,0,1,0,0,1,2,0,0,2,0,0,2,2,2,1,1,1,1,1,0,1,1,1,1,1,0,1,0,0,0,1,0,0,1,1,1,1,0,0,1,0,0,1,0,1,0,0,0,1,0,0,0,0,0,0,2,0,0,0,0,1,0,0,0,0,0,0,0,1,1,1,1,1,0,0,1,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,1,0,1,1,2,2,2,2,2,2,2,2,0,2,2,2,2,0,0,2,0,0,2,2,2,2,0,0,0,0,0,2,2,2,2,0,0,2,0,0,2,0,0,0,2,2,0,2,0,2,0,0,0,2,0,0,0,0,2,2,0,2,0,0,2,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableCrystal3a[ind-1]; } ptr += 4 * width; // Subtype 7: Crystal3b GLubyte transition_tableCrystal3b[243] = { 0,1,2,1,0,0,2,0,0,1,0,0,0,1,1,0,0,2,2,0,0,0,1,2,0,2,0,1,0,0,0,2,0,0,2,1,0,2,1,2,2,1,0,2,1,0,1,2,0,2,0,1,2,2,2,0,0,0,2,1,0,1,0,0,0,2,2,1,2,1,0,2,0,2,0,1,1,2,0,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,0,0,1,1,1,1,0,0,1,0,0,1,1,1,1,0,0,1,0,0,1,0,0,0,1,0,0,0,1,1,0,0,0,0,1,0,1,1,1,1,1,1,0,0,1,0,0,1,0,0,0,0,1,0,1,1,1,0,0,0,1,1,0,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,2,0,0,2,2,2,2,0,0,2,0,0,2,2,2,2,0,0,2,0,0,2,0,0,0,2,2,0,2,2,2,0,0,0,2,0,0,2,0,2,2,2,2,0,0,2,0,0,2,0,0,0,2,2,0,0,0,2,0,0,0,2,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableCrystal3b[ind-1]; } ptr += 4 * width; // Subtype 8: Galaxy GLubyte transition_tableGalaxy[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,0,0,2,0,2,2,0,0,0,0,1,1,2,1,1,2,2,2,0,1,1,2,1,1,0,2,0,0,2,2,0,2,0,0,0,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,2,2,2,0,0,2,0,0,0,2,0,0,2,2,2,2,0,0,2,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,2,0,2,0,2,2,2,2,0,0,2,0,0,2,0,0,0,0,2,0,2,0,2,0,0,0,2,0,0,0,2,0,2,0,2,2,0,0,0,0,2,2,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,0,2,2,0,0,0,0,2,2,0,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableGalaxy[ind-1]; } ptr += 4 * width; // Subtype 9: Greenberg GLubyte transition_tableGreenberg[243] = { 0,1,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableGreenberg[ind-1]; } ptr += 4 * width; // Subtype 10: Honeycomb GLubyte transition_tableHoneycomb[243] = { 0,1,0,1,0,2,0,2,0,1,0,2,0,0,2,2,2,2,0,2,0,2,2,2,0,2,0,1,0,2,0,0,2,2,2,2,0,0,2,0,0,2,2,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,0,1,1,2,0,2,0,1,1,2,1,0,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,0,0,2,0,2,1,0,0,0,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,0,0,0,0,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,2,2,0,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,0,2,2,2,2,0,2,0,2,2,2,0,2,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableHoneycomb[ind-1]; } ptr += 4 * width; // Subtype 11: Knitting GLubyte transition_tableKnitting[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,1,0,2,0,2,1,1,0,1,1,0,0,0,2,2,0,2,0,0,2,2,2,1,0,2,0,2,0,2,0,2,0,2,0,2,0,0,2,2,2,1,0,2,0,2,2,1,0,1,0,1,0,2,0,1,0,2,0,2,0,1,0,1,0,2,0,2,1,2,0,2,0,2,1,2,1,1,0,1,0,1,0,2,0,2,1,1,0,2,0,0,0,2,0,0,0,2,1,2,0,0,1,0,2,2,0,2,0,2,1,2,1,1,0,2,1,2,0,0,1,0,2,2,1,1,1,0,2,1,2,0,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableKnitting[ind-1]; } ptr += 4 * width; // Subtype 12: Lake GLubyte transition_tableLake[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,0,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,0,0,2,0,2,1,0,0,0,1,0,0,0,2,2,0,2,0,0,2,2,2,0,0,2,0,2,0,2,0,2,0,2,0,2,0,0,2,2,2,0,0,2,0,2,2,0,0,0,0,0,1,2,1,1,0,2,0,2,1,1,0,1,0,0,0,0,0,2,0,2,0,0,0,2,0,0,1,1,0,1,0,0,0,0,0,1,0,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,0,2,0,2,0,0,0,2,0,0,0,0,0,0,2,2,0,2,0,2,0,0,0,2,0,0,0,0,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableLake[ind-1]; } ptr += 4 * width; // Subtype 13: Plankton GLubyte transition_tablePlankton[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,2,0,2,0,2,2,2,0,2,0,1,1,2,1,1,2,2,2,2,1,1,2,1,0,2,2,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,0,0,0,0,2,0,2,0,0,0,2,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,1,0,2,0,2,0,1,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,0,0,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,2,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tablePlankton[ind-1]; } ptr += 4 * width; // Subtype 14: Pond GLubyte transition_tablePond[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,2,0,2,0,2,2,2,0,2,0,1,1,2,1,1,2,2,2,2,1,1,2,1,0,2,2,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,0,1,0,2,0,2,0,1,0,2,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,1,0,2,0,1,0,2,0,2,0,1,0,1,1,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,0,0,2,0,2,0,0,0,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,2,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tablePond[ind-1]; } ptr += 4 * width; // Subtype 15: Strata GLubyte transition_tableStrata[243] = { 0,0,0,0,0,0,2,0,0,1,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,2,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableStrata[ind-1]; } ptr += 4 * width; // Subtype 16: Tanks GLubyte transition_tableTanks[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,2,0,2,0,2,2,2,0,2,0,1,1,2,1,1,2,2,2,2,1,1,2,1,0,2,2,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,0,1,0,2,0,2,0,1,0,2,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,1,0,2,0,1,0,2,0,2,0,1,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,0,2,0,2,2,2,0,2,0,2,2,2,2,2,0,2,0,0,0,2,0,2,0,0,0,0,0,2,2,2,2,2,0,2,0,0,2,2,0,2,2,2,0,2,0,2,0,0,0,2,0,0,0,0,0,2,0,2,0,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableTanks[ind-1]; } ptr += 4 * width; // Subtype 17: Typhoon GLubyte transition_tableTyphoon[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,2,2,2,0,0,2,0,2,2,0,0,0,0,1,1,2,1,1,2,2,2,0,1,1,2,1,1,0,2,0,0,2,2,0,2,0,0,0,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,2,2,2,2,0,0,2,0,0,0,2,0,0,2,2,2,2,0,0,2,0,0,0,0,2,0,0,0,2,0,0,0,0,0,0,0,0,0,0,2,2,0,0,0,0,2,0,2,0,2,2,2,2,0,0,2,0,0,2,0,0,0,0,2,0,2,0,2,0,0,0,2,0,0,0,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableTyphoon[ind-1]; } ptr += 4 * width; // Subtype 18: Wave GLubyte transition_tableWave[243] = { 0,1,0,1,1,2,0,2,0,1,1,2,1,1,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,1,0,2,0,2,1,1,0,1,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,2,0,1,1,2,1,0,2,2,2,2,1,0,2,0,0,0,2,0,0,2,2,2,2,0,0,2,0,2,1,0,2,0,0,0,2,0,0,0,0,0,0,0,2,0,2,0,2,0,0,0,2,0,0,0,0,2,2,2,2,0,0,2,0,2,2,0,0,0,2,0,0,0,0,2,0,2,0,0,0,2,0,0,0,2,0,2,2,0,0,0,0,2,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,2,2,0,2,2,2,0,2,0,2,2,2,2,2,2,2,2,2,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0,0,2,0,2,2,2,0,2,0,0,0,0,0,2,0,0,0,0 }; ptr[ 0 ] = 3; for( int ind = 1 ; ind < std::min( width , 243+1 ) ; ind++ ) { ptr[ ind * 4 ] = transition_tableWave[ind-1]; } ptr += 4 * width; glEnable(GL_TEXTURE_RECTANGLE); glBindTexture( GL_TEXTURE_RECTANGLE, textureID ); glTexParameterf(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameterf(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); glTexImage2D(GL_TEXTURE_RECTANGLE, // Type of texture 0, // Pyramid level (for mip-mapping) - 0 is the top level GL_RGBA8, // Components: Internal colour format to convert to width, // Image width height, // Image heigh 0, // Border width in pixels (can either be 1 or 0) GL_RGBA, // Format: Input image format (i.e. GL_RGB, GL_RGBA, GL_BGR etc.) GL_UNSIGNED_BYTE, // Image data type data_table ); // The actual image data itself printOglError( 4 ); } bool pg_initTextures( void ) { pg_screenMessageBitmap = (GLubyte * )pg_generateTexture( &pg_screenMessageBitmap_ID , pg_byte_tex_format , PG_EnvironmentNode->message_pixel_length , 1 ); if( !pg_screenMessageBitmap ) { sprintf( ErrorStr , "Error: screen message bitmap not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } for(int indTrack = 0 ; indTrack < PG_NB_TRACKS ; indTrack++ ) { pg_tracks_Pos_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_Pos_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_Pos_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_Pos_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_tracks_Col_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_Col_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_Col_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_Col_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_tracks_RadBrushRendmode_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_RadBrushRendmode_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_RadBrushRendmode_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_RadBrushRendmode_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_tracks_Pos_target_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_Pos_target_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_Pos_target_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_Pos_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_tracks_Col_target_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_Col_target_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_Col_target_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_Col_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_tracks_RadBrushRendmode_target_Texture[indTrack] = (GLfloat * )pg_generateTexture( &(pg_tracks_RadBrushRendmode_target_Texture_ID[indTrack]) , pg_float_tex_format , PG_EnvironmentNode->Nb_max_mouse_recording_frames , 1 ); if( !pg_tracks_RadBrushRendmode_target_Texture[indTrack] ) { sprintf( ErrorStr , "Error: pg_tracks_RadBrushRendmode_Texture not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } } #define width_data_table 600 #define height_data_table 200 pg_CA_data_table = (GLubyte * )pg_generateTexture( &pg_CA_data_table_ID , pg_byte_tex_format , width_data_table , height_data_table ); pg_CA_data_table_values( pg_CA_data_table_ID , pg_CA_data_table, width_data_table , height_data_table ); if( !pg_CA_data_table_ID ) { sprintf( ErrorStr , "Error: data tables for the CA bitmap not allocated (%s)!" , ScreenMessage ); ReportError( ErrorStr ); throw 336; } pg_loadTexture( PG_EnvironmentNode->font_file_name , &Font_image , &Font_texture_Rectangle , true , false , GL_RGB8 , GL_LUMINANCE , GL_UNSIGNED_BYTE , GL_LINEAR , 128 , 70 ); pg_loadTexture( (char *)(project_name+"/textures/pen.png").c_str() , &Pen_image , &Pen_texture_2D , false , true , GL_RGBA8 , GL_RGBA , GL_UNSIGNED_BYTE , GL_LINEAR , 4096 , 512 ); pg_loadTexture( (char *)(project_name+"/textures/sensor.png").c_str() , &Sensor_image , &Sensor_texture_rectangle , true , false , GL_RGBA8 , GL_RGBA , GL_UNSIGNED_BYTE , GL_LINEAR , 300 , 100 ); pg_loadTexture( (char *)(project_name+"/textures/LYMlogo.png").c_str() , &LYMlogo_image , &LYMlogo_texture_rectangle , true , false , GL_RGBA8 , GL_RGBA , GL_UNSIGNED_BYTE , GL_LINEAR , 1024 , 768 ); pg_loadTexture( (char *)(project_name+"/textures/trackBrushes.png").c_str() , &trackBrush_image , &trackBrush_texture_2D , false , true , GL_RGBA8 , GL_RGBA , GL_UNSIGNED_BYTE , GL_LINEAR , 128 , 512 ); pg_loadTexture3D( (char *)(project_name+"/textures/ParticleAcceleration_alK_3D").c_str() , ".png" , 7 , 4 , true , &Particle_acceleration_texture_3D , GL_RGBA8 , GL_RGBA , GL_LINEAR , 2048 , 1024 , 7 ); return true; } ///////////////////////////////////////////////////////////////// // FBO INITIALIZATION ///////////////////////////////////////////////////////////////// GLuint drawBuffers[16] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2, GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4, GL_COLOR_ATTACHMENT5, GL_COLOR_ATTACHMENT6, GL_COLOR_ATTACHMENT7, GL_COLOR_ATTACHMENT8, GL_COLOR_ATTACHMENT9, GL_COLOR_ATTACHMENT10, GL_COLOR_ATTACHMENT11, GL_COLOR_ATTACHMENT12, GL_COLOR_ATTACHMENT13, GL_COLOR_ATTACHMENT14, GL_COLOR_ATTACHMENT15 }; ///////////////////////////////////////////// // FBO GLuint FBO_localColor_grayCA_tracks[PG_NB_MEMORIZED_PASS] = {0,0,0}; // nb_attachments=5 GLuint FBO_snapshot[2] = {0,0}; // drawing memory on odd and even frames for echo and sensors // FBO texture GLuint FBO_texID_localColor_grayCA_tracks[PG_NB_MEMORIZED_PASS*NB_ATTACHMENTS] = {0,0,0,0,0,0,0,0,0}; // nb_attachments=5 - PG_NB_MEMORIZED_PASS=3 GLuint FBO_texID_snapshot[PG_NB_TRACKS - 1] = {0,0}; // drawing memory on odd and even frames for echo and sensors bool pg_initFBOTextures( GLuint *textureID , int nb_attachments ) { glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S , GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); for( int indAtt = 0 ; indAtt < nb_attachments ; indAtt++ ) { glBindTexture(GL_TEXTURE_RECTANGLE, textureID[ indAtt ]); glTexParameteri(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_RECTANGLE,GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexStorage2D(GL_TEXTURE_RECTANGLE,1,GL_RGBA32F, singleWindowWidth , windowHeight ); glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + indAtt , GL_TEXTURE_RECTANGLE, textureID[ indAtt ] , 0 ); if(glCheckFramebufferStatus(GL_FRAMEBUFFER) ==GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT) { sprintf( ErrorStr , "Error: Binding RECT FBO texture No %d ID %d (error %d)!" , indAtt , textureID[ indAtt ] , glCheckFramebufferStatus(GL_FRAMEBUFFER) ); ReportError( ErrorStr ); throw 336; } } return true; } bool pg_initFBO( void ) { int maxbuffers; glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxbuffers); if( maxbuffers < NB_ATTACHMENTS ) { sprintf( ErrorStr , "Error: Maximal attachment (%d) -> %d required!" , maxbuffers , NB_ATTACHMENTS ); ReportError( ErrorStr ); throw 336; } glGenFramebuffers( PG_NB_MEMORIZED_PASS, FBO_localColor_grayCA_tracks ); glGenTextures(PG_NB_MEMORIZED_PASS * NB_ATTACHMENTS, FBO_texID_localColor_grayCA_tracks); for( int indFB = 0 ; indFB < PG_NB_MEMORIZED_PASS ; indFB++ ) { glBindFramebuffer( GL_FRAMEBUFFER, FBO_localColor_grayCA_tracks[indFB] ); pg_initFBOTextures( FBO_texID_localColor_grayCA_tracks + indFB * NB_ATTACHMENTS , NB_ATTACHMENTS ); glDrawBuffers( NB_ATTACHMENTS , drawBuffers); } glGenFramebuffers( 2, FBO_snapshot ); // drawing memory on odd and even frames for echo and sensors glGenTextures(2, FBO_texID_snapshot); // drawing memory on odd and even frames for echo and sensors for( int indFB = 0 ; indFB < 2 ; indFB++ ) { glBindFramebuffer( GL_FRAMEBUFFER, FBO_snapshot[indFB] ); pg_initFBOTextures( FBO_texID_snapshot + indFB , 1 ); glDrawBuffers( 1 , drawBuffers); } glBindFramebuffer( GL_FRAMEBUFFER, 0 ); return true; } ///////////////////////////////////////////////////////////////// // MATRIX INITIALIZATION ///////////////////////////////////////////////////////////////// void pg_initRenderingMatrices( void ) { memset( (char *)viewMatrix , 0 , 16 * sizeof( float ) ); memset( (char *)modelMatrix , 0 , 16 * sizeof( float ) ); memset( (char *)modelMatrixSensor , 0 , 16 * sizeof( float ) ); viewMatrix[0] = 1.0f; viewMatrix[5] = 1.0f; viewMatrix[10] = 1.0f; viewMatrix[15] = 1.0f; modelMatrix[0] = 1.0f; modelMatrix[5] = 1.0f; modelMatrix[10] = 1.0f; modelMatrix[15] = 1.0f; modelMatrixSensor[0] = 1.0f; modelMatrixSensor[5] = 1.0f; modelMatrixSensor[10] = 1.0f; modelMatrixSensor[15] = 1.0f; // ORTHO float l = 0.0f; float r = (float)singleWindowWidth; float b = 0.0f; float t = (float)windowHeight; float n = -1.0f; float f = 1.0f; GLfloat mat[] = { (GLfloat)(2.0/(r-l)), 0.0, 0.0, 0.0, 0.0, (GLfloat)(2.0/(t-b)), 0.0, 0.0, 0.0, 0.0, (GLfloat)(2.0/(f-n)), 0.0, (GLfloat)(-(r+l)/(r-l)), (GLfloat)(-(t+b)/(t-b)), (GLfloat)(-(f+n)/(f-n)), 1.0 }; memcpy( (char *)projMatrix , mat , 16 * sizeof( float ) ); // printf("Orthographic projection l %.2f r %.2f b %.2f t %.2f n %.2f f %.2f\n" , l,r,b,t,n,f); r = (float)doubleWindowWidth; GLfloat mat2[] = { (GLfloat)(2.0/(r-l)), 0.0, 0.0, 0.0, 0.0, (GLfloat)(2.0/(t-b)), 0.0, 0.0, 0.0, 0.0, (GLfloat)(2.0/(f-n)), 0.0, (GLfloat)(-(r+l)/(r-l)), (GLfloat)(-(t+b)/(t-b)), (GLfloat)(-(f+n)/(f-n)), 1.0 }; memcpy( (char *)doubleProjMatrix , mat2 , 16 * sizeof( float ) ); // printf("Double width orthographic projection l %.2f r %.2f b %.2f t %.2f n %.2f f %.2f\n" , l,r,b,t,n,f); } /////////////////////////////////////////////////////// // On-Screen Message Display /////////////////////////////////////////////////////// void pg_screenMessage_update( void ) { // GLbyte *xfont = NULL; GLubyte *yfont = NULL; GLubyte *wfont = NULL; GLubyte *hfont = NULL; GLubyte *sfont = NULL; GLubyte *tfont = NULL; // GLubyte *afont = NULL; if( NewScreenMessage ) { switch( PG_EnvironmentNode->font_size ) { case 10: // xfont = stb__arial_10_usascii_x; yfont = stb__arial_10_usascii_y; wfont = stb__arial_10_usascii_w; hfont = stb__arial_10_usascii_h; sfont = stb__arial_10_usascii_s; tfont = stb__arial_10_usascii_t; // afont = stb__arial_10_usascii_a; break; case 11: // xfont = stb__arial_11_usascii_x; yfont = stb__arial_11_usascii_y; wfont = stb__arial_11_usascii_w; hfont = stb__arial_11_usascii_h; sfont = stb__arial_11_usascii_s; tfont = stb__arial_11_usascii_t; // afont = stb__arial_11_usascii_a; break; case 12: // xfont = stb__arial_12_usascii_x; yfont = stb__arial_12_usascii_y; wfont = stb__arial_12_usascii_w; hfont = stb__arial_12_usascii_h; sfont = stb__arial_12_usascii_s; tfont = stb__arial_12_usascii_t; // afont = stb__arial_12_usascii_a; break; case 13: // xfont = stb__arial_13_usascii_x; yfont = stb__arial_13_usascii_y; wfont = stb__arial_13_usascii_w; hfont = stb__arial_13_usascii_h; sfont = stb__arial_13_usascii_s; tfont = stb__arial_13_usascii_t; // afont = stb__arial_13_usascii_a; break; case 14: // xfont = stb__arial_14_usascii_x; yfont = stb__arial_14_usascii_y; wfont = stb__arial_14_usascii_w; hfont = stb__arial_14_usascii_h; sfont = stb__arial_14_usascii_s; tfont = stb__arial_14_usascii_t; // afont = stb__arial_14_usascii_a; break; case 15: // xfont = stb__arial_15_usascii_x; yfont = stb__arial_15_usascii_y; wfont = stb__arial_15_usascii_w; hfont = stb__arial_15_usascii_h; sfont = stb__arial_15_usascii_s; tfont = stb__arial_15_usascii_t; // afont = stb__arial_15_usascii_a; break; case 16: // xfont = stb__arial_16_usascii_x; yfont = stb__arial_16_usascii_y; wfont = stb__arial_16_usascii_w; hfont = stb__arial_16_usascii_h; sfont = stb__arial_16_usascii_s; tfont = stb__arial_16_usascii_t; // afont = stb__arial_16_usascii_a; break; case 17: // xfont = stb__arial_17_usascii_x; yfont = stb__arial_17_usascii_y; wfont = stb__arial_17_usascii_w; hfont = stb__arial_17_usascii_h; sfont = stb__arial_17_usascii_s; tfont = stb__arial_17_usascii_t; // afont = stb__arial_17_usascii_a; break; default: case 18: // xfont = stb__arial_18_usascii_x; yfont = stb__arial_18_usascii_y; wfont = stb__arial_18_usascii_w; hfont = stb__arial_18_usascii_h; sfont = stb__arial_18_usascii_s; tfont = stb__arial_18_usascii_t; // afont = stb__arial_18_usascii_a; break; } int pixelRank = 0; int lengthMax = PG_EnvironmentNode->message_pixel_length; memset(pg_screenMessageBitmap, (GLubyte)0, lengthMax * 4 ); // strcpy( ScreenMessage , "abcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuvwxyabcdefghijklmnopqrstuv"); // strcpy( ScreenMessage , "abcdefghijkl"); // lengthMax = 30; for (char *c = ScreenMessage ; *c != '\0' && pixelRank < lengthMax ; c++) { char cur_car = *c; if( cur_car == 'é' || cur_car == 'è' || cur_car == 'ê' || cur_car == 'ë' ) { cur_car = 'e'; } if( cur_car == 'à' || cur_car == 'â' ) { cur_car = 'a'; } if( cur_car == 'î' || cur_car == 'ï' ) { cur_car = 'i'; } if( cur_car == 'É' || cur_car == 'È' || cur_car == 'Ê' || cur_car == 'Ë' ) { cur_car = 'E'; } if( cur_car == 'À' || cur_car == 'Â' ) { cur_car = 'A'; } if( cur_car == 'Î' || cur_car == 'Ï' ) { cur_car = 'I'; } // usable ascii starts at blank space int cur_car_rank = (int)cur_car - 32; cur_car_rank = (cur_car_rank < 0 ? 0 : cur_car_rank ); cur_car_rank = (cur_car_rank > 94 ? 94 : cur_car_rank ); // defines offset according to table for( int indPixel = 0 ; indPixel < wfont[ cur_car_rank ] && pixelRank + indPixel < lengthMax ; indPixel++ ) { int indPixelColor = (pixelRank + indPixel) * 4; pg_screenMessageBitmap[ indPixelColor ] = sfont[ cur_car_rank ]+indPixel; pg_screenMessageBitmap[ indPixelColor + 1 ] = tfont[ cur_car_rank ]; pg_screenMessageBitmap[ indPixelColor + 2 ] = hfont[ cur_car_rank ]; pg_screenMessageBitmap[ indPixelColor + 3 ] = yfont[ cur_car_rank ]; // printf( "%d %d - " , sfont[ cur_car_rank ] , tfont[ cur_car_rank ] ); } pixelRank += wfont[ cur_car_rank ] + 1; } glBindTexture( GL_TEXTURE_RECTANGLE, pg_screenMessageBitmap_ID ); glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glTexParameteri(GL_TEXTURE_RECTANGLE, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); glTexImage2D(GL_TEXTURE_RECTANGLE, // Type of texture 0, // Pyramid level (for mip-mapping) - 0 is the top level GL_RGBA8, // Internal colour format to convert to lengthMax, // Image width 1, // Image height 0, // Border width in pixels (can either be 1 or 0) GL_RGBA, // Input image format (i.e. GL_RGB, GL_RGBA, GL_BGR etc.) GL_UNSIGNED_BYTE, // Image data type pg_screenMessageBitmap); // The actual image data itself NewScreenMessage = false; printOglError( 6 ); } } /////////////////////////////////////////////////////// // GLUT draw function (from the viewpoint) // the glut callback // requires predrawing (drawing from the user to the root node) // ------------------------------------------------------------ // // --------------- DISPLAYS WINDOWS ONE AFTER ANOTHER --------- // // ------------------------------------------------------------ // void window_display( void ) { // CurrentWindow = PG_EnvironmentNode->PG_Window; // glutSetWindow( CurrentWindow->glutID ); PG_EnvironmentNode->windowDisplayed = true; // fprintf(fileLog,"begin window_display %.10f\n" , RealTime() ); // OpenGL initializations before redisplay OpenGLInit(); // fprintf(fileLog,"after OPenGLInit %.10f\n" , RealTime() ); // proper scene redrawing pg_draw_scene( _Render ); // fprintf(fileLog,"after draw scene %.10f\n" , RealTime() ); // specific features for interactive environments with // messages // printf( "Window %s\n" , CurrentWindow->id ); pg_screenMessage_update(); // flushes OpenGL commands glFlush(); glutSwapBuffers(); // // fprintf(fileLog,"after glutSwapBuffers %.10f\n" , RealTime() ); // ------------------------------------------------------------ // // --------------- FRAME/SUBFRAME GRABBING -------------------- // // ---------------- frame by frame output --------------------- // // Svg screen shots // printf("Draw Svg\n" ); if( PG_EnvironmentNode->outputSvg && FrameNo % PG_EnvironmentNode->stepSvg == 0 && FrameNo / PG_EnvironmentNode->stepSvg >= PG_EnvironmentNode->beginSvg && FrameNo / PG_EnvironmentNode->stepSvg <= PG_EnvironmentNode->endSvg ) { // printf("Draw Svg %d\n" , FrameNo ); pg_draw_scene( _Svg ); } // ---------------- frame by frame output --------------------- // // Png screen shots // printf("Draw Png\n" ); if( PG_EnvironmentNode->outputPng && FrameNo % PG_EnvironmentNode->stepPng == 0 && FrameNo / PG_EnvironmentNode->stepPng >= PG_EnvironmentNode->beginPng && FrameNo / PG_EnvironmentNode->stepPng <= PG_EnvironmentNode->endPng ) { pg_draw_scene( _Png ); } // ---------------- frame by frame output --------------------- // // Jpg screen shots // printf("Draw Jpg\n" ); if( PG_EnvironmentNode->outputJpg && FrameNo % PG_EnvironmentNode->stepJpg == 0 && FrameNo / PG_EnvironmentNode->stepJpg >= PG_EnvironmentNode->beginJpg && FrameNo / PG_EnvironmentNode->stepJpg <= PG_EnvironmentNode->endJpg ) { pg_draw_scene( _Jpg ); } } ////////////////////////////////////////////////////////////////////// // SAVE IMAGE ////////////////////////////////////////////////////////////////////// /* Attempts to save PNG to file; returns 0 on success, non-zero on error. */ int writepng(char *filename, int x, int y, int width, int height ) { cv::Mat img( height, width, CV_8UC3 ); // OpenGL's default 4 byte pack alignment would leave extra bytes at the // end of each image row so that each full row contained a number of bytes // divisible by 4. Ie, an RGB row with 3 pixels and 8-bit componets would // be laid out like "RGBRGBRGBxxx" where the last three "xxx" bytes exist // just to pad the row out to 12 bytes (12 is divisible by 4). To make sure // the rows are packed as tight as possible (no row padding), set the pack // alignment to 1. glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, img.data); cv::Mat result; cv::flip(img, result , 0); // vertical flip #ifndef OPENCV_3 cv::cvtColor(result, result, CV_RGB2BGR); std::vector<int> params; params.push_back(CV_IMWRITE_PNG_COMPRESSION); #else cv::cvtColor(result, result, cv::COLOR_RGB2BGR); std::vector<int> params; params.push_back(cv::IMWRITE_PNG_COMPRESSION); #endif params.push_back(9); params.push_back(0); cv::imwrite( filename, result ); return 0; } /* Attempts to save JPG to file; returns 0 on success, non-zero on error. */ int writejpg(char *filename, int x, int y, int width, int height, int compression) { cv::Mat img( height, width, CV_8UC3 ); // OpenGL's default 4 byte pack alignment would leave extra bytes at the // end of each image row so that each full row contained a number of bytes // divisible by 4. Ie, an RGB row with 3 pixels and 8-bit componets would // be laid out like "RGBRGBRGBxxx" where the last three "xxx" bytes exist // just to pad the row out to 12 bytes (12 is divisible by 4). To make sure // the rows are packed as tight as possible (no row padding), set the pack // alignment to 1. glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, img.data); cv::Mat result; cv::flip(img, result , 0); // vertical flip #ifndef OPENCV_3 cv::cvtColor(result, result, CV_RGB2BGR); std::vector<int> params; params.push_back(CV_IMWRITE_JPEG_QUALITY); #else cv::cvtColor(result, result, cv::COLOR_RGB2BGR); std::vector<int> params; params.push_back(cv::IMWRITE_JPEG_QUALITY); #endif params.push_back(70); // that's percent, so 100 == no compression, 1 == full cv::imwrite( filename, result ); return 0; } //// sample choice //// current sample choice //int sample_choice[ PG_NB_SENSORS]; //// all possible sensor layouts //int sample_setUps[ PG_NB_MAX_SAMPLE_SETUPS][ PG_NB_SENSORS ] = // {{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25}, // {26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50}, // {51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75}}; //// groups of samples for aliasing with additive samples //int sample_groups[ 18 ][ 4 ] = // { { 1, 2, 6, 7 }, // { 4, 5, 9, 10 }, // { 16, 17, 21, 22 }, // { 19, 20, 24, 25 }, // { 8, 12, 14, 18 }, // { 3, 11, 15, 23 }, // // { 26, 27, 31, 32 }, // { 29, 30, 34, 35 }, // { 41, 42, 46, 48 }, // { 44, 45, 49, 50 }, // { 33, 37, 39, 43 }, // { 28, 36, 40, 48 }, // // { 51, 52, 56, 57 }, // { 54, 55, 59, 60 }, // { 66, 67, 71, 72 }, // { 69, 70, 74, 75 }, // { 58, 62, 64, 68 }, // { 53, 61, 65, 73 } }; void readSensors( void ) { float sensorValues[PG_NB_SENSORS + 18]; bool sensorOn[PG_NB_SENSORS + 18]; bool sampleOn[PG_NB_MAX_SAMPLE_SETUPS * PG_NB_SENSORS]; int sampleToSensorPointer[PG_NB_MAX_SAMPLE_SETUPS * PG_NB_SENSORS]; GLubyte pixelColor[3 * PG_NB_SENSORS]; // marks all the samples as unread for( int indSample = 0 ; indSample < PG_NB_MAX_SAMPLE_SETUPS * PG_NB_SENSORS ; indSample++ ) { sampleOn[indSample] = false; sampleToSensorPointer[indSample] = -1; } glPixelStorei(GL_PACK_ALIGNMENT, 1); // sensor readback //printf("sensor on "); for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { if( sensor_onOff[ indSens ] ) { glReadPixels( (int)sensorPositions[ 3 * indSens ], (int)(sensorPositions[ 3 * indSens + 1]), 1, 1, GL_RGB, GL_UNSIGNED_BYTE, pixelColor + 3 * indSens ); sensorValues[indSens] = ( pixelColor[ 3 * indSens ] + pixelColor[ 3 * indSens + 1] + pixelColor[ 3 * indSens + 2])/(255.f * 3.f); sensorOn[indSens] = ( sensorValues[indSens] > 0.0f ); if( sensorOn[indSens] ) { sampleOn[ sample_choice[ indSens ] ] = true; sampleToSensorPointer[ sample_choice[ indSens ] ] = indSens; //printf("%d ",indSens); } } else { sensorValues[indSens] = 0.0f; sensorOn[indSens] = false; } } //printf("\n"); // looks for buffer aliasing possibilities: groups of sounds that could be replaced by a single buffer bool groupOn[18]; float groupValues[18]; //printf("group on "); for(int indgroup = 0 ; indgroup < 18 ; indgroup++ ) { if( sampleOn[ sample_groups[ indgroup ][ 0 ] ] && sampleOn[ sample_groups[ indgroup ][ 1 ] ] && sampleOn[ sample_groups[ indgroup ][ 2 ] ] && sampleOn[ sample_groups[ indgroup ][ 3 ] ] ) { // switches on the group with the average activation value groupOn[indgroup] = true; groupValues[indgroup] = ( sensorValues[ sampleToSensorPointer[ sample_groups[ indgroup ][ 0 ] ] ] + sensorValues[ sampleToSensorPointer[ sample_groups[ indgroup ][ 1 ] ] ] + sensorValues[ sampleToSensorPointer[ sample_groups[ indgroup ][ 2 ] ] ] + sensorValues[ sampleToSensorPointer[ sample_groups[ indgroup ][ 3 ] ] ] ); // switches off the associated sensors sensorValues[sampleToSensorPointer[ sample_groups[ indgroup ][ 0 ] ]] = 0.0f; sensorOn[sampleToSensorPointer[ sample_groups[ indgroup ][ 0 ] ]] = false; sensorValues[sampleToSensorPointer[ sample_groups[ indgroup ][ 1 ] ]] = 0.0f; sensorOn[sampleToSensorPointer[ sample_groups[ indgroup ][ 1 ] ]] = false; sensorValues[sampleToSensorPointer[ sample_groups[ indgroup ][ 2 ] ]] = 0.0f; sensorOn[sampleToSensorPointer[ sample_groups[ indgroup ][ 2 ] ]] = false; sensorValues[sampleToSensorPointer[ sample_groups[ indgroup ][ 3 ] ]] = 0.0f; sensorOn[sampleToSensorPointer[ sample_groups[ indgroup ][ 3 ] ]] = false; //printf("%d (%d,%d,%d,%d) ",indgroup,sampleToSensorPointer[ sample_groups[ indgroup ][ 0 ] ], // sampleToSensorPointer[ sample_groups[ indgroup ][ 1 ] ], // sampleToSensorPointer[ sample_groups[ indgroup ][ 2 ] ], // sampleToSensorPointer[ sample_groups[ indgroup ][ 3 ] ]); } else { groupOn[indgroup] = false; groupValues[indgroup] = 0.0f; } } //printf("\n"); // message value std::string float_str; std::string message = "/sensors"; float totalAmplitude = 0.0; for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { if( sensorOn[indSens] ) { float_str = std::to_string(static_cast<long double>(sensorValues[ indSens ])); // float_str.resize(4); message += " " + float_str; totalAmplitude += sensorValues[ indSens ]; } else { message += " 0.0"; } } for(int indgroup = 0 ; indgroup < 18 ; indgroup++ ) { if( groupOn[indgroup] ) { float_str = std::to_string(static_cast<long double>(groupValues[indgroup])); // float_str.resize(4); message += " " + float_str; totalAmplitude += groupValues[indgroup]; } else { message += " 0.0"; } } float_str = std::to_string(static_cast<long double>(totalAmplitude)); // float_str.resize(4); message += " " + float_str; // message format std::string format = ""; for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { format += "f "; } for(int indgroup = 0 ; indgroup < 18 ; indgroup++ ) { format += "f "; } // Total amplitude format += "f"; // message posting pg_send_message_udp( (char *)format.c_str() , (char *)message.c_str() , (char *)"udp_SC_send" ); // message trace //std::cout << "format: " << format << "\n"; //std::cout << "msg: " << message << "\n"; } ////////////////////////////////////////////////////// // SCENE RENDERING ////////////////////////////////////////////////////// // generic interactive draw function (from the root) // scene redisplay (controlled by a drawing mode: file, interactive // or edition) void pg_update_scene( void ) { /////////////////////////////////////////////////////////////////////// // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // +++ mouse pointer adjustment according to music +++++++ // +++ notice that there is one frame delay ++++++++++++++ // +++ for taking these values in consideration ++++++++++ // +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ mouse_x_deviation = xy_spectrum[0] * xy_spectrum_coef; mouse_y_deviation = xy_spectrum[1] * xy_spectrum_coef; bool is_trackreplay = false; switch( currentTrack ) { case 0: is_trackreplay = track_replay_0; break; } if( !is_trackreplay ) { if( activeDrawingStroke > 0 ) { tracks_x[ currentTrack ] = mouse_x; tracks_y[ currentTrack ] = mouse_y; tracks_x_prev[ currentTrack ] = mouse_x_prev; tracks_y_prev[ currentTrack ] = mouse_y_prev; } else { tracks_x[ currentTrack ] = -1; tracks_y[ currentTrack ] = -1; tracks_x_prev[ currentTrack ] = -1; tracks_y_prev[ currentTrack ] = -1; } } // printf("Track %d %.1fx%.1f prev: %.1fx%.1f\n",currentTrack,tracks_x[ currentTrack ],tracks_y[ currentTrack ],tracks_x_prev[ currentTrack ],tracks_y_prev[ currentTrack ]); // <write_console value="Position: currentTrack activeDrawingStroke ({$config:track_replay[1]}) ({$config:tracks_BrushID[1]}) ({$config:tracks_RadiusX[1]}) ({$config:tracks_RadiusY[1]}) ({$config:tracks_x[1]}) ({$config:tracks_y[1]})"/> ///////////////////////////////////////////////////////////////////////// // DRAWING SHADER UNIFORM VARIABLES glUseProgram(shader_Drawing_programme); // drawing off and drawing point or line glUniform4f(uniform_Drawing_fs_4fv_W_H_drawingStart_drawingStroke , (GLfloat)singleWindowWidth , (GLfloat)windowHeight , (GLfloat)drawing_start_frame , (GLfloat)activeDrawingStroke ); // acceleration center and CA subtype // in case of interpolation between CA1 and CA2 // if( !BrokenInterpolationVar[ _CA1_CA2_weight ] ) { // if( CA1_CA2_weight < 1.0 && CA1_CA2_weight > 0.0 ) { // float randVal = (float)rand() / (float)RAND_MAX; // if( randVal <= CA1_CA2_weight ) { //CAType = CA1TypeSubType / 10; //CASubType = CA1TypeSubType % 10; // } // else { //CAType = CA2TypeSubType / 10; //CASubType = CA2TypeSubType % 10; // } // } // else if( CA1_CA2_weight >= 1.0 ) { // CAType = CA1TypeSubType / 10; // CASubType = CA1TypeSubType % 10; // } // else if( CA1_CA2_weight <= 0.0 ) { // CAType = CA2TypeSubType / 10; // CASubType = CA2TypeSubType % 10; // } // // printf("CA type/subtype %d-%d\n" , CAType , CASubType ); // } glUniform4f(uniform_Drawing_fs_4fv_CAType_CASubType_partAccCenter , (float)CAType , (float)CASubType , partAccCenter_0 , partAccCenter_1 ); // particle acceleration glUniform4f(uniform_Drawing_fs_4fv_partMode_partAcc_clearLayer_void , (GLfloat)particleMode, part_acc_factor + particle_acc_attack, (GLfloat)isClearAllLayers , 0.0f ); // track decay glUniform3f(uniform_Drawing_fs_3fv_trackdecay_CAstep_initCA , trackdecay_0*trackdecay_sign_0 , (GLfloat)CAstep , initCA ); // one shot CA launching if( initCA ) { initCA = 0.0f; } // CA decay, flash glUniform4f(uniform_Drawing_fs_4fv_flashPart_isBeat_void_clearCA , (GLfloat)flashPart, (GLfloat)isBeat , 0.0f , (GLfloat)isClearCA ); // CA type, frame no, flashback and current track glUniform4f(uniform_Drawing_fs_4fv_CAdecay_frameno_partTexture_currentTrack , CAdecay*CAdecay_sign, (GLfloat)FrameNo, particle_texture_ID, (GLfloat)currentTrack); // flash back & CA coefs glUniform4f(uniform_Drawing_fs_4fv_flashBackCoef_flashCACoefs, flashBack_weight, flashCA_weights[0], flashCA_weights[1], flashCA_weights[2] ); // printf("flashCA_weights %.2f %.2f %.2f \n",flashCA_weights[0], flashCA_weights[1], flashCA_weights[2] ); // pen position storage on the two quads glUniform3f(uniform_Drawing_fs_3fv_mouseTracks_replay , (track_replay_0 ? 1.0f : -1.0f), (-1.0f), (-1.0f)); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_x , 1 , tracks_x); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_y , 1 , tracks_y); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_x_prev , 1 , tracks_x_prev); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_y_prev , 1 , tracks_y_prev); // pen color glUniform3fv(uniform_Drawing_fs_3fv_mouseTracks_Color_r , 1 , tracks_Color_r); glUniform3fv(uniform_Drawing_fs_3fv_mouseTracks_Color_g , 1 , tracks_Color_g); glUniform3fv(uniform_Drawing_fs_3fv_mouseTracks_Color_b , 1 , tracks_Color_b); glUniform3fv(uniform_Drawing_fs_3fv_mouseTracks_Color_a , 1 , tracks_Color_a); // pen brush & size glUniform3f(uniform_Drawing_fs_3fv_mouseTracks_BrushID , (GLfloat)tracks_BrushID[0] , (GLfloat)tracks_BrushID[1] , (GLfloat)tracks_BrushID[2] ); // printf("Current track %d BrushID %.2f %.2f %.2f\n" , currentTrack , tracks_BrushID[0] , tracks_BrushID[1] , tracks_BrushID[2] ); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_RadiusX , 1 , tracks_RadiusX); glUniform4fv(uniform_Drawing_fs_4fv_mouseTracks_RadiusY , 1 , tracks_RadiusY); ///////////////////////////////////////////////////////////////////////// // COMPOSITION SHADER UNIFORM VARIABLES glUseProgram(shader_Composition_programme); // CA weight glUniform3f(uniform_Composition_fs_3fv_width_height_CAweight , (GLfloat)singleWindowWidth , (GLfloat)windowHeight , CAweight ); // track weight glUniform3f(uniform_Composition_fs_3fv_trackweight , trackweight_0 , 0.0f , 0.0f ); // message transparency & echo glUniform4f(uniform_Composition_fs_4fv_messageTransparency_echo_echoNeg_invert , messageTransparency , echo , echoNeg ,(invertAllLayers ? 1.0f : -1.0f) ); ///////////////////////////////////////////////////////////////////////// // FINAL SHADER UNIFORM VARIABLES glUseProgram(shader_Final_programme); glUniform2f(uniform_Final_fs_2fv_transparency_scale, blendTransp, scale ); // hoover cursor glUniform4f(uniform_Final_fs_4fv_xy_frameno_cursorSize , (GLfloat)CurrentCursorHooverPos_x, (GLfloat)CurrentCursorHooverPos_y, (GLfloat)FrameNo, (GLfloat)PG_EnvironmentNode->cursorSize); glUniform2f(uniform_Final_fs_2fv_tablet1xy , xy_hoover_tablet1[0] , xy_hoover_tablet1[1] ); ///////////////////////////////////////////////////////////////////////// // SENSOR SHADER UNIFORM VARIABLES glUseProgram(shader_Sensor_programme); //glUniform2f(uniform_Sensor_fs_2fv_frameno_invert, // (GLfloat)FrameNo, (invertAllLayers ? 1.0f : -1.0f) ); if( sensorFollowMouse_onOff && (mouse_x > 0 || mouse_y > 0) ) { sensorPositions[ 3 * currentSensor ] = mouse_x; sensorPositions[ 3 * currentSensor + 1 ] = windowHeight - mouse_y; } /////////////////////////////////////////////////////////////////////// // saves mouse values mouse_x_prev = mouse_x; mouse_y_prev = mouse_y; /////////////////////////////////////////////////////////////////////// // flash reset: restores flash to 0 so that // it does not stay on more than one frame for( int indtrack = 0 ; indtrack < PG_NB_TRACKS ; indtrack++ ) { flashCA_weights[indtrack] = 0; } if( flashPart > 0 ) { flashPart -= 1; } flashBack_weight = 0; // ///////////////////////// // clear layer reset clearAllLayers = false; // clear CA reset isClearCA = 0; // clear layer reset isClearAllLayers = 0; } void pg_draw_scene( DrawingMode mode ) { // ******************** Svg output ******************** if( mode == _Svg ) { sprintf( currentFilename , "%s%s.%07d.svg" , PG_EnvironmentNode->Svg_shot_dir_name , PG_EnvironmentNode->Svg_file_name , FrameNo / PG_EnvironmentNode->stepSvg ); fprintf( fileLog , "Snapshot svg step %d (%s)\n" , FrameNo / PG_EnvironmentNode->stepSvg , currentFilename ); writesvg(currentFilename, singleWindowWidth , windowHeight ); } // ******************** Png output ******************** else if( mode == _Png ) { sprintf( currentFilename , "%s%s.%07d.png" , PG_EnvironmentNode->Png_shot_dir_name , PG_EnvironmentNode->Png_file_name , FrameNo / PG_EnvironmentNode->stepPng ); fprintf( fileLog , "Snapshot png step %d (%s)\n" , FrameNo / PG_EnvironmentNode->stepPng , currentFilename ); glReadBuffer(GL_FRONT); writepng(currentFilename, 0,0, singleWindowWidth , windowHeight ); } // ******************** Jpg output ******************** else if( mode == _Jpg ) { sprintf( currentFilename , "%s%s.%07d.jpg" , PG_EnvironmentNode->Jpg_shot_dir_name , PG_EnvironmentNode->Jpg_file_name , FrameNo / PG_EnvironmentNode->stepJpg ); fprintf( fileLog , "Snapshot jpg step %d (%s)\n" , FrameNo / PG_EnvironmentNode->stepJpg , currentFilename ); printf( "Snapshot jpg step %d (%s)\n" , FrameNo / PG_EnvironmentNode->stepJpg , currentFilename ); glReadBuffer(GL_FRONT); writejpg(currentFilename, 0,0, singleWindowWidth , windowHeight ,75); } // ******************** Video output ******************** #ifdef PG_HAVE_FFMPEG else if( mode == _Video && PG_EnvironmentNode->audioVideoOutData ) { glReadBuffer(GL_BACK); PG_EnvironmentNode->audioVideoOutData ->write_frame(); } #endif // ******************** interactive output ******************** // ******************** (OpenGL or evi3d) ******************** else if( mode == _Render ) { ////////////////////////////////////////////////// // SCENE UPDATE pg_update_scene(); printOglError( 51 ); ////////////////////////////////////////////////// // PASS #1: PING PONG DRAWING // sets viewport to single window glViewport (0, 0, singleWindowWidth , windowHeight ); // ping pong output and input FBO bindings // glBindFramebuffer(GL_READ_FRAMEBUFFER, FBO_localColor_grayCA_tracks[(FrameNo % PG_NB_MEMORIZED_PASS)]); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, FBO_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS)]); // output buffer cleanup glDisable( GL_DEPTH_TEST ); glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor( 0.0 , 0.0 , 0.0 , 1.0 ); //////////////////////////////////////// // activate shaders and sets uniform variable values glUseProgram (shader_Drawing_programme); glBindVertexArray (quadDraw_vao); glUniformMatrix4fv(uniform_Drawing_vp_proj, 1, GL_FALSE, projMatrix); glUniformMatrix4fv(uniform_Drawing_vp_view, 1, GL_FALSE, viewMatrix); glUniformMatrix4fv(uniform_Drawing_vp_model, 1, GL_FALSE, modelMatrix); // texture unit location glUniform1i(uniform_Drawing_texture_fs_decal, 0); glUniform1i(uniform_Drawing_texture_fs_lookupTable1, 1); glUniform1i(uniform_Drawing_texture_fs_lookupTable2, 2); glUniform1i(uniform_Drawing_texture_fs_lookupTable3, 3); glUniform1i(uniform_Drawing_texture_fs_lookupTable4, 4); glUniform1i(uniform_Drawing_texture_fs_lookupTable5, 5); glUniform1i(uniform_Drawing_texture_fs_lookupTable6, 6); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); // 3-cycle ping-pong localColor step n (FBO attachment 1) glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[(FrameNo % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS]); // 3-cycle ping-pong speed/position of particles step n step n (FBO attachment 2) glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[(FrameNo % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 1]); // 3-cycle ping-pong CA step n+2 (or n-1) (FBO attachment 1) glActiveTexture(GL_TEXTURE0 + 2); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[((FrameNo + 2) % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 2]); // 3-cycle ping-pong CA step n (FBO attachment 3) glActiveTexture(GL_TEXTURE0 + 3); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[(FrameNo % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 2]); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S , GL_REPEAT ); glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); // pen patterns glActiveTexture(GL_TEXTURE0 + 4); glBindTexture(GL_TEXTURE_2D, Pen_texture_2D ); // particle acceleration texture glActiveTexture(GL_TEXTURE0 + 5); glBindTexture(GL_TEXTURE_3D, Particle_acceleration_texture_3D ); // data tables for the CA glActiveTexture(GL_TEXTURE0 + 6); glBindTexture(GL_TEXTURE_RECTANGLE, pg_CA_data_table_ID ); // draw points from the currently bound VAO with current in-use shader glDrawArrays (GL_TRIANGLES, 0, 3 * nbFaces); printOglError( 52 ); ////////////////////////////////////////////////// // PASS #2: COMPOSITION + PING-PONG ECHO // binds input to last output // glBindFramebuffer(GL_READ_FRAMEBUFFER, FBO_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS)]); ///////////////////////////////////////////////////////// // draws the main rectangular surface with // outputs inside a buffer that can be used for accumulation if( FrameNo > 0 ) { glBindFramebuffer(GL_DRAW_FRAMEBUFFER, FBO_snapshot[(FrameNo % 2)]); // drawing memory on odd and even frames for echo and sensors } // output video buffer clean-up glClear (GL_COLOR_BUFFER_BIT); glClearColor( 0.0 , 0.0 , 0.0 , 1.0 ); //////////////////////////////////////// // activate shaders and sets uniform variable values glUseProgram (shader_Composition_programme); glBindVertexArray (quadDraw_vao); glUniformMatrix4fv(uniform_Composition_vp_proj, 1, GL_FALSE, projMatrix); glUniformMatrix4fv(uniform_Composition_vp_view, 1, GL_FALSE, viewMatrix); glUniformMatrix4fv(uniform_Composition_vp_model, 1, GL_FALSE, modelMatrix); // texture unit location glUniform1i(uniform_Composition_texture_fs_decal, 0); glUniform1i(uniform_Composition_texture_fs_lookupTable1, 1); glUniform1i(uniform_Composition_texture_fs_lookupTable2, 2); glUniform1i(uniform_Composition_texture_fs_lookupTable3, 3); glUniform1i(uniform_Composition_texture_fs_lookupTable4, 4); glUniform1i(uniform_Composition_texture_fs_lookupTable_font, 5); glUniform1i(uniform_Composition_texture_fs_lookupTable_message, 6); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); // 3-cycle ping-pong localColor step n + 1 (FBO attachment 1) glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS]); // 3-cycle ping-pong CA step n + 1 (FBO attachment 3) glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 2]); // 3-cycle ping-pong track 1 step n + 1 (FBO attachment 4) glActiveTexture(GL_TEXTURE0 + 2); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 3]); // 3-cycle ping-pong track 2 step n + 1 (FBO attachment 5) glActiveTexture(GL_TEXTURE0 + 3); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_localColor_grayCA_tracks[((FrameNo + 1) % PG_NB_MEMORIZED_PASS) * NB_ATTACHMENTS + 4]); // preceding snapshot glActiveTexture(GL_TEXTURE0 + 4); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_snapshot[(std::max( 0 , (FrameNo + 1)) % 2)] ); // drawing memory on odd and even frames for echo and sensors // font texture glActiveTexture(GL_TEXTURE0 + 5); glBindTexture(GL_TEXTURE_RECTANGLE, Font_texture_Rectangle); // font texture glActiveTexture(GL_TEXTURE0 + 6); glBindTexture(GL_TEXTURE_RECTANGLE, pg_screenMessageBitmap_ID); // draw points from the currently bound VAO with current in-use shader glDrawArrays (GL_TRIANGLES, 0, 3 * nbFaces); // ///////////////////////// // read sensor values and send messages glBindFramebuffer(GL_READ_FRAMEBUFFER, FBO_snapshot[(std::max( 0 , FrameNo) % 2)]); // drawing memory on odd and even frames for echo and sensors if( FrameNo % 10 > 0 ) { readSensors(); } glBindFramebuffer(GL_READ_FRAMEBUFFER, 0 ); ////////////////////////////////////////////////// // PASS #3: DISPLAY // unbind output FBO glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); // sets viewport to double window glViewport (0, 0, doubleWindowWidth , windowHeight ); glDrawBuffer(GL_BACK); // output video buffer clean-up glClear (GL_COLOR_BUFFER_BIT); glClearColor( 0.0 , 0.0 , 0.0 , 1.0 ); // printf("rendering\n" ); //////////////////////////////////////// // drawing last quad // activate shaders and sets uniform variable values glUseProgram (shader_Final_programme); glBindVertexArray (quadFinal_vao); glUniformMatrix4fv(uniform_Final_vp_proj, 1, GL_FALSE, doubleProjMatrix); glUniformMatrix4fv(uniform_Final_vp_view, 1, GL_FALSE, viewMatrix); glUniformMatrix4fv(uniform_Final_vp_model, 1, GL_FALSE, modelMatrix); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); // texture unit location glUniform1i(uniform_Final_texture_fs_decal, 0); // previous pass output glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_RECTANGLE, FBO_texID_snapshot[(FrameNo % 2)]); // texture unit location glUniform1i(uniform_Final_texture_fs_lookupTable1, 1); // previous pass output glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_RECTANGLE, LYMlogo_texture_rectangle ); // draw points from the currently bound VAO with current in-use shader glDrawArrays (GL_TRIANGLES, 0, 3 * nbFaces); //} printOglError( 54 ); //////////////////////////////////////// // drawing sensors // activate transparency glEnable( GL_BLEND ); glBlendEquationSeparate(GL_FUNC_ADD, GL_FUNC_ADD); glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ZERO); // activate shaders and sets uniform variable values glUseProgram (shader_Sensor_programme); glBindVertexArray (quadSensor_vao); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_S , GL_CLAMP ); glTexParameterf( GL_TEXTURE_RECTANGLE, GL_TEXTURE_WRAP_T, GL_CLAMP ); // texture unit location glUniform1i(uniform_Sensor_texture_fs_decal, 0); // previous pass output glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_RECTANGLE, Sensor_texture_rectangle ); glUniformMatrix4fv(uniform_Sensor_vp_view, 1, GL_FALSE, viewMatrix); glUniformMatrix4fv(uniform_Sensor_vp_proj, 1, GL_FALSE, doubleProjMatrix); // sensor rendering for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { if( sensor_onOff[indSens] ) { modelMatrixSensor[12] = (sensorPositions[ 3 * indSens ] + 0.5f - singleWindowWidth/2.0f) * scale + singleWindowWidth/2.0f; modelMatrixSensor[13] = (sensorPositions[ 3 * indSens + 1] + 0.5f - windowHeight/2.0f) * scale + windowHeight/2.0f; modelMatrixSensor[14] = sensorPositions[ 3 * indSens + 2]; glUniformMatrix4fv(uniform_Sensor_vp_model, 1, GL_FALSE, modelMatrixSensor); glUniform4f(uniform_Sensor_fs_4fv_onOff_isCurrentSensor_isFollowMouse_transparency , (sensor_onOff[indSens] ? 1.0f : -1.0f) , (indSens == currentSensor ? 1.0f : -1.0f) , (sensorFollowMouse_onOff ? 1.0f : -1.0f) , blendTransp ); // draw points from the currently bound VAO with current in-use shader glDrawArrays (GL_TRIANGLES, 0, 3 * nbFaces); } else { // incremental sensor activation every 10 sec. if( sensor_activation == 5 && CurrentClockTime - sensor_last_activation_time > 10 ) { sensor_last_activation_time = CurrentClockTime; sensor_onOff[indSens] = true; } } } // duplicates the sensors in case of double window if( PG_EnvironmentNode->double_window ) { for( int indSens = 0 ; indSens < PG_NB_SENSORS ; indSens++ ) { if( sensor_onOff[indSens] ) { modelMatrixSensor[12] = (sensorPositions[ 3 * indSens ] + 0.5f - singleWindowWidth/2.0f) * scale + 3 * singleWindowWidth/2.0f; modelMatrixSensor[13] = (sensorPositions[ 3 * indSens + 1] + 0.5f - windowHeight/2.0f) * scale + windowHeight/2.0f; modelMatrixSensor[14] = sensorPositions[ 3 * indSens + 2]; glUniformMatrix4fv(uniform_Sensor_vp_model, 1, GL_FALSE, modelMatrixSensor); glUniform4f(uniform_Sensor_fs_4fv_onOff_isCurrentSensor_isFollowMouse_transparency , (sensor_onOff[indSens] ? 1.0f : -1.0f) , (indSens == currentSensor ? 1.0f : -1.0f) , (sensorFollowMouse_onOff ? 1.0f : -1.0f) , blendTransp ); // draw points from the currently bound VAO with current in-use shader glDrawArrays (GL_TRIANGLES, 0, 3 * nbFaces); } } } printOglError( 595 ); glDisable( GL_BLEND ); } // // flushes OpenGL commands // glFlush(); }
yukao/Porphyrograph
LYM-sources/SourcesBerfore18/Porphyrograph-geneMuse-src/pg-draw.cpp
C++
gpl-3.0
147,112
import { Component, OnInit, Inject } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material'; @Component({ selector: 'app-remove-quantity', templateUrl: './remove-quantity.component.html', styleUrls: ['./remove-quantity.component.css'] }) export class RemoveQuantityComponent implements OnInit { constructor( @Inject(MAT_DIALOG_DATA) public selection: any, private dialogRef: MatDialogRef<RemoveQuantityComponent> ) {} ngOnInit() {} cancel() { this.dialogRef.close(); } removeFromOrder() { this.dialogRef.close('remove'); } }
sumnercreations/ceilings
src/app/quantity/remove-quantity/remove-quantity.component.ts
TypeScript
gpl-3.0
598
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QString> #include <QtTest> #include <QtAndroidExtras/QAndroidJniObject> #include <QtAndroidExtras/QAndroidJniEnvironment> static const char testClassName[] = "org/qtproject/qt5/android/testdatapackage/QtAndroidJniObjectTestClass"; static const jbyte A_BYTE_VALUE = 127; static const jshort A_SHORT_VALUE = 32767; static const jint A_INT_VALUE = 060701; static const jlong A_LONG_VALUE = 060701; static const jfloat A_FLOAT_VALUE = 1.0; static const jdouble A_DOUBLE_VALUE = 1.0; static const jboolean A_BOOLEAN_VALUE = true; static const jchar A_CHAR_VALUE = 'Q'; static QString A_STRING_OBJECT() { return QStringLiteral("TEST_DATA_STRING"); } class tst_QAndroidJniObject : public QObject { Q_OBJECT public: tst_QAndroidJniObject(); private slots: void initTestCase(); void ctor(); void callMethodTest(); void callObjectMethodTest(); void stringConvertionTest(); void compareOperatorTests(); void callStaticObjectMethodClassName(); void callStaticObjectMethod(); void callStaticBooleanMethodClassName(); void callStaticBooleanMethod(); void callStaticCharMethodClassName(); void callStaticCharMethod(); void callStaticIntMethodClassName(); void callStaticIntMethod(); void callStaticByteMethodClassName(); void callStaticByteMethod(); void callStaticDoubleMethodClassName(); void callStaticDoubleMethod(); void callStaticFloatMethodClassName(); void callStaticFloatMethod(); void callStaticLongMethodClassName(); void callStaticLongMethod(); void callStaticShortMethodClassName(); void callStaticShortMethod(); void getStaticObjectFieldClassName(); void getStaticObjectField(); void getStaticIntFieldClassName(); void getStaticIntField(); void getStaticByteFieldClassName(); void getStaticByteField(); void getStaticLongFieldClassName(); void getStaticLongField(); void getStaticDoubleFieldClassName(); void getStaticDoubleField(); void getStaticFloatFieldClassName(); void getStaticFloatField(); void getStaticShortFieldClassName(); void getStaticShortField(); void getStaticCharFieldClassName(); void getStaticCharField(); void getBooleanField(); void getIntField(); void templateApiCheck(); void isClassAvailable(); void fromLocalRef(); void cleanupTestCase(); }; tst_QAndroidJniObject::tst_QAndroidJniObject() { } void tst_QAndroidJniObject::initTestCase() { } void tst_QAndroidJniObject::cleanupTestCase() { } void tst_QAndroidJniObject::ctor() { { QAndroidJniObject object; QVERIFY(!object.isValid()); } { QAndroidJniObject object("java/lang/String"); QVERIFY(object.isValid()); } { QAndroidJniObject string = QAndroidJniObject::fromString(QLatin1String("Hello, Java")); QAndroidJniObject object("java/lang/String", "(Ljava/lang/String;)V", string.object<jstring>()); QVERIFY(object.isValid()); QCOMPARE(string.toString(), object.toString()); } { QAndroidJniEnvironment env; jclass javaStringClass = env->FindClass("java/lang/String"); QAndroidJniObject string(javaStringClass); QVERIFY(string.isValid()); } { QAndroidJniEnvironment env; const QString qString = QLatin1String("Hello, Java"); jclass javaStringClass = env->FindClass("java/lang/String"); QAndroidJniObject string = QAndroidJniObject::fromString(qString); QAndroidJniObject stringCpy(javaStringClass, "(Ljava/lang/String;)V", string.object<jstring>()); QVERIFY(stringCpy.isValid()); QCOMPARE(qString, stringCpy.toString()); } } void tst_QAndroidJniObject::callMethodTest() { { QAndroidJniObject jString1 = QAndroidJniObject::fromString(QLatin1String("Hello, Java")); QAndroidJniObject jString2 = QAndroidJniObject::fromString(QLatin1String("hELLO, jAVA")); QVERIFY(jString1 != jString2); const jboolean isEmpty = jString1.callMethod<jboolean>("isEmpty"); QVERIFY(!isEmpty); const jint ret = jString1.callMethod<jint>("compareToIgnoreCase", "(Ljava/lang/String;)I", jString2.object<jstring>()); QVERIFY(0 == ret); } { jlong jLong = 100; QAndroidJniObject longObject("java/lang/Long", "(J)V", jLong); jlong ret = longObject.callMethod<jlong>("longValue"); QCOMPARE(ret, jLong); } } void tst_QAndroidJniObject::callObjectMethodTest() { const QString qString = QLatin1String("Hello, Java"); QAndroidJniObject jString = QAndroidJniObject::fromString(qString); const QString qStringRet = jString.callObjectMethod<jstring>("toUpperCase").toString(); QCOMPARE(qString.toUpper(), qStringRet); QAndroidJniObject subString = jString.callObjectMethod("substring", "(II)Ljava/lang/String;", 0, 4); QCOMPARE(subString.toString(), qString.mid(0, 4)); } void tst_QAndroidJniObject::stringConvertionTest() { const QString qString(QLatin1String("Hello, Java")); QAndroidJniObject jString = QAndroidJniObject::fromString(qString); QVERIFY(jString.isValid()); QString qStringRet = jString.toString(); QCOMPARE(qString, qStringRet); } void tst_QAndroidJniObject::compareOperatorTests() { QString str("hello!"); QAndroidJniObject stringObject = QAndroidJniObject::fromString(str); jobject obj = stringObject.object(); jobject jobj = stringObject.object<jobject>(); jstring jsobj = stringObject.object<jstring>(); QVERIFY(obj == stringObject); QVERIFY(jobj == stringObject); QVERIFY(stringObject == jobj); QVERIFY(jsobj == stringObject); QVERIFY(stringObject == jsobj); QAndroidJniObject stringObject3 = stringObject.object<jstring>(); QVERIFY(stringObject3 == stringObject); QAndroidJniObject stringObject2 = QAndroidJniObject::fromString(str); QVERIFY(stringObject != stringObject2); jstring jstrobj = 0; QAndroidJniObject invalidStringObject; QVERIFY(invalidStringObject == jstrobj); QVERIFY(jstrobj != stringObject); QVERIFY(stringObject != jstrobj); QVERIFY(!invalidStringObject.isValid()); } void tst_QAndroidJniObject::callStaticObjectMethodClassName() { QAndroidJniObject formatString = QAndroidJniObject::fromString(QLatin1String("test format")); QVERIFY(formatString.isValid()); QVERIFY(QAndroidJniObject::isClassAvailable("java/lang/String")); QAndroidJniObject returnValue = QAndroidJniObject::callStaticObjectMethod("java/lang/String", "format", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", formatString.object<jstring>(), jobjectArray(0)); QVERIFY(returnValue.isValid()); QString returnedString = returnValue.toString(); QCOMPARE(returnedString, QString::fromLatin1("test format")); } void tst_QAndroidJniObject::callStaticObjectMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/String"); QVERIFY(cls != 0); QAndroidJniObject formatString = QAndroidJniObject::fromString(QLatin1String("test format")); QVERIFY(formatString.isValid()); QAndroidJniObject returnValue = QAndroidJniObject::callStaticObjectMethod(cls, "format", "(Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String;", formatString.object<jstring>(), jobjectArray(0)); QVERIFY(returnValue.isValid()); QString returnedString = returnValue.toString(); QCOMPARE(returnedString, QString::fromLatin1("test format")); } void tst_QAndroidJniObject::callStaticBooleanMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Boolean"); QVERIFY(cls != 0); { QAndroidJniObject parameter = QAndroidJniObject::fromString("true"); QVERIFY(parameter.isValid()); jboolean b = QAndroidJniObject::callStaticMethod<jboolean>(cls, "parseBoolean", "(Ljava/lang/String;)Z", parameter.object<jstring>()); QVERIFY(b); } { QAndroidJniObject parameter = QAndroidJniObject::fromString("false"); QVERIFY(parameter.isValid()); jboolean b = QAndroidJniObject::callStaticMethod<jboolean>(cls, "parseBoolean", "(Ljava/lang/String;)Z", parameter.object<jstring>()); QVERIFY(!b); } } void tst_QAndroidJniObject::callStaticBooleanMethodClassName() { { QAndroidJniObject parameter = QAndroidJniObject::fromString("true"); QVERIFY(parameter.isValid()); jboolean b = QAndroidJniObject::callStaticMethod<jboolean>("java/lang/Boolean", "parseBoolean", "(Ljava/lang/String;)Z", parameter.object<jstring>()); QVERIFY(b); } { QAndroidJniObject parameter = QAndroidJniObject::fromString("false"); QVERIFY(parameter.isValid()); jboolean b = QAndroidJniObject::callStaticMethod<jboolean>("java/lang/Boolean", "parseBoolean", "(Ljava/lang/String;)Z", parameter.object<jstring>()); QVERIFY(!b); } } void tst_QAndroidJniObject::callStaticByteMethodClassName() { QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jbyte returnValue = QAndroidJniObject::callStaticMethod<jbyte>("java/lang/Byte", "parseByte", "(Ljava/lang/String;)B", parameter.object<jstring>()); QCOMPARE(returnValue, jbyte(number.toInt())); } void tst_QAndroidJniObject::callStaticByteMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Byte"); QVERIFY(cls != 0); QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jbyte returnValue = QAndroidJniObject::callStaticMethod<jbyte>(cls, "parseByte", "(Ljava/lang/String;)B", parameter.object<jstring>()); QCOMPARE(returnValue, jbyte(number.toInt())); } void tst_QAndroidJniObject::callStaticIntMethodClassName() { QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jint returnValue = QAndroidJniObject::callStaticMethod<jint>("java/lang/Integer", "parseInt", "(Ljava/lang/String;)I", parameter.object<jstring>()); QCOMPARE(returnValue, number.toInt()); } void tst_QAndroidJniObject::callStaticIntMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Integer"); QVERIFY(cls != 0); QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jint returnValue = QAndroidJniObject::callStaticMethod<jint>(cls, "parseInt", "(Ljava/lang/String;)I", parameter.object<jstring>()); QCOMPARE(returnValue, number.toInt()); } void tst_QAndroidJniObject::callStaticCharMethodClassName() { jchar returnValue = QAndroidJniObject::callStaticMethod<jchar>("java/lang/Character", "toUpperCase", "(C)C", jchar('a')); QCOMPARE(returnValue, jchar('A')); } void tst_QAndroidJniObject::callStaticCharMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Character"); QVERIFY(cls != 0); jchar returnValue = QAndroidJniObject::callStaticMethod<jchar>(cls, "toUpperCase", "(C)C", jchar('a')); QCOMPARE(returnValue, jchar('A')); } void tst_QAndroidJniObject::callStaticDoubleMethodClassName () { QString number = QString::number(123.45); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jdouble returnValue = QAndroidJniObject::callStaticMethod<jdouble>("java/lang/Double", "parseDouble", "(Ljava/lang/String;)D", parameter.object<jstring>()); QCOMPARE(returnValue, number.toDouble()); } void tst_QAndroidJniObject::callStaticDoubleMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Double"); QVERIFY(cls != 0); QString number = QString::number(123.45); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jdouble returnValue = QAndroidJniObject::callStaticMethod<jdouble>(cls, "parseDouble", "(Ljava/lang/String;)D", parameter.object<jstring>()); QCOMPARE(returnValue, number.toDouble()); } void tst_QAndroidJniObject::callStaticFloatMethodClassName() { QString number = QString::number(123.45); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jfloat returnValue = QAndroidJniObject::callStaticMethod<jfloat>("java/lang/Float", "parseFloat", "(Ljava/lang/String;)F", parameter.object<jstring>()); QCOMPARE(returnValue, number.toFloat()); } void tst_QAndroidJniObject::callStaticFloatMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Float"); QVERIFY(cls != 0); QString number = QString::number(123.45); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jfloat returnValue = QAndroidJniObject::callStaticMethod<jfloat>(cls, "parseFloat", "(Ljava/lang/String;)F", parameter.object<jstring>()); QCOMPARE(returnValue, number.toFloat()); } void tst_QAndroidJniObject::callStaticShortMethodClassName() { QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jshort returnValue = QAndroidJniObject::callStaticMethod<jshort>("java/lang/Short", "parseShort", "(Ljava/lang/String;)S", parameter.object<jstring>()); QCOMPARE(returnValue, number.toShort()); } void tst_QAndroidJniObject::callStaticShortMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Short"); QVERIFY(cls != 0); QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jshort returnValue = QAndroidJniObject::callStaticMethod<jshort>(cls, "parseShort", "(Ljava/lang/String;)S", parameter.object<jstring>()); QCOMPARE(returnValue, number.toShort()); } void tst_QAndroidJniObject::callStaticLongMethodClassName() { QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jlong returnValue = QAndroidJniObject::callStaticMethod<jlong>("java/lang/Long", "parseLong", "(Ljava/lang/String;)J", parameter.object<jstring>()); QCOMPARE(returnValue, jlong(number.toLong())); } void tst_QAndroidJniObject::callStaticLongMethod() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Long"); QVERIFY(cls != 0); QString number = QString::number(123); QAndroidJniObject parameter = QAndroidJniObject::fromString(number); jlong returnValue = QAndroidJniObject::callStaticMethod<jlong>(cls, "parseLong", "(Ljava/lang/String;)J", parameter.object<jstring>()); QCOMPARE(returnValue, jlong(number.toLong())); } void tst_QAndroidJniObject::getStaticObjectFieldClassName() { { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField<jobject>("java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(!booleanValue); } { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField<jobject>("java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(booleanValue); } { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField("java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(!booleanValue); } } void tst_QAndroidJniObject::getStaticObjectField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Boolean"); QVERIFY(cls != 0); { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField<jobject>(cls, "FALSE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(!booleanValue); } { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField<jobject>(cls, "TRUE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(booleanValue); } { QAndroidJniObject boolObject = QAndroidJniObject::getStaticObjectField(cls, "FALSE", "Ljava/lang/Boolean;"); QVERIFY(boolObject.isValid()); jboolean booleanValue = boolObject.callMethod<jboolean>("booleanValue"); QVERIFY(!booleanValue); } } void tst_QAndroidJniObject::getStaticIntFieldClassName() { jint i = QAndroidJniObject::getStaticField<jint>("java/lang/Double", "SIZE"); QCOMPARE(i, 64); } void tst_QAndroidJniObject::getStaticIntField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Double"); QVERIFY(cls != 0); jint i = QAndroidJniObject::getStaticField<jint>(cls, "SIZE"); QCOMPARE(i, 64); } void tst_QAndroidJniObject::getStaticByteFieldClassName() { jbyte i = QAndroidJniObject::getStaticField<jbyte>("java/lang/Byte", "MAX_VALUE"); QCOMPARE(i, jbyte(127)); } void tst_QAndroidJniObject::getStaticByteField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Byte"); QVERIFY(cls != 0); jbyte i = QAndroidJniObject::getStaticField<jbyte>(cls, "MAX_VALUE"); QCOMPARE(i, jbyte(127)); } void tst_QAndroidJniObject::getStaticLongFieldClassName() { jlong i = QAndroidJniObject::getStaticField<jlong>("java/lang/Long", "MAX_VALUE"); QCOMPARE(i, jlong(9223372036854775807L)); } void tst_QAndroidJniObject::getStaticLongField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Long"); QVERIFY(cls != 0); jlong i = QAndroidJniObject::getStaticField<jlong>(cls, "MAX_VALUE"); QCOMPARE(i, jlong(9223372036854775807L)); } void tst_QAndroidJniObject::getStaticDoubleFieldClassName() { jdouble i = QAndroidJniObject::getStaticField<jdouble>("java/lang/Double", "NaN"); jlong *k = reinterpret_cast<jlong*>(&i); QCOMPARE(*k, jlong(0x7ff8000000000000L)); } void tst_QAndroidJniObject::getStaticDoubleField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Double"); QVERIFY(cls != 0); jdouble i = QAndroidJniObject::getStaticField<jdouble>(cls, "NaN"); jlong *k = reinterpret_cast<jlong*>(&i); QCOMPARE(*k, jlong(0x7ff8000000000000L)); } void tst_QAndroidJniObject::getStaticFloatFieldClassName() { jfloat i = QAndroidJniObject::getStaticField<jfloat>("java/lang/Float", "NaN"); unsigned *k = reinterpret_cast<unsigned*>(&i); QCOMPARE(*k, unsigned(0x7fc00000)); } void tst_QAndroidJniObject::getStaticFloatField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Float"); QVERIFY(cls != 0); jfloat i = QAndroidJniObject::getStaticField<jfloat>(cls, "NaN"); unsigned *k = reinterpret_cast<unsigned*>(&i); QCOMPARE(*k, unsigned(0x7fc00000)); } void tst_QAndroidJniObject::getStaticShortFieldClassName() { jshort i = QAndroidJniObject::getStaticField<jshort>("java/lang/Short", "MAX_VALUE"); QCOMPARE(i, jshort(32767)); } void tst_QAndroidJniObject::getStaticShortField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Short"); QVERIFY(cls != 0); jshort i = QAndroidJniObject::getStaticField<jshort>(cls, "MAX_VALUE"); QCOMPARE(i, jshort(32767)); } void tst_QAndroidJniObject::getStaticCharFieldClassName() { jchar i = QAndroidJniObject::getStaticField<jchar>("java/lang/Character", "MAX_VALUE"); QCOMPARE(i, jchar(0xffff)); } void tst_QAndroidJniObject::getStaticCharField() { QAndroidJniEnvironment env; jclass cls = env->FindClass("java/lang/Character"); QVERIFY(cls != 0); jchar i = QAndroidJniObject::getStaticField<jchar>(cls, "MAX_VALUE"); QCOMPARE(i, jchar(0xffff)); } void tst_QAndroidJniObject::getBooleanField() { QAndroidJniObject obj("org/qtproject/qt5/android/QtActivityDelegate"); QVERIFY(obj.isValid()); QVERIFY(!obj.getField<jboolean>("m_fullScreen")); } void tst_QAndroidJniObject::getIntField() { QAndroidJniObject obj("org/qtproject/qt5/android/QtActivityDelegate"); QVERIFY(obj.isValid()); jint res = obj.getField<jint>("m_currentRotation"); QCOMPARE(res, -1); } void tst_QAndroidJniObject::templateApiCheck() { QAndroidJniObject testClass(testClassName); QVERIFY(testClass.isValid()); // void --------------------------------------------------------------------------------------- QAndroidJniObject::callStaticMethod<void>(testClassName, "staticVoidMethod"); QAndroidJniObject::callStaticMethod<void>(testClassName, "staticVoidMethodWithArgs", "(IZC)V", 1, true, 'c'); testClass.callMethod<void>("voidMethod"); testClass.callMethod<void>("voidMethodWithArgs", "(IZC)V", 1, true, 'c'); // jboolean ----------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jboolean>(testClassName, "staticBooleanMethod")); QVERIFY(QAndroidJniObject::callStaticMethod<jboolean>(testClassName, "staticBooleanMethodWithArgs", "(ZZZ)Z", true, true, true)); QVERIFY(testClass.callMethod<jboolean>("booleanMethod")); QVERIFY(testClass.callMethod<jboolean>("booleanMethodWithArgs", "(ZZZ)Z", true, true, true)); // jbyte -------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jbyte>(testClassName, "staticByteMethod") == A_BYTE_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jbyte>(testClassName, "staticByteMethodWithArgs", "(BBB)B", 1, 1, 1) == A_BYTE_VALUE); QVERIFY(testClass.callMethod<jbyte>("byteMethod") == A_BYTE_VALUE); QVERIFY(testClass.callMethod<jbyte>("byteMethodWithArgs", "(BBB)B", 1, 1, 1) == A_BYTE_VALUE); // jchar -------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jchar>(testClassName, "staticCharMethod") == A_CHAR_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jchar>(testClassName, "staticCharMethodWithArgs", "(CCC)C", jchar(1), jchar(1), jchar(1)) == A_CHAR_VALUE); QVERIFY(testClass.callMethod<jchar>("charMethod") == A_CHAR_VALUE); QVERIFY(testClass.callMethod<jchar>("charMethodWithArgs", "(CCC)C", jchar(1), jchar(1), jchar(1)) == A_CHAR_VALUE); // jshort ------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jshort>(testClassName, "staticShortMethod") == A_SHORT_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jshort>(testClassName, "staticShortMethodWithArgs", "(SSS)S", jshort(1), jshort(1), jshort(1)) == A_SHORT_VALUE); QVERIFY(testClass.callMethod<jshort>("shortMethod") == A_SHORT_VALUE); QVERIFY(testClass.callMethod<jshort>("shortMethodWithArgs", "(SSS)S", jshort(1), jshort(1), jshort(1)) == A_SHORT_VALUE); // jint --------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jint>(testClassName, "staticIntMethod") == A_INT_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jint>(testClassName, "staticIntMethodWithArgs", "(III)I", jint(1), jint(1), jint(1)) == A_INT_VALUE); QVERIFY(testClass.callMethod<jint>("intMethod") == A_INT_VALUE); QVERIFY(testClass.callMethod<jint>("intMethodWithArgs", "(III)I", jint(1), jint(1), jint(1)) == A_INT_VALUE); // jlong -------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jlong>(testClassName, "staticLongMethod") == A_LONG_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jlong>(testClassName, "staticLongMethodWithArgs", "(JJJ)J", jlong(1), jlong(1), jlong(1)) == A_LONG_VALUE); QVERIFY(testClass.callMethod<jlong>("longMethod") == A_LONG_VALUE); QVERIFY(testClass.callMethod<jlong>("longMethodWithArgs", "(JJJ)J", jlong(1), jlong(1), jlong(1)) == A_LONG_VALUE); // jfloat ------------------------------------------------------------------------------------- QVERIFY(QAndroidJniObject::callStaticMethod<jfloat>(testClassName, "staticFloatMethod") == A_FLOAT_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jfloat>(testClassName, "staticFloatMethodWithArgs", "(FFF)F", jfloat(1.1), jfloat(1.1), jfloat(1.1)) == A_FLOAT_VALUE); QVERIFY(testClass.callMethod<jfloat>("floatMethod") == A_FLOAT_VALUE); QVERIFY(testClass.callMethod<jfloat>("floatMethodWithArgs", "(FFF)F", jfloat(1.1), jfloat(1.1), jfloat(1.1)) == A_FLOAT_VALUE); // jdouble ------------------------------------------------------------------------------------ QVERIFY(QAndroidJniObject::callStaticMethod<jdouble>(testClassName, "staticDoubleMethod") == A_DOUBLE_VALUE); QVERIFY(QAndroidJniObject::callStaticMethod<jdouble>(testClassName, "staticDoubleMethodWithArgs", "(DDD)D", jdouble(1.1), jdouble(1.1), jdouble(1.1)) == A_DOUBLE_VALUE); QVERIFY(testClass.callMethod<jdouble>("doubleMethod") == A_DOUBLE_VALUE); QVERIFY(testClass.callMethod<jdouble>("doubleMethodWithArgs", "(DDD)D", jdouble(1.1), jdouble(1.1), jdouble(1.1)) == A_DOUBLE_VALUE); // jobject ------------------------------------------------------------------------------------ { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jobject>(testClassName, "staticObjectMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jobject>("objectMethod"); QVERIFY(res.isValid()); } // jclass ------------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jclass>(testClassName, "staticClassMethod"); QVERIFY(res.isValid()); QAndroidJniEnvironment env; QVERIFY(env->IsInstanceOf(testClass.object(), res.object<jclass>())); } { QAndroidJniObject res = testClass.callObjectMethod<jclass>("classMethod"); QVERIFY(res.isValid()); QAndroidJniEnvironment env; QVERIFY(env->IsInstanceOf(testClass.object(), res.object<jclass>())); } // jstring ------------------------------------------------------------------------------------ { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jstring>(testClassName, "staticStringMethod"); QVERIFY(res.isValid()); QVERIFY(res.toString() == A_STRING_OBJECT()); } { QAndroidJniObject res = testClass.callObjectMethod<jstring>("stringMethod"); QVERIFY(res.isValid()); QVERIFY(res.toString() == A_STRING_OBJECT()); } // jthrowable --------------------------------------------------------------------------------- { // The Throwable object the same message (see: "getMessage()") as A_STRING_OBJECT QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jthrowable>(testClassName, "staticThrowableMethod"); QVERIFY(res.isValid()); QVERIFY(res.callObjectMethod<jstring>("getMessage").toString() == A_STRING_OBJECT()); } { QAndroidJniObject res = testClass.callObjectMethod<jthrowable>("throwableMethod"); QVERIFY(res.isValid()); QVERIFY(res.callObjectMethod<jstring>("getMessage").toString() == A_STRING_OBJECT()); } // jobjectArray ------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jobjectArray>(testClassName, "staticObjectArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jobjectArray>("objectArrayMethod"); QVERIFY(res.isValid()); } // jbooleanArray ------------------------------------------------------------------------------ { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jbooleanArray>(testClassName, "staticBooleanArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jbooleanArray>("booleanArrayMethod"); QVERIFY(res.isValid()); } // jbyteArray --------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jbyteArray>(testClassName, "staticByteArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jbyteArray>("byteArrayMethod"); QVERIFY(res.isValid()); } // jcharArray --------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jcharArray>(testClassName, "staticCharArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jcharArray>("charArrayMethod"); QVERIFY(res.isValid()); } // jshortArray -------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jshortArray>(testClassName, "staticShortArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jshortArray>("shortArrayMethod"); QVERIFY(res.isValid()); } // jintArray ---------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jintArray>(testClassName, "staticIntArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jintArray>("intArrayMethod"); QVERIFY(res.isValid()); } // jlongArray --------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jlongArray>(testClassName, "staticLongArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jlongArray>("longArrayMethod"); QVERIFY(res.isValid()); } // jfloatArray -------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jfloatArray>(testClassName, "staticFloatArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jfloatArray>("floatArrayMethod"); QVERIFY(res.isValid()); } // jdoubleArray ------------------------------------------------------------------------------- { QAndroidJniObject res = QAndroidJniObject::callStaticObjectMethod<jdoubleArray>(testClassName, "staticDoubleArrayMethod"); QVERIFY(res.isValid()); } { QAndroidJniObject res = testClass.callObjectMethod<jdoubleArray>("doubleArrayMethod"); QVERIFY(res.isValid()); } } void tst_QAndroidJniObject::isClassAvailable() { QVERIFY(QAndroidJniObject::isClassAvailable("java/lang/String")); QVERIFY(!QAndroidJniObject::isClassAvailable("class/not/Available")); QVERIFY(QAndroidJniObject::isClassAvailable("org/qtproject/qt5/android/QtActivityDelegate")); } void tst_QAndroidJniObject::fromLocalRef() { const int limit = 512 + 1; QAndroidJniEnvironment env; for (int i = 0; i != limit; ++i) QAndroidJniObject o = QAndroidJniObject::fromLocalRef(env->FindClass("java/lang/String")); } QTEST_APPLESS_MAIN(tst_QAndroidJniObject) #include "tst_qandroidjniobject.moc"
geminy/aidear
oss/qt/qt-everywhere-opensource-src-5.9.0/qtandroidextras/tests/auto/qandroidjniobject/tst_qandroidjniobject.cpp
C++
gpl-3.0
43,144
// *********************************************************************************************** // * * // * createMenu.cpp - creates application menus * // * * // * Dr. Rainer Sieger - 2008-05-18 * // * * // *********************************************************************************************** #include "Application.h" // ********************************************************************************************** // ********************************************************************************************** // ********************************************************************************************** /*! @brief Erstellen der Menue-Aktionen. */ void MainWindow::createActions() { // File menu newWindowAction = new QAction(tr("&New window"), this); newWindowAction->setShortcut(tr("Ctrl+N")); connect(newWindowAction, SIGNAL(triggered()), this, SLOT(newWindow())); openFileAction = new QAction(tr("&Open..."), this); openFileAction->setShortcut(tr("Ctrl+O")); connect(openFileAction, SIGNAL(triggered()), this, SLOT(chooseFiles())); openFolderAction = new QAction(tr("Select &Folder..."), this); openFolderAction->setShortcut(tr("Ctrl+F")); connect(openFolderAction, SIGNAL(triggered()), this, SLOT(chooseFolder())); saveAction = new QAction(tr("&Save"), this); saveAction->setShortcut(tr("Ctrl+S")); connect(saveAction, SIGNAL(triggered()), this, SLOT(saveFile())); saveAsAction = new QAction(tr("Save &As..."), this); connect(saveAsAction, SIGNAL(triggered()), this, SLOT(saveFileAs())); hideWindowAction = new QAction(tr("&Close window"), this); hideWindowAction->setShortcut(tr("Ctrl+W")); connect(hideWindowAction, SIGNAL(triggered()), this, SLOT(hideWindow())); exitAction = new QAction(tr("&Quit"), this); exitAction->setShortcut(tr("Ctrl+Q")); connect(exitAction, SIGNAL(triggered()), this, SLOT(exitApplication())); //AMD createAmdXmlAction = new QAction(tr("Dataset list -> XML files for AMD registration"), this); connect(createAmdXmlAction, SIGNAL(triggered()), this, SLOT(doCreateAmdXml())); // TIB createDoiXmlAction = new QAction(tr("Reference list -> XML files for DOI registration"), this); connect(createDoiXmlAction, SIGNAL(triggered()), this, SLOT(doCreateDoiXml())); createSingleDoiXmlDialogAction = new QAction(tr("Create XML file for DOI registration..."), this); connect(createSingleDoiXmlDialogAction, SIGNAL(triggered()), this, SLOT(doCreateSingleDoiXmlDialog())); /* // ePIC createEPicXmlAction = new QAction(tr("Reference list -> XML file for ePIC batch upload"), this); connect(createEPicXmlAction, SIGNAL(triggered()), this, SLOT(doCreateEPicXml())); createSimpleEPicXmlAction = new QAction(tr("Create simple XML file for ePIC batch upload..."), this); connect(createSimpleEPicXmlAction, SIGNAL(triggered()), this, SLOT(doCreateSimpleEPicXml())); */ // Templates createAmdXmlTemplateAction = new QAction(tr("Create dataset list as template"), this); connect(createAmdXmlTemplateAction, SIGNAL(triggered()), this, SLOT(doCreateAmdXmlTemplate())); createDoiXmlTemplateAction = new QAction(tr("Create reference list as template"), this); connect(createDoiXmlTemplateAction, SIGNAL(triggered()), this, SLOT(doCreateDoiXmlTemplate())); // Help menu aboutAction = new QAction(tr("&About ") + getApplicationName( true ), this); connect(aboutAction, SIGNAL(triggered()), this, SLOT(about())); aboutQtAction = new QAction(tr("About &Qt"), this); connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt())); showHelpAction = new QAction(getApplicationName( true ) + tr(" &Help"), this); showHelpAction->setShortcut(tr("F1")); connect(showHelpAction, SIGNAL(triggered()), this, SLOT(displayHelp())); #if defined(Q_OS_WIN) newWindowAction->setStatusTip(tr("Create a new file")); openFileAction->setStatusTip(tr("Choose an existing file")); openFolderAction->setStatusTip(tr("Choose an existing folder")); saveAction->setStatusTip(tr("Save the document to disk")); saveAsAction->setStatusTip(tr("Save the document under a new name")); exitAction->setStatusTip(tr("Exit the application")); createSingleDoiXmlDialogAction->setStatusTip(tr("create a single DOI XML file with a dialog")); createDoiXmlAction->setStatusTip(tr("create many DOI XML files with a list of references")); createDoiXmlTemplateAction->setStatusTip(tr("create a reference list as template")); aboutAction->setStatusTip(tr("Show the application's About box")); aboutQtAction->setStatusTip(tr("Show the Qt library's About box")); showHelpAction->setStatusTip(tr("Show the application's help")); #endif } // ********************************************************************************************** // ********************************************************************************************** // ********************************************************************************************** /*! @brief Verbindet Menues mit Aktionen. */ void MainWindow::createMenus() { fileMenu = menuBar()->addMenu( tr( "&File" ) ); fileMenu->addAction( openFileAction ); fileMenu->addAction( openFolderAction ); fileMenu->addSeparator(); #if defined(Q_OS_MAC) fileMenu->addAction( newWindowAction ); newWindowAction->setEnabled( false ); fileMenu->addAction( hideWindowAction ); #endif #if defined(Q_OS_WIN) fileMenu->addAction( hideWindowAction ); #endif fileMenu->addSeparator(); fileMenu->addAction( exitAction ); // ********************************************************************************************** toolMenu = menuBar()->addMenu( tr( "Tools" ) ); toolMenu->addAction( createAmdXmlAction ); toolMenu->addAction( createDoiXmlAction ); toolMenu->addSeparator(); toolMenu->addAction( createAmdXmlTemplateAction ); toolMenu->addAction( createDoiXmlTemplateAction ); // toolMenu->addAction( createSingleDoiXmlDialogAction ); // toolMenu->addAction( createSimpleEPicXmlAction ); // toolMenu->addAction( createEPicXmlAction ); // toolMenu->addSeparator(); // ********************************************************************************************** helpMenu = menuBar()->addMenu( tr( "&Help" ) ); helpMenu->addAction( aboutAction ); helpMenu->addAction( aboutQtAction ); helpMenu->addSeparator(); helpMenu->addAction( showHelpAction ); } // ********************************************************************************************** // ********************************************************************************************** // ********************************************************************************************** void MainWindow::enableMenuItems( const QStringList &sl_FilenameList ) { bool b_containsBinaryFile = containsBinaryFile( sl_FilenameList ); // ********************************************************************************************** QList<QAction*> toolMenuActions = toolMenu->actions(); if ( b_containsBinaryFile == false ) { for ( int i=0; i<toolMenuActions.count(); ++i ) toolMenuActions.at( i )->setEnabled( true ); } else { for ( int i=0; i<toolMenuActions.count(); ++i ) toolMenuActions.at( i )->setEnabled( false ); } }
rsieger/PanXML
trunk/Sources/ApplicationCreateMenu.cpp
C++
gpl-3.0
7,803
package l2s.gameserver.network.l2.s2c; import l2s.gameserver.model.Creature; /** * 0000: 3f 2a 89 00 4c 01 00 00 00 0a 15 00 00 66 fe 00 ?*..L........f.. * 0010: 00 7c f1 ff ff .|... * * format dd ddd */ public class ChangeWaitTypePacket extends L2GameServerPacket { private int _objectId; private int _moveType; private int _x, _y, _z; public static final int WT_SITTING = 0; public static final int WT_STANDING = 1; public static final int WT_START_FAKEDEATH = 2; public static final int WT_STOP_FAKEDEATH = 3; public ChangeWaitTypePacket(Creature cha, int newMoveType) { _objectId = cha.getObjectId(); _moveType = newMoveType; _x = cha.getX(); _y = cha.getY(); _z = cha.getZ(); } @Override protected final void writeImpl() { writeD(_objectId); writeD(_moveType); writeD(_x); writeD(_y); writeD(_z); } }
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/network/l2/s2c/ChangeWaitTypePacket.java
Java
gpl-3.0
890
#region Copyright & License Information /* * Copyright 2007-2014 The OpenRA Developers (see AUTHORS) * This file is part of OpenRA, which is free software. It is made * available to you under the terms of the GNU General Public License * as published by the Free Software Foundation. For more information, * see COPYING. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Linq; using OpenRA.Mods.Common; using OpenRA.Mods.RA.Activities; using OpenRA.Mods.RA.Traits; using OpenRA.Mods.RA.Buildings; using OpenRA.Mods.RA.Move; using OpenRA.Mods.Common.Power; using OpenRA.Primitives; using OpenRA.Support; using OpenRA.Traits; namespace OpenRA.Mods.RA.AI { public sealed class HackyAIInfo : IBotInfo, ITraitInfo { [Desc("Ingame name this bot uses.")] public readonly string Name = "Unnamed Bot"; [Desc("Minimum number of units AI must have before attacking.")] public readonly int SquadSize = 8; [Desc("Production queues AI uses for buildings.")] public readonly string[] BuildingQueues = { "Building" }; [Desc("Production queues AI uses for defenses.")] public readonly string[] DefenseQueues = { "Defense" }; [Desc("Delay (in ticks) between giving out orders to units.")] public readonly int AssignRolesInterval = 20; [Desc("Delay (in ticks) between attempting rush attacks.")] public readonly int RushInterval = 600; [Desc("Delay (in ticks) between updating squads.")] public readonly int AttackForceInterval = 30; [Desc("How long to wait (in ticks) between structure production checks when there is no active production.")] public readonly int StructureProductionInactiveDelay = 125; [Desc("How long to wait (in ticks) between structure production checks ticks when actively building things.")] public readonly int StructureProductionActiveDelay = 10; [Desc("Minimum range at which to build defensive structures near a combat hotspot.")] public readonly int MinimumDefenseRadius = 5; [Desc("Maximum range at which to build defensive structures near a combat hotspot.")] public readonly int MaximumDefenseRadius = 20; [Desc("Try to build another production building if there is too much cash.")] public readonly int NewProductionCashThreshold = 5000; [Desc("Only produce units as long as there are less than this amount of units idling inside the base.")] public readonly int IdleBaseUnitsMaximum = 12; [Desc("Radius in cells around enemy BaseBuilder (Construction Yard) where AI scans for targets to rush.")] public readonly int RushAttackScanRadius = 15; [Desc("Radius in cells around the base that should be scanned for units to be protected.")] public readonly int ProtectUnitScanRadius = 15; [Desc("Radius in cells around a factory scanned for rally points by the AI.")] public readonly int RallyPointScanRadius = 8; [Desc("Radius in cells around the center of the base to expand.")] public readonly int MaxBaseRadius = 20; [Desc("Production queues AI uses for producing units.")] public readonly string[] UnitQueues = { "Vehicle", "Infantry", "Plane", "Ship", "Aircraft" }; [Desc("Should the AI repair its buildings if damaged?")] public readonly bool ShouldRepairBuildings = true; string IBotInfo.Name { get { return this.Name; } } [Desc("What units to the AI should build.", "What % of the total army must be this type of unit.")] [FieldLoader.LoadUsing("LoadUnits")] public readonly Dictionary<string, float> UnitsToBuild = null; [Desc("What buildings to the AI should build.", "What % of the total base must be this type of building.")] [FieldLoader.LoadUsing("LoadBuildings")] public readonly Dictionary<string, float> BuildingFractions = null; [Desc("Tells the AI what unit types fall under the same common name.")] [FieldLoader.LoadUsing("LoadUnitsCommonNames")] public readonly Dictionary<string, string[]> UnitsCommonNames = null; [Desc("Tells the AI what building types fall under the same common name.")] [FieldLoader.LoadUsing("LoadBuildingsCommonNames")] public readonly Dictionary<string, string[]> BuildingCommonNames = null; [Desc("What buildings should the AI have max limits n.", "What is the limit of the building.")] [FieldLoader.LoadUsing("LoadBuildingLimits")] public readonly Dictionary<string, int> BuildingLimits = null; // TODO Update OpenRA.Utility/Command.cs#L300 to first handle lists and also read nested ones [Desc("Tells the AI how to use its support powers.")] [FieldLoader.LoadUsing("LoadDecisions")] public readonly List<SupportPowerDecision> PowerDecisions = new List<SupportPowerDecision>(); static object LoadList<T>(MiniYaml y, string field) { var nd = y.ToDictionary(); return nd.ContainsKey(field) ? nd[field].ToDictionary(my => FieldLoader.GetValue<T>(field, my.Value)) : new Dictionary<string, T>(); } static object LoadUnits(MiniYaml y) { return LoadList<float>(y, "UnitsToBuild"); } static object LoadBuildings(MiniYaml y) { return LoadList<float>(y, "BuildingFractions"); } static object LoadUnitsCommonNames(MiniYaml y) { return LoadList<string[]>(y, "UnitsCommonNames"); } static object LoadBuildingsCommonNames(MiniYaml y) { return LoadList<string[]>(y, "BuildingCommonNames"); } static object LoadBuildingLimits(MiniYaml y) { return LoadList<int>(y, "BuildingLimits"); } static object LoadDecisions(MiniYaml yaml) { var ret = new List<SupportPowerDecision>(); foreach (var d in yaml.Nodes) if (d.Key.Split('@')[0] == "SupportPowerDecision") ret.Add(new SupportPowerDecision(d.Value)); return ret; } public object Create(ActorInitializer init) { return new HackyAI(this, init); } } public class Enemy { public int Aggro; } public enum BuildingType { Building, Defense, Refinery } public sealed class HackyAI : ITick, IBot, INotifyDamage { public MersenneTwister random { get; private set; } public readonly HackyAIInfo Info; public CPos baseCenter { get; private set; } public Player p { get; private set; } Dictionary<SupportPowerInstance, int> waitingPowers = new Dictionary<SupportPowerInstance, int>(); Dictionary<string, SupportPowerDecision> powerDecisions = new Dictionary<string, SupportPowerDecision>(); PowerManager playerPower; SupportPowerManager supportPowerMngr; PlayerResources playerResource; bool enabled; int ticks; BitArray resourceTypeIndices; RushFuzzy rushFuzzy = new RushFuzzy(); Cache<Player, Enemy> aggro = new Cache<Player, Enemy>(_ => new Enemy()); List<BaseBuilder> builders = new List<BaseBuilder>(); List<Squad> squads = new List<Squad>(); List<Actor> unitsHangingAroundTheBase = new List<Actor>(); // Units that the ai already knows about. Any unit not on this list needs to be given a role. List<Actor> activeUnits = new List<Actor>(); public const int feedbackTime = 30; // ticks; = a bit over 1s. must be >= netlag. public readonly World world; public Map Map { get { return world.Map; } } IBotInfo IBot.Info { get { return this.Info; } } public HackyAI(HackyAIInfo info, ActorInitializer init) { Info = info; world = init.world; foreach (var decision in info.PowerDecisions) powerDecisions.Add(decision.OrderName, decision); } public static void BotDebug(string s, params object[] args) { if (Game.Settings.Debug.BotDebug) Game.Debug(s, args); } // Called by the host's player creation code public void Activate(Player p) { this.p = p; enabled = true; playerPower = p.PlayerActor.Trait<PowerManager>(); supportPowerMngr = p.PlayerActor.Trait<SupportPowerManager>(); playerResource = p.PlayerActor.Trait<PlayerResources>(); foreach (var building in Info.BuildingQueues) builders.Add(new BaseBuilder(this, building, p, playerPower, playerResource)); foreach (var defense in Info.DefenseQueues) builders.Add(new BaseBuilder(this, defense, p, playerPower, playerResource)); random = new MersenneTwister((int)p.PlayerActor.ActorID); resourceTypeIndices = new BitArray(world.TileSet.TerrainInfo.Length); // Big enough foreach (var t in Map.Rules.Actors["world"].Traits.WithInterface<ResourceTypeInfo>()) resourceTypeIndices.Set(world.TileSet.GetTerrainIndex(t.TerrainType), true); } ActorInfo ChooseRandomUnitToBuild(ProductionQueue queue) { var buildableThings = queue.BuildableItems(); if (!buildableThings.Any()) return null; var unit = buildableThings.ElementAtOrDefault(random.Next(buildableThings.Count())); return HasAdequateAirUnits(unit) ? unit : null; } ActorInfo ChooseUnitToBuild(ProductionQueue queue) { var buildableThings = queue.BuildableItems(); if (!buildableThings.Any()) return null; var myUnits = p.World .ActorsWithTrait<IPositionable>() .Where(a => a.Actor.Owner == p) .Select(a => a.Actor.Info.Name).ToArray(); foreach (var unit in Info.UnitsToBuild.Shuffle(random)) if (buildableThings.Any(b => b.Name == unit.Key)) if (myUnits.Count(a => a == unit.Key) < unit.Value * myUnits.Length) if (HasAdequateAirUnits(Map.Rules.Actors[unit.Key])) return Map.Rules.Actors[unit.Key]; return null; } int CountBuilding(string frac, Player owner) { return world.ActorsWithTrait<Building>() .Count(a => a.Actor.Owner == owner && a.Actor.Info.Name == frac); } int CountUnits(string unit, Player owner) { return world.ActorsWithTrait<IPositionable>() .Count(a => a.Actor.Owner == owner && a.Actor.Info.Name == unit); } int? CountBuildingByCommonName(string commonName, Player owner) { if (!Info.BuildingCommonNames.ContainsKey(commonName)) return null; return world.ActorsWithTrait<Building>() .Count(a => a.Actor.Owner == owner && Info.BuildingCommonNames[commonName].Contains(a.Actor.Info.Name)); } public ActorInfo GetBuildingInfoByCommonName(string commonName, Player owner) { if (commonName == "ConstructionYard") return Map.Rules.Actors.Where(k => Info.BuildingCommonNames[commonName].Contains(k.Key)).Random(random).Value; return GetInfoByCommonName(Info.BuildingCommonNames, commonName, owner); } public ActorInfo GetUnitInfoByCommonName(string commonName, Player owner) { return GetInfoByCommonName(Info.UnitsCommonNames, commonName, owner); } public ActorInfo GetInfoByCommonName(Dictionary<string, string[]> names, string commonName, Player owner) { if (!names.Any() || !names.ContainsKey(commonName)) throw new InvalidOperationException("Can't find {0} in the HackyAI UnitsCommonNames definition.".F(commonName)); return Map.Rules.Actors.Where(k => names[commonName].Contains(k.Key)).Random(random).Value; } public bool HasAdequateFact() { // Require at least one construction yard, unless we have no vehicles factory (can't build it). return CountBuildingByCommonName("ConstructionYard", p) > 0 || CountBuildingByCommonName("VehiclesFactory", p) == 0; } public bool HasAdequateProc() { // Require at least one refinery, unless we have no power (can't build it). return CountBuildingByCommonName("Refinery", p) > 0 || CountBuildingByCommonName("Power", p) == 0; } public bool HasMinimumProc() { // Require at least two refineries, unless we have no power (can't build it) // or barracks (higher priority?) return CountBuildingByCommonName("Refinery", p) >= 2 || CountBuildingByCommonName("Power", p) == 0 || CountBuildingByCommonName("Barracks", p) == 0; } // For mods like RA (number of building must match the number of aircraft) bool HasAdequateAirUnits(ActorInfo actorInfo) { if (!actorInfo.Traits.Contains<ReloadsInfo>() && actorInfo.Traits.Contains<LimitedAmmoInfo>() && actorInfo.Traits.Contains<AircraftInfo>()) { var countOwnAir = CountUnits(actorInfo.Name, p); var countBuildings = CountBuilding(actorInfo.Traits.Get<AircraftInfo>().RearmBuildings.FirstOrDefault(), p); if (countOwnAir >= countBuildings) return false; } return true; } CPos defenseCenter; public CPos? ChooseBuildLocation(string actorType, bool distanceToBaseIsImportant, BuildingType type) { var bi = Map.Rules.Actors[actorType].Traits.GetOrDefault<BuildingInfo>(); if (bi == null) return null; // Find the buildable cell that is closest to pos and centered around center Func<CPos, CPos, int, int, CPos?> findPos = (center, target, minRange, maxRange) => { var cells = Map.FindTilesInAnnulus(center, minRange, maxRange); // Sort by distance to target if we have one if (center != target) cells = cells.OrderBy(c => (c - target).LengthSquared); else cells = cells.Shuffle(random); foreach (var cell in cells) { if (!world.CanPlaceBuilding(actorType, bi, cell, null)) continue; if (distanceToBaseIsImportant && !bi.IsCloseEnoughToBase(world, p, actorType, cell)) continue; return cell; } return null; }; switch (type) { case BuildingType.Defense: // Build near the closest enemy structure var closestEnemy = world.Actors.Where(a => !a.Destroyed && a.HasTrait<Building>() && p.Stances[a.Owner] == Stance.Enemy) .ClosestTo(world.Map.CenterOfCell(defenseCenter)); var targetCell = closestEnemy != null ? closestEnemy.Location : baseCenter; return findPos(defenseCenter, targetCell, Info.MinimumDefenseRadius, Info.MaximumDefenseRadius); case BuildingType.Refinery: // Try and place the refinery near a resource field var nearbyResources = Map.FindTilesInCircle(baseCenter, Info.MaxBaseRadius) .Where(a => resourceTypeIndices.Get(Map.GetTerrainIndex(a))) .Shuffle(random); foreach (var c in nearbyResources) { var found = findPos(c, baseCenter, 0, Info.MaxBaseRadius); if (found != null) return found; } // Try and find a free spot somewhere else in the base return findPos(baseCenter, baseCenter, 0, Info.MaxBaseRadius); case BuildingType.Building: return findPos(baseCenter, baseCenter, 0, distanceToBaseIsImportant ? Info.MaxBaseRadius : Map.MaxTilesInCircleRange); } // Can't find a build location return null; } public void Tick(Actor self) { if (!enabled) return; ticks++; if (ticks == 1) InitializeBase(self); if (ticks % feedbackTime == 0) ProductionUnits(self); AssignRolesToIdleUnits(self); SetRallyPointsForNewProductionBuildings(self); TryToUseSupportPower(self); foreach (var b in builders) b.Tick(); } internal Actor ChooseEnemyTarget() { if (p.WinState != WinState.Undefined) return null; var liveEnemies = world.Players .Where(q => p != q && p.Stances[q] == Stance.Enemy && q.WinState == WinState.Undefined); if (!liveEnemies.Any()) return null; var leastLikedEnemies = liveEnemies .GroupBy(e => aggro[e].Aggro) .MaxByOrDefault(g => g.Key); var enemy = (leastLikedEnemies != null) ? leastLikedEnemies.Random(random) : liveEnemies.FirstOrDefault(); // Pick something worth attacking owned by that player var target = world.Actors .Where(a => a.Owner == enemy && a.HasTrait<IOccupySpace>()) .ClosestTo(world.Map.CenterOfCell(baseCenter)); if (target == null) { /* Assume that "enemy" has nothing. Cool off on attacks. */ aggro[enemy].Aggro = aggro[enemy].Aggro / 2 - 1; Log.Write("debug", "Bot {0} couldn't find target for player {1}", this.p.ClientIndex, enemy.ClientIndex); return null; } // Bump the aggro slightly to avoid changing our mind if (leastLikedEnemies.Count() > 1) aggro[enemy].Aggro++; return target; } internal Actor FindClosestEnemy(WPos pos) { var allEnemyUnits = world.Actors .Where(unit => p.Stances[unit.Owner] == Stance.Enemy && !unit.HasTrait<Husk>() && unit.HasTrait<ITargetable>()); return allEnemyUnits.ClosestTo(pos); } internal Actor FindClosestEnemy(WPos pos, WRange radius) { var enemyUnits = world.FindActorsInCircle(pos, radius) .Where(unit => p.Stances[unit.Owner] == Stance.Enemy && !unit.HasTrait<Husk>() && unit.HasTrait<ITargetable>()).ToList(); if (enemyUnits.Count > 0) return enemyUnits.ClosestTo(pos); return null; } List<Actor> FindEnemyConstructionYards() { return world.Actors.Where(a => p.Stances[a.Owner] == Stance.Enemy && !a.IsDead && a.HasTrait<BaseBuilding>() && !a.HasTrait<Mobile>()).ToList(); } void CleanSquads() { squads.RemoveAll(s => !s.IsValid); foreach (var s in squads) s.units.RemoveAll(a => a.IsDead || a.Owner != p); } // Use of this function requires that one squad of this type. Hence it is a piece of shit Squad GetSquadOfType(SquadType type) { return squads.FirstOrDefault(s => s.type == type); } Squad RegisterNewSquad(SquadType type, Actor target = null) { var ret = new Squad(this, type, target); squads.Add(ret); return ret; } int assignRolesTicks = 0; int rushTicks = 0; int attackForceTicks = 0; void AssignRolesToIdleUnits(Actor self) { CleanSquads(); activeUnits.RemoveAll(a => a.IsDead || a.Owner != p); unitsHangingAroundTheBase.RemoveAll(a => a.IsDead || a.Owner != p); if (--rushTicks <= 0) { rushTicks = Info.RushInterval; TryToRushAttack(); } if (--attackForceTicks <= 0) { attackForceTicks = Info.AttackForceInterval; foreach (var s in squads) s.Update(); } if (--assignRolesTicks > 0) return; assignRolesTicks = Info.AssignRolesInterval; GiveOrdersToIdleHarvesters(); FindNewUnits(self); CreateAttackForce(); FindAndDeployBackupMcv(self); } void GiveOrdersToIdleHarvesters() { // Find idle harvesters and give them orders: foreach (var a in activeUnits) { var harv = a.TraitOrDefault<Harvester>(); if (harv == null) continue; if (!a.IsIdle) { var act = a.GetCurrentActivity(); // A Wait activity is technically idle: if ((act.GetType() != typeof(Wait)) && (act.NextActivity == null || act.NextActivity.GetType() != typeof(FindResources))) continue; } if (!harv.IsEmpty) continue; // Tell the idle harvester to quit slacking: world.IssueOrder(new Order("Harvest", a, false)); } } void FindNewUnits(Actor self) { var newUnits = self.World.ActorsWithTrait<IPositionable>() .Where(a => a.Actor.Owner == p && !a.Actor.HasTrait<BaseBuilding>() && !activeUnits.Contains(a.Actor)) .Select(a => a.Actor); foreach (var a in newUnits) { if (a.HasTrait<Harvester>()) world.IssueOrder(new Order("Harvest", a, false)); else unitsHangingAroundTheBase.Add(a); if (a.HasTrait<Aircraft>() && a.HasTrait<AttackBase>()) { var air = GetSquadOfType(SquadType.Air); if (air == null) air = RegisterNewSquad(SquadType.Air); air.units.Add(a); } activeUnits.Add(a); } } void CreateAttackForce() { // Create an attack force when we have enough units around our base. // (don't bother leaving any behind for defense) var randomizedSquadSize = Info.SquadSize + random.Next(30); if (unitsHangingAroundTheBase.Count >= randomizedSquadSize) { var attackForce = RegisterNewSquad(SquadType.Assault); foreach (var a in unitsHangingAroundTheBase) if (!a.HasTrait<Aircraft>()) attackForce.units.Add(a); unitsHangingAroundTheBase.Clear(); } } void TryToRushAttack() { var allEnemyBaseBuilder = FindEnemyConstructionYards(); var ownUnits = activeUnits .Where(unit => unit.HasTrait<AttackBase>() && !unit.HasTrait<Aircraft>() && unit.IsIdle).ToList(); if (!allEnemyBaseBuilder.Any() || (ownUnits.Count < Info.SquadSize)) return; foreach (var b in allEnemyBaseBuilder) { var enemies = world.FindActorsInCircle(b.CenterPosition, WRange.FromCells(Info.RushAttackScanRadius)) .Where(unit => p.Stances[unit.Owner] == Stance.Enemy && unit.HasTrait<AttackBase>()).ToList(); if (rushFuzzy.CanAttack(ownUnits, enemies)) { var target = enemies.Any() ? enemies.Random(random) : b; var rush = GetSquadOfType(SquadType.Rush); if (rush == null) rush = RegisterNewSquad(SquadType.Rush, target); foreach (var a3 in ownUnits) rush.units.Add(a3); return; } } } void ProtectOwn(Actor attacker) { var protectSq = GetSquadOfType(SquadType.Protection); if (protectSq == null) protectSq = RegisterNewSquad(SquadType.Protection, attacker); if (!protectSq.TargetIsValid) protectSq.Target = attacker; if (!protectSq.IsValid) { var ownUnits = world.FindActorsInCircle(world.Map.CenterOfCell(baseCenter), WRange.FromCells(Info.ProtectUnitScanRadius)) .Where(unit => unit.Owner == p && !unit.HasTrait<Building>() && unit.HasTrait<AttackBase>()).ToList(); foreach (var a in ownUnits) protectSq.units.Add(a); } } bool IsRallyPointValid(CPos x, BuildingInfo info) { return info != null && world.IsCellBuildable(x, info); } void SetRallyPointsForNewProductionBuildings(Actor self) { var buildings = self.World.ActorsWithTrait<RallyPoint>() .Where(rp => rp.Actor.Owner == p && !IsRallyPointValid(rp.Trait.Location, rp.Actor.Info.Traits.GetOrDefault<BuildingInfo>())).ToArray(); foreach (var a in buildings) world.IssueOrder(new Order("SetRallyPoint", a.Actor, false) { TargetLocation = ChooseRallyLocationNear(a.Actor), SuppressVisualFeedback = true }); } // Won't work for shipyards... CPos ChooseRallyLocationNear(Actor producer) { var possibleRallyPoints = Map.FindTilesInCircle(producer.Location, Info.RallyPointScanRadius) .Where(c => IsRallyPointValid(c, producer.Info.Traits.GetOrDefault<BuildingInfo>())); if (!possibleRallyPoints.Any()) { BotDebug("Bot Bug: No possible rallypoint near {0}", producer.Location); return producer.Location; } return possibleRallyPoints.Random(random); } void InitializeBase(Actor self) { // Find and deploy our mcv var mcv = self.World.Actors .FirstOrDefault(a => a.Owner == p && a.HasTrait<BaseBuilding>()); if (mcv != null) { baseCenter = mcv.Location; defenseCenter = baseCenter; // Don't transform the mcv if it is a fact // HACK: This needs to query against MCVs directly if (mcv.HasTrait<Mobile>()) world.IssueOrder(new Order("DeployTransform", mcv, false)); } else BotDebug("AI: Can't find BaseBuildUnit."); } // Find any newly constructed MCVs and deploy them at a sensible // backup location within the main base. void FindAndDeployBackupMcv(Actor self) { // HACK: This needs to query against MCVs directly var mcvs = self.World.Actors.Where(a => a.Owner == p && a.HasTrait<BaseBuilding>() && a.HasTrait<Mobile>()); if (!mcvs.Any()) return; foreach (var mcv in mcvs) { if (mcv.IsMoving()) continue; var factType = mcv.Info.Traits.Get<TransformsInfo>().IntoActor; var desiredLocation = ChooseBuildLocation(factType, false, BuildingType.Building); if (desiredLocation == null) continue; world.IssueOrder(new Order("Move", mcv, true) { TargetLocation = desiredLocation.Value }); world.IssueOrder(new Order("DeployTransform", mcv, true)); } } void TryToUseSupportPower(Actor self) { if (supportPowerMngr == null) return; var powers = supportPowerMngr.Powers.Where(p => !p.Value.Disabled); foreach (var kv in powers) { var sp = kv.Value; // Add power to dictionary if not in delay dictionary yet if (!waitingPowers.ContainsKey(sp)) waitingPowers.Add(sp, 0); if (waitingPowers[sp] > 0) waitingPowers[sp]--; // If we have recently tried and failed to find a use location for a power, then do not try again until later var isDelayed = (waitingPowers[sp] > 0); if (sp.Ready && !isDelayed && powerDecisions.ContainsKey(sp.Info.OrderName)) { var powerDecision = powerDecisions[sp.Info.OrderName]; if (powerDecision == null) { BotDebug("Bot Bug: FindAttackLocationToSupportPower, couldn't find powerDecision for {0}", sp.Info.OrderName); continue; } var attackLocation = FindCoarseAttackLocationToSupportPower(sp); if (attackLocation == null) { BotDebug("AI: {1} can't find suitable coarse attack location for support power {0}. Delaying rescan.", sp.Info.OrderName, p.PlayerName); waitingPowers[sp] += powerDecision.GetNextScanTime(this); continue; } // Found a target location, check for precise target attackLocation = FindFineAttackLocationToSupportPower(sp, (CPos)attackLocation); if (attackLocation == null) { BotDebug("AI: {1} can't find suitable final attack location for support power {0}. Delaying rescan.", sp.Info.OrderName, p.PlayerName); waitingPowers[sp] += powerDecision.GetNextScanTime(this); continue; } // Valid target found, delay by a few ticks to avoid rescanning before power fires via order BotDebug("AI: {2} found new target location {0} for support power {1}.", attackLocation, sp.Info.OrderName, p.PlayerName); waitingPowers[sp] += 10; world.IssueOrder(new Order(sp.Info.OrderName, supportPowerMngr.self, false) { TargetLocation = attackLocation.Value, SuppressVisualFeedback = true }); } } } ///<summary>Scans the map in chunks, evaluating all actors in each.</summary> CPos? FindCoarseAttackLocationToSupportPower(SupportPowerInstance readyPower) { CPos? bestLocation = null; var bestAttractiveness = 0; var powerDecision = powerDecisions[readyPower.Info.OrderName]; if (powerDecision == null) { BotDebug("Bot Bug: FindAttackLocationToSupportPower, couldn't find powerDecision for {0}", readyPower.Info.OrderName); return null; } var checkRadius = powerDecision.CoarseScanRadius; for (var i = 0; i < world.Map.MapSize.X; i += checkRadius) { for (var j = 0; j < world.Map.MapSize.Y; j += checkRadius) { var consideredAttractiveness = 0; var tl = world.Map.CenterOfCell(new CPos(i, j)); var br = world.Map.CenterOfCell(new CPos(i + checkRadius, j + checkRadius)); var targets = world.ActorMap.ActorsInBox(tl, br); consideredAttractiveness = powerDecision.GetAttractiveness(targets, p); if (consideredAttractiveness <= bestAttractiveness || consideredAttractiveness < powerDecision.MinimumAttractiveness) continue; bestAttractiveness = consideredAttractiveness; bestLocation = new CPos(i, j); } } return bestLocation; } ///<summary>Detail scans an area, evaluating positions.</summary> CPos? FindFineAttackLocationToSupportPower(SupportPowerInstance readyPower, CPos checkPos, int extendedRange = 1) { CPos? bestLocation = null; var bestAttractiveness = 0; var powerDecision = powerDecisions[readyPower.Info.OrderName]; if (powerDecision == null) { BotDebug("Bot Bug: FindAttackLocationToSupportPower, couldn't find powerDecision for {0}", readyPower.Info.OrderName); return null; } var checkRadius = powerDecision.CoarseScanRadius; var fineCheck = powerDecision.FineScanRadius; for (var i = (0 - extendedRange); i <= (checkRadius + extendedRange); i += fineCheck) { var x = checkPos.X + i; for (var j = (0 - extendedRange); j <= (checkRadius + extendedRange); j += fineCheck) { var y = checkPos.Y + j; var pos = world.Map.CenterOfCell(new CPos(x, y)); var consideredAttractiveness = 0; consideredAttractiveness += powerDecision.GetAttractiveness(pos, p); if (consideredAttractiveness <= bestAttractiveness || consideredAttractiveness < powerDecision.MinimumAttractiveness) continue; bestAttractiveness = consideredAttractiveness; bestLocation = new CPos(x, y); } } return bestLocation; } internal IEnumerable<ProductionQueue> FindQueues(string category) { return world.ActorsWithTrait<ProductionQueue>() .Where(a => a.Actor.Owner == p && a.Trait.Info.Type == category && a.Trait.Enabled) .Select(a => a.Trait); } void ProductionUnits(Actor self) { // Stop building until economy is restored if (!HasAdequateProc()) return; // No construction yards - Build a new MCV if (!HasAdequateFact() && !self.World.Actors.Any(a => a.Owner == p && a.HasTrait<BaseBuilding>() && a.HasTrait<Mobile>())) BuildUnit("Vehicle", GetUnitInfoByCommonName("Mcv", p).Name); foreach (var q in Info.UnitQueues) BuildUnit(q, unitsHangingAroundTheBase.Count < Info.IdleBaseUnitsMaximum); } void BuildUnit(string category, bool buildRandom) { // Pick a free queue var queue = FindQueues(category).FirstOrDefault(q => q.CurrentItem() == null); if (queue == null) return; var unit = buildRandom ? ChooseRandomUnitToBuild(queue) : ChooseUnitToBuild(queue); if (unit != null && Info.UnitsToBuild.Any(u => u.Key == unit.Name)) world.IssueOrder(Order.StartProduction(queue.Actor, unit.Name, 1)); } void BuildUnit(string category, string name) { var queue = FindQueues(category).FirstOrDefault(q => q.CurrentItem() == null); if (queue == null) return; if (Map.Rules.Actors[name] != null) world.IssueOrder(Order.StartProduction(queue.Actor, name, 1)); } public void Damaged(Actor self, AttackInfo e) { if (!enabled) return; if (e.Attacker.Owner.Stances[self.Owner] == Stance.Neutral) return; var rb = self.TraitOrDefault<RepairableBuilding>(); if (Info.ShouldRepairBuildings && rb != null) { if (e.DamageState > DamageState.Light && e.PreviousDamageState <= DamageState.Light && !rb.RepairActive) { BotDebug("Bot noticed damage {0} {1}->{2}, repairing.", self, e.PreviousDamageState, e.DamageState); world.IssueOrder(new Order("RepairBuilding", self.Owner.PlayerActor, false) { TargetActor = self }); } } if (e.Attacker.Destroyed) return; if (!e.Attacker.HasTrait<ITargetable>()) return; if (e.Attacker != null && e.Damage > 0) aggro[e.Attacker.Owner].Aggro += e.Damage; // Protected harvesters or building if ((self.HasTrait<Harvester>() || self.HasTrait<Building>()) && p.Stances[e.Attacker.Owner] == Stance.Enemy) { defenseCenter = e.Attacker.Location; ProtectOwn(e.Attacker); } } } }
166MMX/OpenRA
OpenRA.Mods.RA/AI/HackyAI.cs
C#
gpl-3.0
30,524
#!/usr/bin/env python # coding=utf-8 # Copyright (C) 2014 by Serge Poltavski # # serge.poltavski@gmail.com # # # # This program is free software; you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation; either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/> # from __future__ import print_function __author__ = 'Serge Poltavski' class PdPainter(object): def draw_canvas(self, canvas): pass def draw_comment(self, comment): print("Draw comment: #", comment.text()) def draw_message(self, message): print("Draw message [id:%i]: %s" % (message.id, message.to_string())) def draw_object(self, obj): print("Draw object: [id:%i] [%s]" % (obj.id, " ".join(obj.args))) def draw_core_gui(self, gui): print("Draw core GUI: [id:%i] [%s]" % (gui.id, gui.name)) def draw_subpatch(self, subpatch): print("Draw subpatch: [pd {0:s}]".format(subpatch.name)) def draw_graph(self, graph): print("Draw graph ") def draw_connections(self, canvas): print("Draw connections ") def draw_poly(self, vertexes, **kwargs): print("Draw poly:", vertexes) def draw_text(self, x, y, text, **kwargs): print("Draw text:", text) def draw_inlets(self, inlets, x, y, width): print("Draw inlets:", inlets) def draw_outlets(self, outlets, x, y, width): print("Draw outlets:", outlets) def draw_circle(self, x, y, width, **kwargs): print("Draw circle") def draw_arc(self, x, y, radius, start_angle, end_angle, **kwargs): print("Draw arc") def draw_line(self, x0, y0, x1, y1, **kwargs): print("Draw line") def draw_rect(self, x, y, w, h, **kwargs): print("Draw rect")
uliss/pddoc
pddoc/pdpainter.py
Python
gpl-3.0
2,655
package main import ( "io/ioutil" "log" "os" "strconv" "time" "github.com/openlab-aux/golableuchtung" serial "github.com/huin/goserial" ) func main() { if len(os.Args) != 5 { log.Fatal("invalid number of arguments") } leucht := lableuchtung.LabLeucht{} c := &serial.Config{ Name: "/dev/ttyACM0", Baud: 115200, } var err error leucht.ReadWriteCloser, err = serial.OpenPort(c) if err != nil { log.Fatal(err) } leucht.ResponseTimeout = 10 * time.Millisecond ioutil.ReadAll(leucht) // consume fnord pkg := lableuchtung.Package{0, 0, 0, 0} for i := 0; i < 4; i++ { v, err := strconv.ParseUint(os.Args[i+1], 10, 8) if err != nil { log.Fatal(err) } pkg[i] = byte(v) } err = leucht.SendPackage(pkg) if err != nil { log.Fatal(err) } }
openlab-aux/golableuchtung
serialcli/leucht.go
GO
gpl-3.0
784
<? /** * @license http://www.mailcleaner.net/open/licence_en.html Mailcleaner Public License * @package mailcleaner * @author Olivier Diserens * @copyright 2006, Olivier Diserens */ /** * needs some defaults */ require_once ("system/SystemConfig.php"); class Pie { /** * file name * @var string */ private $filename_ = 'untitled.png'; /** * chart width and height * @var array */ private $size_ = array("width" => 0, "height" => 0); /** * chart 3d effect width */ private $width3d_ = 20; /** * datas * @var array */ private $datas_ = array(); /** * sum of all the values * @var numeric */ private $sum_values_ = 0; /** * constructor */ public function __construct() {} /** * set the filename * @param $filename string the filename * @return boolean trus on success, false on failure */ public function setFilename($filename) { if ($filename != "") { $this->filename_ = $filename; return true; } return false; } /** * set the Pie size * @param $witdh integer graphic witdh * @param $height integer graphic height * @return boolean true on success, false on failure */ public function setSize($width, $height) { if (is_int($width) && is_int($height)) { $this->size_['width'] = $width; $this->size_['height'] = $height; return true; } return false; } /** * add a data value * @param $value numeric numeric value * @param $name string name of the value * @param $color array color * @return boolean true on success, false on failure */ public function addValue($value, $name, $color) { if (!is_numeric($value) || !is_array($color)) { return false; } if ($value == 0) { return true; } array_push($this->datas_, array('v' => $value, 'n' => $name, 'c' => $color)); $this->sum_values_ += $value; return true; } /** * generate the graphic file * @return boolean true on success, false on failure */ public function generate() { $sysconf = SystemConfig::getInstance(); $delta = 270; $width = $this->size_['width']*2; $height = ($this->size_['height']+$this->width3d_)*2; $ext_width = $width + 5; $ext_height= $height + $this->width3d_ + 5; $image = imagecreatetruecolor($ext_width, $ext_height); $white = imagecolorallocate($image, 0xFF, 0xFF, 0xFF); imagefilledrectangle($image, 0, 0, $ext_width, $ext_height, $white); $xcenter = intval($ext_width / 2); $ycenter = intval($ext_height / 2) - ($this->width3d_/2); $gray = imagecolorallocate($image, 0xC0, 0xC0, 0xC0); $darkgray = imagecolorallocate($image, 0x90, 0x90, 0x90); $colors = array(); ## create 3d effect for ($i = $ycenter+$this->width3d_; $i > $ycenter; $i--) { $last_angle = 0; imagefilledarc($image, $xcenter, $i, $width, $height, 0, 360 , $darkgray, IMG_ARC_PIE); foreach ($this->datas_ as $data) { $name = $data['n']; $rcomp = intval($data['c'][0]- 0x40); if ($rcomp < 0) { $rcomp = 0; } $gcomp = intval($data['c'][1]- 0x40); if ($gcomp < 0) { $gcomp = 0; } $bcomp = intval($data['c'][2]- 0x40); if ($bcomp < 0) { $bcomp = 0; } $colors[$name] = imagecolorallocate($image, $rcomp, $gcomp, $bcomp); $percent = (100/$this->sum_values_) * $data['v']; $angle = $percent * 3.6; if ($angle < 1.1) { $angle = 1.1; } imagefilledarc($image, $xcenter, $i, $width, $height, $last_angle+$delta, $last_angle+$angle+$delta , $colors[$name], IMG_ARC_PIE); $last_angle += $angle; } } ## create default imagefilledarc($image, $xcenter, $ycenter, $width, $height, 0, 360 , $gray, IMG_ARC_PIE); ## creates real pies $last_angle = 0; foreach ($this->datas_ as $data) { $name = $data['n']; $colors[$name] = imagecolorallocate($image, $data['c'][0], $data['c'][1], $data['c'][2]); $percent = (100/$this->sum_values_) * $data['v']; $angle = $percent * 3.6; if ($angle < 1.1) { $angle = 1.1; } imagefilledarc($image, $xcenter, $ycenter, $width, $height, $last_angle+$delta, $last_angle+$angle+$delta , $colors[$name], IMG_ARC_PIE); $last_angle += $angle; } // resample to get anti-alias effect $destImage = imagecreatetruecolor($this->size_['width'], $this->size_['height']); imagecopyresampled($destImage, $image, 0, 0, 0, 0, $this->size_['width'], $this->size_['height'], $ext_width, $ext_height); imagepng($destImage, $sysconf->VARDIR_."/www/".$this->filename_); imagedestroy($image); imagedestroy($destImage); return true; } } ?>
MailCleaner/MailCleaner
www/classes/view/graphics/Pie.php
PHP
gpl-3.0
4,573
# SSH proxy forward and remote shell __author__ = "Frederico Martins" __license__ = "GPLv3" __version__ = 1 from getpass import getpass from paramiko import AutoAddPolicy, SSHClient, ssh_exception class SSH(object): proxy = None def __init__(self, host, user, password=None, port=22): self.host = host self.port = port self.user = user self.password = password or getpass(prompt="Network password: ") def forward(self, host, user=None, password=None, port=22): self._proxy = SSHClient() user = user or self.user password = password or self.password self._proxy.set_missing_host_key_policy(AutoAddPolicy()) try: self._proxy.connect(host, port=port, username=user, password=password) except ssh_exception.AuthenticationException: print("Error: Authentication failed for user {0}".format(self.user)) exit(-1) transport = self._proxy.get_transport() self.proxy = transport.open_channel("direct-tcpip", (self.host, self.port), (host, port)) def execute(self, command): if not hasattr(self, '_ssh'): self._ssh = SSHClient() self._ssh.set_missing_host_key_policy(AutoAddPolicy()) self._ssh.connect(self.host, username=self.user, password=self.password, sock=self.proxy) return self._ssh.exec_command(command) def close(self): if hasattr(self, '_ssh'): self._ssh.close() if hasattr(self, '_proxy'): self._proxy.close()
flippym/toolbox
ssh-streaming.py
Python
gpl-3.0
1,573
<?php // Define queries inside of the reports array. // !! IMPORTANT: Make sure queries do not have a semicolon ';' at the end so the pagination will work. $reports = array(); $reports['default'] = "SELECT username,full_name,email,date_created,active,login_date from users";
PyrousNET/TorchFramework
reports/users.php
PHP
gpl-3.0
276
import os, json, random from utils import * import collections class FileDataBaseException(Exception): pass def update_dict_recursively(d, u): for k, v in u.iteritems(): if isinstance(v, collections.Mapping): r = update_dict_recursively(d.get(k, {}), v) d[k] = r else: d[k] = u[k] return d class FileDataBase: def __init__(self): self.files = {} self.last_id = 0 self.shuffled_keys = None self.shuffled_last = 0 self._init = False self._files_saved = False def IsInitialized(self): return self._init def ScanDirectoryRecursively(self, watch_dir, extension, exclude, myFileInfoExtractor=None, renewFiles=True): changed = 0 count = 0 exist = 0 excluded = 0 path2file = {self.files[i]['path']: i for i in self.files} files_ok = {} for root, _, files in os.walk(watch_dir): for filename in files: # skip excluded files if filename in exclude: excluded += 1 continue if filename.endswith(extension): path = root + '/' + filename # find duplicates added = False value = {'path': path} if myFileInfoExtractor: try: info = myFileInfoExtractor(path) except: info = None if info is None: excluded += 1 continue value.update(info) if path in path2file: id_ = path2file[path] files_ok[id_] = value changed += self.files[id_] != value added = True exist += 1 if not added: files_ok[str(self.last_id)] = value self.last_id += 1 count += 1 if renewFiles: self.files = files_ok else: self.files.update(files_ok) self._init = True self._files_saved = False if count > 0 or changed > 0 else True return count, exist, excluded def ShuffleFiles(self): self.shuffled_keys = self.files.keys() myRandom = random.Random(42) myRandom.shuffle(self.shuffled_keys) def GetFilesPortion(self, count, count_is_percent=True): if self.shuffled_keys is None: raise FileDataBaseException('Use ShuffleFiles before GetFilesPortion') if count_is_percent: count *= self.GetFilesNumber() start = self.shuffled_last end = None if count is None else int(self.shuffled_last+count) self.shuffled_last = end return self.shuffled_keys[start:end] def GetFilesPortions(self, count_list): return [self.GetFilesPortion(c) for c in count_list] def ResetShuffle(self): self.shuffled_keys = None self.shuffled_last = 0 def GetFile(self, _id): return self.files[_id] def GetPath(self, _id): try: int(_id) except: return _id else: return self.files[_id]['path'] def GetPathes(self, ids_or_ids_list): if isinstance(ids_or_ids_list, list): if isinstance(ids_or_ids_list[0], list): return [[self.GetPath(i) for i in ids] for ids in ids_or_ids_list] return [self.GetPath(i) for i in ids_or_ids_list] def SetFiles(self, other_filedb): self.files = other_filedb.files self._init = other_filedb._init self._files_saved = other_filedb._files_saved def GetFiles(self): return self.files def GetFilesNumber(self): return len(self.files) def GetFileBasename2id(self): return {os.path.basename(self.GetPath(_id)): _id for _id in self.GetAllIds()} def SaveFiles(self, filename): if not self._files_saved: try: filename = os.path.normpath(filename) json.dump(self.files, open(filename, 'w')) self._files_saved = True # log('FileDB saved to:', filename) return True except: return False else: return False def GetAllIds(self): return self.files.keys() def GetPathes2IdsMap(self): return {self.files[i]['path']: i for i in self.files} def LoadFiles(self, filename): try: self._init = False self._files_saved = False self.files = json.load(open(filename)) self.last_id = max([int(i) for i in self.files.keys()])+1 self._init = True self._files_saved = True except: return False return True class MetaDataBase: def __init__(self): self.meta = {} self.filedb = None def SetFileDB(self, filedb): self.filedb = filedb def SaveMeta(self, filename): # save json with meta info tmp = json.encoder.FLOAT_REPR json.encoder.FLOAT_REPR = lambda o: format(o, '.6f') json.dump(self.meta, open(filename, 'w'), sort_keys=True) json.encoder.FLOAT_REPR = tmp return True def LoadMeta(self, filename): try: self.meta = json.load(open(filename)) except: return False return True def SetMeta(self, _id, data): if not isinstance(data, dict): raise FileDataBaseException('data must be a dict '+str(data)) self.meta[_id] = data def AddMeta(self, _id, data): if not isinstance(data, dict): raise FileDataBaseException('data must be a dict '+str(data)) if _id in self.meta: self.meta[_id] = update_dict_recursively(self.meta[_id], data) else: self.meta[_id] = data def GetMeta(self, _id): if not _id in self.meta: raise FileDataBaseException('incorrect id ' + str(_id)) return self.meta[_id] def GetAllIds(self): return self.meta.keys()
makseq/testarium
testarium/filedb.py
Python
gpl-3.0
6,170
package lejos.utility; import lejos.hardware.LCD; /** * This class has been developed to use it in case of you have * to tests leJOS programs and you need to show in NXT Display data * but you don't need to design a User Interface. * * This class is very useful to debug algorithms in your NXT brick. * * @author Juan Antonio Brenha Moral * */ public class DebugMessages { private int lineCounter = 0;//Used to know in what row LCD is showing the messages private final int maximumLCDLines = 7;//NXT Brick has a LCD with 7 lines private int LCDLines = maximumLCDLines;//By default, Debug Messages show messages in maximumLCDLines private int delayMS = 250;//By default, the value to establish a delay private boolean delayEnabled = false;//By default, DebugMessages show messages without any delay /* * Constructors */ /* * Constructor with default features */ public DebugMessages(){ //Empty } /** * Constructor which the user establish in what line start showing messages * * @param init */ public DebugMessages(int init){ lineCounter = init; } /* * Getters & Setters */ /** * Set the number of lines to show in the screen. * * @param lines */ public void setLCDLines(int lines){ if(lines <= maximumLCDLines){ LCDLines = lines; } } /** * Enable/Disabled if you need to show output with delay * * @param de */ public void setDelayEnabled(boolean de){ delayEnabled = de; } /** * Set the delay measured in MS. * * @param dMs */ public void setDelay(int dMs){ delayMS = dMs; } /* * Public Methods */ /** * Show in NXT Screen a message * * @param message */ public void echo(String message){ if(lineCounter > LCDLines){ lineCounter = 0; LCD.clear(); }else{ LCD.drawString(message, 0, lineCounter); LCD.refresh(); lineCounter++; } if(delayEnabled){ try {Thread.sleep(delayMS);} catch (Exception e) {} } } /** * Show in NXT Screen a message * * @param message */ public void echo(int message){ if(lineCounter > LCDLines){ lineCounter = 0; LCD.clear(); }else{ LCD.drawInt(message, 0, lineCounter); LCD.refresh(); lineCounter++; } if(delayEnabled){ try {Thread.sleep(delayMS);} catch (Exception e) {} } } /** * Clear LCD */ public void clear(){ LCD.clear(); lineCounter = 0; if(delayEnabled){ try {Thread.sleep(delayMS);} catch (Exception e) {} } } }
SnakeSVx/ev3
Lejos/src/main/java/lejos/utility/DebugMessages.java
Java
gpl-3.0
2,602
<?php /** * @license http://opensource.org/licenses/gpl-license.php GNU Public License * @link https://github.com/bderidder/ldm-guild-website */ namespace LaDanse\RestBundle\Controller\GameData; use LaDanse\RestBundle\Common\AbstractRestController; use LaDanse\RestBundle\Common\JsonResponse; use LaDanse\RestBundle\Common\ResourceHelper; use LaDanse\ServicesBundle\Common\ServiceException; use LaDanse\ServicesBundle\Service\DTO\GameData\PatchRealm; use LaDanse\ServicesBundle\Service\GameData\GameDataService; use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * @Route("/realms") */ class RealmResource extends AbstractRestController { /** * @return Response * * @Route("/", name="getAllRealms", options = { "expose" = true }, methods={"GET"}) */ public function getAllRealmsAction() { /** @var GameDataService $gameDataService */ $gameDataService = $this->get(GameDataService::SERVICE_NAME); $realms = $gameDataService->getAllRealms(); return new JsonResponse($realms); } /** * @param Request $request * @return Response * @Route("/", name="postRealm", methods={"POST"}) */ public function postRealmAction(Request $request) { /** @var GameDataService $gameDataService */ $gameDataService = $this->get(GameDataService::SERVICE_NAME); try { $patchRealm = $this->getDtoFromContent($request, PatchRealm::class); $dtoRealm = $gameDataService->postRealm($patchRealm); return new JsonResponse($dtoRealm); } catch(ServiceException $serviceException) { return ResourceHelper::createErrorResponse( $request, $serviceException->getCode(), $serviceException->getMessage() ); } } }
bderidder/ldm-guild-website
src/LaDanse/RestBundle/Controller/GameData/RealmResource.php
PHP
gpl-3.0
1,963
"use strict"; var path = require("path"); var fs = require("fs"); var sourceMap = require('source-map'); var sourceMaps = {}; var coffeeMaps = {}; var registered = false; function registerErrorHandler() { if (registered) return; registered = true; function mungeStackFrame(frame) { if (frame.isNative()) return; var fileLocation = ''; var fileName; if (frame.isEval()) { fileName = frame.getScriptNameOrSourceURL(); } else { fileName = frame.getFileName(); } fileName = fileName || "<anonymous>"; var line = frame.getLineNumber(); var column = frame.getColumnNumber(); var map = sourceMaps[fileName]; // V8 gives 1-indexed column numbers, but source-map expects 0-indexed columns. var source = map && map.originalPositionFor({line: line, column: column - 1}); if (source && source.line) { line = source.line; column = source.column + 1; } else if (map) { fileName += " <generated>"; } else { return; } Object.defineProperties(frame, { getFileName: { value: function() { return fileName; } }, getLineNumber: { value: function() { return line; } }, getColumnNumber: { value: function() { return column; } } }); }; var old = Error.prepareStackTrace; if (!old) { // No existing handler? Use a default-ish one. // Copied from http://v8.googlecode.com/svn/branches/bleeding_edge/src/messages.js. old = function(err, stack) { var buf = []; for (var i = 0; i < stack.length; i++) { var line; try { line = " at " + stack[i].toString(); } catch (e) { try { line = "<error: " + e + ">"; } catch (e) { line = "<error>"; } } buf.push(line); } return (err.name || err.message ? err.name + ": " + (err.message || '') + "\n" : "") + // buf.join("\n") + "\n"; } } Error.prepareStackTrace = function(err, stack) { var frames = []; for (var i = 0; i < stack.length; i++) { var frame = stack[i]; if (frame.getFunction() == exports.run) break; mungeStackFrame(frame); frames.push(frame); } return old(err, stack); } } function run(options) { var subdir = "callbacks"; if (options.generators) subdir = options.fast ? "generators-fast" : "generators"; else if (options.fibers) subdir = options.fast ? "fibers-fast" : "fibers"; var transformer = "streamline/lib/" + subdir + "/transform"; var streamline = require(transformer).transform; function clone(obj) { return Object.keys(obj).reduce(function(val, key) { val[key] = obj[key]; return val; }, {}); } var streamliners = { _js: function(module, filename, code, prevMap) { registerErrorHandler(); if (!code) code = fs.readFileSync(filename, "utf8"); // If there's a shebang, strip it while preserving line count. var match = /^#!.*([^\u0000]*)$/.exec(code); if (match) code = match[1]; var cachedTransform = require("streamline/lib/compiler/compileSync").cachedTransformSync; var opts = clone(options); opts.sourceName = filename; opts.lines = opts.lines || 'sourcemap'; opts.prevMap = prevMap; var streamlined = options.cache ? cachedTransform(code, filename, streamline, opts) : streamline(code, opts); if (streamlined instanceof sourceMap.SourceNode) { var streamlined = streamlined.toStringWithSourceMap({ file: filename }); var map = streamlined.map; if (prevMap) { map.applySourceMap(prevMap, filename); } sourceMaps[filename] = new sourceMap.SourceMapConsumer(map.toString()); module._compile(streamlined.code, filename) } else { module._compile(streamlined, filename); } }, _coffee: function(module, filename, code) { registerErrorHandler(); if (!code) code = fs.readFileSync(filename, "utf8"); // Test for cached version so that we shortcircuit CS re-compilation, not just streamline pass var cachedTransform = require("streamline/lib/compiler/compileSync").cachedTransformSync; var opts = clone(options); opts.sourceName = filename; opts.lines = opts.lines || 'sourcemap'; var cached = cachedTransform(code, filename, streamline, opts, true); if (cached) return module._compile(cached, filename); // Compile the source CoffeeScript to regular JS. We make sure to // use the module's local instance of CoffeeScript if possible. var coffee = require("../util/require")("coffee-script", module.filename); var ground = coffee.compile(code, { filename: filename, sourceFiles: [module.filename], sourceMap: 1 }); if (ground.v3SourceMap) { var coffeeMap = new sourceMap.SourceMapConsumer(ground.v3SourceMap); coffeeMaps[filename] = coffeeMap; ground = ground.js; } // Then transform it like regular JS. streamliners._js(module, filename, ground, coffeeMap); } }; // Is CoffeeScript being used? Could be through our own _coffee binary, // through its coffee binary, or through require('coffee-script'). // The latter two add a .coffee require extension handler. var executable = path.basename(process.argv[0]); var coffeeRegistered = require.extensions['.coffee']; var coffeeExecuting = executable === '_coffee'; var coffeePresent = coffeeRegistered || coffeeExecuting; // Register require() extension handlers for ._js and ._coffee, but only // register ._coffee if CoffeeScript is being used. require.extensions['._js'] = streamliners._js; if (coffeePresent) require.extensions['._coffee'] = streamliners._coffee; // If we were asked to register extension handlers only, we're done. if (options.registerOnly) return; // Otherwise, we're being asked to execute (run) a file too. var filename = process.argv[1]; // If we're running via _coffee, we should run CoffeeScript ourselves so // that it can register its regular .coffee handler. We make sure to do // this relative to the caller's working directory instead of from here. // (CoffeeScript 1.7+ no longer registers a handler automatically.) if (coffeeExecuting && !coffeeRegistered) { var coffee = require("../util/require")("coffee-script"); if (typeof coffee.register === 'function') { coffee.register(); } } // We'll make that file the "main" module by reusing the current one. var mainModule = require.main; // Clear the main module's require cache. if (mainModule.moduleCache) { mainModule.moduleCache = {}; } // Set the module's paths and filename. Luckily, Node exposes its native // helper functions to resolve these guys! // https://github.com/joyent/node/blob/master/lib/module.js // Except we need to tell Node that these are paths, not native modules. filename = path.resolve(filename || '.'); mainModule.filename = filename = require("module")._resolveFilename(filename); mainModule.paths = require("module")._nodeModulePaths(path.dirname(filename)); // if node is installed with NVM, NODE_PATH is not defined so we add it to our paths if (!process.env.NODE_PATH) mainModule.paths.push(path.join(__dirname, '../../..')); // And update the process argv and execPath too. process.argv.splice(1, 1, filename) //process.execPath = filename; // Load the target file and evaluate it as the main module. // The input path should have been resolved to a file, so use its extension. // If the file doesn't have an extension (e.g. scripts with a shebang), // go by what executable this was called as. var ext = path.extname(filename) || (coffeeExecuting ? '._coffee' : '._js'); require.extensions[ext](mainModule, filename); } module.exports.run = run;
phun-ky/heritage
node_modules/neo4j/node_modules/streamline/lib/compiler/underscored.js
JavaScript
gpl-3.0
7,491
RSpec.describe Admission::Status do def privilege context @fake_privilege_klass ||= Struct.new(:context, :inherited) @fake_privilege_klass.new context end describe '#new' do it 'sets privileges to nil' do instance = Admission::Status.new :person, nil, :rules, :arbiter expect(instance).to have_inst_vars( person: :person, privileges: nil, rules: :rules, arbiter: :arbiter ) instance = Admission::Status.new :person, [], :rules, :arbiter expect(instance).to have_inst_vars( person: :person, privileges: nil, rules: :rules, arbiter: :arbiter ) end it 'sets privileges and freezes them' do instance = Admission::Status.new :person, [:czech], :rules, :arbiter expect(instance).to have_inst_vars( person: :person, privileges: [:czech], rules: :rules, arbiter: :arbiter ) expect(instance.privileges).to be_frozen end it 'sorts privileges by context' do instance = Admission::Status.new :person, [ privilege(nil), privilege(:czech), privilege(15), privilege(:czech), privilege({a: 15}), privilege({a: {f: 1}}), privilege(nil), privilege({a: 15}), ], :rules, :arbiter expect(instance.privileges.map(&:context)).to eq([ nil, nil, :czech, :czech, 15, {:a=>15}, {:a=>15}, {:a=>{:f=>1}} ]) expect(instance.privileges).to be_frozen end end describe '#allowed_in_contexts' do it 'returns empty list for blank privileges' do instance = Admission::Status.new :person, nil, :rules, :arbiter expect(instance.allowed_in_contexts).to eq([]) end it 'lists only context for which any privilege allows it' do priv1 = privilege text: '1' priv2 = privilege text: '2' rules = {can: {priv1 => true}} instance = Admission::Status.new nil, [priv1, priv2], rules, Admission::Arbitration list = instance.allowed_in_contexts :can expect(list).to eq([priv1.context]) end end end
doooby/admission
spec/unit/status_spec.rb
Ruby
gpl-3.0
2,166
<?php class ControllerSettingSetting extends Controller { private $error = array(); public function index() { $this->load->language('setting/setting'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('setting/setting'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { $this->model_setting_setting->editSetting('config', $this->request->post); if ($this->config->get('config_currency_auto')) { $this->load->model('localisation/currency'); $this->model_localisation_currency->updateCurrencies(); } $this->session->data['success'] = $this->language->get('text_success'); $this->redirect($this->url->link('setting/store', 'token=' . $this->session->data['token'], 'SSL')); } $this->data['heading_title'] = $this->language->get('heading_title'); $this->data['text_select'] = $this->language->get('text_select'); $this->data['text_none'] = $this->language->get('text_none'); $this->data['text_yes'] = $this->language->get('text_yes'); $this->data['text_no'] = $this->language->get('text_no'); $this->data['text_items'] = $this->language->get('text_items'); $this->data['text_product'] = $this->language->get('text_product'); $this->data['text_voucher'] = $this->language->get('text_voucher'); $this->data['text_tax'] = $this->language->get('text_tax'); $this->data['text_account'] = $this->language->get('text_account'); $this->data['text_checkout'] = $this->language->get('text_checkout'); $this->data['text_stock'] = $this->language->get('text_stock'); $this->data['text_affiliate'] = $this->language->get('text_affiliate'); $this->data['text_return'] = $this->language->get('text_return'); $this->data['text_image_manager'] = $this->language->get('text_image_manager'); $this->data['text_browse'] = $this->language->get('text_browse'); $this->data['text_clear'] = $this->language->get('text_clear'); $this->data['text_shipping'] = $this->language->get('text_shipping'); $this->data['text_payment'] = $this->language->get('text_payment'); $this->data['text_mail'] = $this->language->get('text_mail'); $this->data['text_smtp'] = $this->language->get('text_smtp'); $this->data['entry_name'] = $this->language->get('entry_name'); $this->data['entry_owner'] = $this->language->get('entry_owner'); $this->data['entry_address'] = $this->language->get('entry_address'); $this->data['entry_email'] = $this->language->get('entry_email'); $this->data['entry_telephone'] = $this->language->get('entry_telephone'); $this->data['entry_fax'] = $this->language->get('entry_fax'); $this->data['entry_title'] = $this->language->get('entry_title'); $this->data['entry_meta_description'] = $this->language->get('entry_meta_description'); $this->data['entry_layout'] = $this->language->get('entry_layout'); $this->data['entry_template'] = $this->language->get('entry_template'); $this->data['entry_country'] = $this->language->get('entry_country'); $this->data['entry_zone'] = $this->language->get('entry_zone'); $this->data['entry_language'] = $this->language->get('entry_language'); $this->data['entry_admin_language'] = $this->language->get('entry_admin_language'); $this->data['entry_currency'] = $this->language->get('entry_currency'); $this->data['entry_currency_auto'] = $this->language->get('entry_currency_auto'); $this->data['entry_length_class'] = $this->language->get('entry_length_class'); $this->data['entry_weight_class'] = $this->language->get('entry_weight_class'); $this->data['entry_catalog_limit'] = $this->language->get('entry_catalog_limit'); $this->data['entry_admin_limit'] = $this->language->get('entry_admin_limit'); $this->data['entry_product_count'] = $this->language->get('entry_product_count'); $this->data['entry_review'] = $this->language->get('entry_review'); $this->data['entry_download'] = $this->language->get('entry_download'); $this->data['entry_upload_allowed'] = $this->language->get('entry_upload_allowed'); $this->data['entry_voucher_min'] = $this->language->get('entry_voucher_min'); $this->data['entry_voucher_max'] = $this->language->get('entry_voucher_max'); $this->data['entry_tax'] = $this->language->get('entry_tax'); $this->data['entry_vat'] = $this->language->get('entry_vat'); $this->data['entry_tax_default'] = $this->language->get('entry_tax_default'); $this->data['entry_tax_customer'] = $this->language->get('entry_tax_customer'); $this->data['entry_customer_online'] = $this->language->get('entry_customer_online'); $this->data['entry_customer_group'] = $this->language->get('entry_customer_group'); $this->data['entry_customer_group_display'] = $this->language->get('entry_customer_group_display'); $this->data['entry_customer_price'] = $this->language->get('entry_customer_price'); $this->data['entry_account'] = $this->language->get('entry_account'); $this->data['entry_cart_weight'] = $this->language->get('entry_cart_weight'); $this->data['entry_guest_checkout'] = $this->language->get('entry_guest_checkout'); $this->data['entry_checkout'] = $this->language->get('entry_checkout'); $this->data['entry_order_edit'] = $this->language->get('entry_order_edit'); $this->data['entry_invoice_prefix'] = $this->language->get('entry_invoice_prefix'); $this->data['entry_order_status'] = $this->language->get('entry_order_status'); $this->data['entry_complete_status'] = $this->language->get('entry_complete_status'); $this->data['entry_stock_display'] = $this->language->get('entry_stock_display'); $this->data['entry_stock_warning'] = $this->language->get('entry_stock_warning'); $this->data['entry_stock_checkout'] = $this->language->get('entry_stock_checkout'); $this->data['entry_stock_status'] = $this->language->get('entry_stock_status'); $this->data['entry_affiliate'] = $this->language->get('entry_affiliate'); $this->data['entry_commission'] = $this->language->get('entry_commission'); $this->data['entry_return_status'] = $this->language->get('entry_return_status'); $this->data['entry_logo'] = $this->language->get('entry_logo'); $this->data['entry_icon'] = $this->language->get('entry_icon'); $this->data['entry_image_category'] = $this->language->get('entry_image_category'); $this->data['entry_image_thumb'] = $this->language->get('entry_image_thumb'); $this->data['entry_image_popup'] = $this->language->get('entry_image_popup'); $this->data['entry_image_product'] = $this->language->get('entry_image_product'); $this->data['entry_image_additional'] = $this->language->get('entry_image_additional'); $this->data['entry_image_related'] = $this->language->get('entry_image_related'); $this->data['entry_image_compare'] = $this->language->get('entry_image_compare'); $this->data['entry_image_wishlist'] = $this->language->get('entry_image_wishlist'); $this->data['entry_image_cart'] = $this->language->get('entry_image_cart'); $this->data['entry_mail_protocol'] = $this->language->get('entry_mail_protocol'); $this->data['entry_mail_parameter'] = $this->language->get('entry_mail_parameter'); $this->data['entry_smtp_host'] = $this->language->get('entry_smtp_host'); $this->data['entry_smtp_username'] = $this->language->get('entry_smtp_username'); $this->data['entry_smtp_password'] = $this->language->get('entry_smtp_password'); $this->data['entry_smtp_port'] = $this->language->get('entry_smtp_port'); $this->data['entry_smtp_timeout'] = $this->language->get('entry_smtp_timeout'); $this->data['entry_alert_mail'] = $this->language->get('entry_alert_mail'); $this->data['entry_account_mail'] = $this->language->get('entry_account_mail'); $this->data['entry_alert_emails'] = $this->language->get('entry_alert_emails'); $this->data['entry_fraud_detection'] = $this->language->get('entry_fraud_detection'); $this->data['entry_fraud_key'] = $this->language->get('entry_fraud_key'); $this->data['entry_fraud_score'] = $this->language->get('entry_fraud_score'); $this->data['entry_fraud_status'] = $this->language->get('entry_fraud_status'); $this->data['entry_use_ssl'] = $this->language->get('entry_use_ssl'); $this->data['entry_maintenance'] = $this->language->get('entry_maintenance'); $this->data['entry_encryption'] = $this->language->get('entry_encryption'); $this->data['entry_seo_url'] = $this->language->get('entry_seo_url'); $this->data['entry_compression'] = $this->language->get('entry_compression'); $this->data['entry_error_display'] = $this->language->get('entry_error_display'); $this->data['entry_error_log'] = $this->language->get('entry_error_log'); $this->data['entry_error_filename'] = $this->language->get('entry_error_filename'); $this->data['entry_google_analytics'] = $this->language->get('entry_google_analytics'); $this->data['button_save'] = $this->language->get('button_save'); $this->data['button_cancel'] = $this->language->get('button_cancel'); $this->data['tab_general'] = $this->language->get('tab_general'); $this->data['tab_store'] = $this->language->get('tab_store'); $this->data['tab_local'] = $this->language->get('tab_local'); $this->data['tab_option'] = $this->language->get('tab_option'); $this->data['tab_image'] = $this->language->get('tab_image'); $this->data['tab_mail'] = $this->language->get('tab_mail'); $this->data['tab_fraud'] = $this->language->get('tab_fraud'); $this->data['tab_server'] = $this->language->get('tab_server'); if (isset($this->error['warning'])) { $this->data['error_warning'] = $this->error['warning']; } else { $this->data['error_warning'] = ''; } if (isset($this->error['name'])) { $this->data['error_name'] = $this->error['name']; } else { $this->data['error_name'] = ''; } if (isset($this->error['owner'])) { $this->data['error_owner'] = $this->error['owner']; } else { $this->data['error_owner'] = ''; } if (isset($this->error['address'])) { $this->data['error_address'] = $this->error['address']; } else { $this->data['error_address'] = ''; } if (isset($this->error['email'])) { $this->data['error_email'] = $this->error['email']; } else { $this->data['error_email'] = ''; } if (isset($this->error['telephone'])) { $this->data['error_telephone'] = $this->error['telephone']; } else { $this->data['error_telephone'] = ''; } if (isset($this->error['title'])) { $this->data['error_title'] = $this->error['title']; } else { $this->data['error_title'] = ''; } if (isset($this->error['customer_group_display'])) { $this->data['error_customer_group_display'] = $this->error['customer_group_display']; } else { $this->data['error_customer_group_display'] = ''; } if (isset($this->error['voucher_min'])) { $this->data['error_voucher_min'] = $this->error['voucher_min']; } else { $this->data['error_voucher_min'] = ''; } if (isset($this->error['voucher_max'])) { $this->data['error_voucher_max'] = $this->error['voucher_max']; } else { $this->data['error_voucher_max'] = ''; } if (isset($this->error['image_category'])) { $this->data['error_image_category'] = $this->error['image_category']; } else { $this->data['error_image_category'] = ''; } if (isset($this->error['image_thumb'])) { $this->data['error_image_thumb'] = $this->error['image_thumb']; } else { $this->data['error_image_thumb'] = ''; } if (isset($this->error['image_popup'])) { $this->data['error_image_popup'] = $this->error['image_popup']; } else { $this->data['error_image_popup'] = ''; } if (isset($this->error['image_product'])) { $this->data['error_image_product'] = $this->error['image_product']; } else { $this->data['error_image_product'] = ''; } if (isset($this->error['image_additional'])) { $this->data['error_image_additional'] = $this->error['image_additional']; } else { $this->data['error_image_additional'] = ''; } if (isset($this->error['image_related'])) { $this->data['error_image_related'] = $this->error['image_related']; } else { $this->data['error_image_related'] = ''; } if (isset($this->error['image_compare'])) { $this->data['error_image_compare'] = $this->error['image_compare']; } else { $this->data['error_image_compare'] = ''; } if (isset($this->error['image_wishlist'])) { $this->data['error_image_wishlist'] = $this->error['image_wishlist']; } else { $this->data['error_image_wishlist'] = ''; } if (isset($this->error['image_cart'])) { $this->data['error_image_cart'] = $this->error['image_cart']; } else { $this->data['error_image_cart'] = ''; } if (isset($this->error['error_filename'])) { $this->data['error_error_filename'] = $this->error['error_filename']; } else { $this->data['error_error_filename'] = ''; } if (isset($this->error['catalog_limit'])) { $this->data['error_catalog_limit'] = $this->error['catalog_limit']; } else { $this->data['error_catalog_limit'] = ''; } if (isset($this->error['admin_limit'])) { $this->data['error_admin_limit'] = $this->error['admin_limit']; } else { $this->data['error_admin_limit'] = ''; } $this->data['breadcrumbs'] = array(); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => false ); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('setting/setting', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => ' :: ' ); if (isset($this->session->data['success'])) { $this->data['success'] = $this->session->data['success']; unset($this->session->data['success']); } else { $this->data['success'] = ''; } $this->data['action'] = $this->url->link('setting/setting', 'token=' . $this->session->data['token'], 'SSL'); $this->data['cancel'] = $this->url->link('setting/store', 'token=' . $this->session->data['token'], 'SSL'); $this->data['token'] = $this->session->data['token']; if (isset($this->request->post['config_name'])) { $this->data['config_name'] = $this->request->post['config_name']; } else { $this->data['config_name'] = $this->config->get('config_name'); } if (isset($this->request->post['config_owner'])) { $this->data['config_owner'] = $this->request->post['config_owner']; } else { $this->data['config_owner'] = $this->config->get('config_owner'); } if (isset($this->request->post['config_address'])) { $this->data['config_address'] = $this->request->post['config_address']; } else { $this->data['config_address'] = $this->config->get('config_address'); } if (isset($this->request->post['config_email'])) { $this->data['config_email'] = $this->request->post['config_email']; } else { $this->data['config_email'] = $this->config->get('config_email'); } if (isset($this->request->post['config_telephone'])) { $this->data['config_telephone'] = $this->request->post['config_telephone']; } else { $this->data['config_telephone'] = $this->config->get('config_telephone'); } if (isset($this->request->post['config_fax'])) { $this->data['config_fax'] = $this->request->post['config_fax']; } else { $this->data['config_fax'] = $this->config->get('config_fax'); } if (isset($this->request->post['config_title'])) { $this->data['config_title'] = $this->request->post['config_title']; } else { $this->data['config_title'] = $this->config->get('config_title'); } if (isset($this->request->post['config_meta_description'])) { $this->data['config_meta_description'] = $this->request->post['config_meta_description']; } else { $this->data['config_meta_description'] = $this->config->get('config_meta_description'); } if (isset($this->request->post['config_layout_id'])) { $this->data['config_layout_id'] = $this->request->post['config_layout_id']; } else { $this->data['config_layout_id'] = $this->config->get('config_layout_id'); } $this->load->model('design/layout'); $this->data['layouts'] = $this->model_design_layout->getLayouts(); if (isset($this->request->post['config_template'])) { $this->data['config_template'] = $this->request->post['config_template']; } else { $this->data['config_template'] = $this->config->get('config_template'); } $this->data['templates'] = array(); $directories = glob(DIR_CATALOG . 'view/theme/*', GLOB_ONLYDIR); $local_directories = glob(DIR_LOCAL_CATALOG . 'view/theme/*', GLOB_ONLYDIR); $directories = array_merge($directories, $local_directories); foreach ($directories as $directory) { $this->data['templates'][] = basename($directory); } if (isset($this->request->post['config_country_id'])) { $this->data['config_country_id'] = $this->request->post['config_country_id']; } else { $this->data['config_country_id'] = $this->config->get('config_country_id'); } $this->load->model('localisation/country'); $this->data['countries'] = $this->model_localisation_country->getCountries(); if (isset($this->request->post['config_zone_id'])) { $this->data['config_zone_id'] = $this->request->post['config_zone_id']; } else { $this->data['config_zone_id'] = $this->config->get('config_zone_id'); } if (isset($this->request->post['config_language'])) { $this->data['config_language'] = $this->request->post['config_language']; } else { $this->data['config_language'] = $this->config->get('config_language'); } $this->load->model('localisation/language'); $this->data['languages'] = $this->model_localisation_language->getLanguages(); if (isset($this->request->post['config_admin_language'])) { $this->data['config_admin_language'] = $this->request->post['config_admin_language']; } else { $this->data['config_admin_language'] = $this->config->get('config_admin_language'); } if (isset($this->request->post['config_currency'])) { $this->data['config_currency'] = $this->request->post['config_currency']; } else { $this->data['config_currency'] = $this->config->get('config_currency'); } if (isset($this->request->post['config_currency_auto'])) { $this->data['config_currency_auto'] = $this->request->post['config_currency_auto']; } else { $this->data['config_currency_auto'] = $this->config->get('config_currency_auto'); } $this->load->model('localisation/currency'); $this->data['currencies'] = $this->model_localisation_currency->getCurrencies(); if (isset($this->request->post['config_length_class_id'])) { $this->data['config_length_class_id'] = $this->request->post['config_length_class_id']; } else { $this->data['config_length_class_id'] = $this->config->get('config_length_class_id'); } $this->load->model('localisation/length_class'); $this->data['length_classes'] = $this->model_localisation_length_class->getLengthClasses(); if (isset($this->request->post['config_weight_class_id'])) { $this->data['config_weight_class_id'] = $this->request->post['config_weight_class_id']; } else { $this->data['config_weight_class_id'] = $this->config->get('config_weight_class_id'); } $this->load->model('localisation/weight_class'); $this->data['weight_classes'] = $this->model_localisation_weight_class->getWeightClasses(); if (isset($this->request->post['config_catalog_limit'])) { $this->data['config_catalog_limit'] = $this->request->post['config_catalog_limit']; } else { $this->data['config_catalog_limit'] = $this->config->get('config_catalog_limit'); } if (isset($this->request->post['config_admin_limit'])) { $this->data['config_admin_limit'] = $this->request->post['config_admin_limit']; } else { $this->data['config_admin_limit'] = $this->config->get('config_admin_limit'); } if (isset($this->request->post['config_product_count'])) { $this->data['config_product_count'] = $this->request->post['config_product_count']; } else { $this->data['config_product_count'] = $this->config->get('config_product_count'); } if (isset($this->request->post['config_review_status'])) { $this->data['config_review_status'] = $this->request->post['config_review_status']; } else { $this->data['config_review_status'] = $this->config->get('config_review_status'); } if (isset($this->request->post['config_download'])) { $this->data['config_download'] = $this->request->post['config_download']; } else { $this->data['config_download'] = $this->config->get('config_download'); } if (isset($this->request->post['config_upload_allowed'])) { $this->data['config_upload_allowed'] = $this->request->post['config_upload_allowed']; } else { $this->data['config_upload_allowed'] = $this->config->get('config_upload_allowed'); } if (isset($this->request->post['config_voucher_min'])) { $this->data['config_voucher_min'] = $this->request->post['config_voucher_min']; } else { $this->data['config_voucher_min'] = $this->config->get('config_voucher_min'); } if (isset($this->request->post['config_voucher_max'])) { $this->data['config_voucher_max'] = $this->request->post['config_voucher_max']; } else { $this->data['config_voucher_max'] = $this->config->get('config_voucher_max'); } if (isset($this->request->post['config_tax'])) { $this->data['config_tax'] = $this->request->post['config_tax']; } else { $this->data['config_tax'] = $this->config->get('config_tax'); } if (isset($this->request->post['config_vat'])) { $this->data['config_vat'] = $this->request->post['config_vat']; } else { $this->data['config_vat'] = $this->config->get('config_vat'); } if (isset($this->request->post['config_tax_default'])) { $this->data['config_tax_default'] = $this->request->post['config_tax_default']; } else { $this->data['config_tax_default'] = $this->config->get('config_tax_default'); } if (isset($this->request->post['config_tax_customer'])) { $this->data['config_tax_customer'] = $this->request->post['config_tax_customer']; } else { $this->data['config_tax_customer'] = $this->config->get('config_tax_customer'); } if (isset($this->request->post['config_customer_online'])) { $this->data['config_customer_online'] = $this->request->post['config_customer_online']; } else { $this->data['config_customer_online'] = $this->config->get('config_customer_online'); } if (isset($this->request->post['config_customer_group_id'])) { $this->data['config_customer_group_id'] = $this->request->post['config_customer_group_id']; } else { $this->data['config_customer_group_id'] = $this->config->get('config_customer_group_id'); } $this->load->model('sale/customer_group'); $this->data['customer_groups'] = $this->model_sale_customer_group->getCustomerGroups(); if (isset($this->request->post['config_customer_group_display'])) { $this->data['config_customer_group_display'] = $this->request->post['config_customer_group_display']; } elseif ($this->config->get('config_customer_group_display')) { $this->data['config_customer_group_display'] = $this->config->get('config_customer_group_display'); } else { $this->data['config_customer_group_display'] = array(); } if (isset($this->request->post['config_customer_price'])) { $this->data['config_customer_price'] = $this->request->post['config_customer_price']; } else { $this->data['config_customer_price'] = $this->config->get('config_customer_price'); } if (isset($this->request->post['config_account_id'])) { $this->data['config_account_id'] = $this->request->post['config_account_id']; } else { $this->data['config_account_id'] = $this->config->get('config_account_id'); } $this->load->model('catalog/information'); $this->data['informations'] = $this->model_catalog_information->getInformations(); if (isset($this->request->post['config_cart_weight'])) { $this->data['config_cart_weight'] = $this->request->post['config_cart_weight']; } else { $this->data['config_cart_weight'] = $this->config->get('config_cart_weight'); } if (isset($this->request->post['config_guest_checkout'])) { $this->data['config_guest_checkout'] = $this->request->post['config_guest_checkout']; } else { $this->data['config_guest_checkout'] = $this->config->get('config_guest_checkout'); } if (isset($this->request->post['config_checkout_id'])) { $this->data['config_checkout_id'] = $this->request->post['config_checkout_id']; } else { $this->data['config_checkout_id'] = $this->config->get('config_checkout_id'); } if (isset($this->request->post['config_order_edit'])) { $this->data['config_order_edit'] = $this->request->post['config_order_edit']; } elseif ($this->config->get('config_order_edit')) { $this->data['config_order_edit'] = $this->config->get('config_order_edit'); } else { $this->data['config_order_edit'] = 7; } if (isset($this->request->post['config_invoice_prefix'])) { $this->data['config_invoice_prefix'] = $this->request->post['config_invoice_prefix']; } elseif ($this->config->get('config_invoice_prefix')) { $this->data['config_invoice_prefix'] = $this->config->get('config_invoice_prefix'); } else { $this->data['config_invoice_prefix'] = 'INV-' . date('Y') . '-00'; } if (isset($this->request->post['config_order_status_id'])) { $this->data['config_order_status_id'] = $this->request->post['config_order_status_id']; } else { $this->data['config_order_status_id'] = $this->config->get('config_order_status_id'); } if (isset($this->request->post['config_complete_status_id'])) { $this->data['config_complete_status_id'] = $this->request->post['config_complete_status_id']; } else { $this->data['config_complete_status_id'] = $this->config->get('config_complete_status_id'); } $this->load->model('localisation/order_status'); $this->data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses(); if (isset($this->request->post['config_stock_display'])) { $this->data['config_stock_display'] = $this->request->post['config_stock_display']; } else { $this->data['config_stock_display'] = $this->config->get('config_stock_display'); } if (isset($this->request->post['config_stock_warning'])) { $this->data['config_stock_warning'] = $this->request->post['config_stock_warning']; } else { $this->data['config_stock_warning'] = $this->config->get('config_stock_warning'); } if (isset($this->request->post['config_stock_checkout'])) { $this->data['config_stock_checkout'] = $this->request->post['config_stock_checkout']; } else { $this->data['config_stock_checkout'] = $this->config->get('config_stock_checkout'); } if (isset($this->request->post['config_stock_status_id'])) { $this->data['config_stock_status_id'] = $this->request->post['config_stock_status_id']; } else { $this->data['config_stock_status_id'] = $this->config->get('config_stock_status_id'); } $this->load->model('localisation/stock_status'); $this->data['stock_statuses'] = $this->model_localisation_stock_status->getStockStatuses(); if (isset($this->request->post['config_affiliate_id'])) { $this->data['config_affiliate_id'] = $this->request->post['config_affiliate_id']; } else { $this->data['config_affiliate_id'] = $this->config->get('config_affiliate_id'); } if (isset($this->request->post['config_commission'])) { $this->data['config_commission'] = $this->request->post['config_commission']; } elseif ($this->config->has('config_commission')) { $this->data['config_commission'] = $this->config->get('config_commission'); } else { $this->data['config_commission'] = '5.00'; } if (isset($this->request->post['config_return_status_id'])) { $this->data['config_return_status_id'] = $this->request->post['config_return_status_id']; } else { $this->data['config_return_status_id'] = $this->config->get('config_return_status_id'); } $this->load->model('localisation/return_status'); $this->data['return_statuses'] = $this->model_localisation_return_status->getReturnStatuses(); $this->load->model('tool/image'); if (isset($this->request->post['config_logo'])) { $this->data['config_logo'] = $this->request->post['config_logo']; } else { $this->data['config_logo'] = $this->config->get('config_logo'); } if ($this->config->get('config_logo') && file_exists(DIR_IMAGE . $this->config->get('config_logo')) && is_file(DIR_IMAGE . $this->config->get('config_logo'))) { $this->data['logo'] = $this->model_tool_image->resize($this->config->get('config_logo'), 100, 100); } else { $this->data['logo'] = $this->model_tool_image->resize('no_image.jpg', 100, 100); } if (isset($this->request->post['config_icon'])) { $this->data['config_icon'] = $this->request->post['config_icon']; } else { $this->data['config_icon'] = $this->config->get('config_icon'); } if ($this->config->get('config_icon') && file_exists(DIR_IMAGE . $this->config->get('config_icon')) && is_file(DIR_IMAGE . $this->config->get('config_icon'))) { $this->data['icon'] = $this->model_tool_image->resize($this->config->get('config_icon'), 100, 100); } else { $this->data['icon'] = $this->model_tool_image->resize('no_image.jpg', 100, 100); } $this->data['no_image'] = $this->model_tool_image->resize('no_image.jpg', 100, 100); if (isset($this->request->post['config_image_category_width'])) { $this->data['config_image_category_width'] = $this->request->post['config_image_category_width']; } else { $this->data['config_image_category_width'] = $this->config->get('config_image_category_width'); } if (isset($this->request->post['config_image_category_height'])) { $this->data['config_image_category_height'] = $this->request->post['config_image_category_height']; } else { $this->data['config_image_category_height'] = $this->config->get('config_image_category_height'); } if (isset($this->request->post['config_image_thumb_width'])) { $this->data['config_image_thumb_width'] = $this->request->post['config_image_thumb_width']; } else { $this->data['config_image_thumb_width'] = $this->config->get('config_image_thumb_width'); } if (isset($this->request->post['config_image_thumb_height'])) { $this->data['config_image_thumb_height'] = $this->request->post['config_image_thumb_height']; } else { $this->data['config_image_thumb_height'] = $this->config->get('config_image_thumb_height'); } if (isset($this->request->post['config_image_popup_width'])) { $this->data['config_image_popup_width'] = $this->request->post['config_image_popup_width']; } else { $this->data['config_image_popup_width'] = $this->config->get('config_image_popup_width'); } if (isset($this->request->post['config_image_popup_height'])) { $this->data['config_image_popup_height'] = $this->request->post['config_image_popup_height']; } else { $this->data['config_image_popup_height'] = $this->config->get('config_image_popup_height'); } if (isset($this->request->post['config_image_product_width'])) { $this->data['config_image_product_width'] = $this->request->post['config_image_product_width']; } else { $this->data['config_image_product_width'] = $this->config->get('config_image_product_width'); } if (isset($this->request->post['config_image_product_height'])) { $this->data['config_image_product_height'] = $this->request->post['config_image_product_height']; } else { $this->data['config_image_product_height'] = $this->config->get('config_image_product_height'); } if (isset($this->request->post['config_image_additional_width'])) { $this->data['config_image_additional_width'] = $this->request->post['config_image_additional_width']; } else { $this->data['config_image_additional_width'] = $this->config->get('config_image_additional_width'); } if (isset($this->request->post['config_image_additional_height'])) { $this->data['config_image_additional_height'] = $this->request->post['config_image_additional_height']; } else { $this->data['config_image_additional_height'] = $this->config->get('config_image_additional_height'); } if (isset($this->request->post['config_image_related_width'])) { $this->data['config_image_related_width'] = $this->request->post['config_image_related_width']; } else { $this->data['config_image_related_width'] = $this->config->get('config_image_related_width'); } if (isset($this->request->post['config_image_related_height'])) { $this->data['config_image_related_height'] = $this->request->post['config_image_related_height']; } else { $this->data['config_image_related_height'] = $this->config->get('config_image_related_height'); } if (isset($this->request->post['config_image_compare_width'])) { $this->data['config_image_compare_width'] = $this->request->post['config_image_compare_width']; } else { $this->data['config_image_compare_width'] = $this->config->get('config_image_compare_width'); } if (isset($this->request->post['config_image_compare_height'])) { $this->data['config_image_compare_height'] = $this->request->post['config_image_compare_height']; } else { $this->data['config_image_compare_height'] = $this->config->get('config_image_compare_height'); } if (isset($this->request->post['config_image_wishlist_width'])) { $this->data['config_image_wishlist_width'] = $this->request->post['config_image_wishlist_width']; } else { $this->data['config_image_wishlist_width'] = $this->config->get('config_image_wishlist_width'); } if (isset($this->request->post['config_image_wishlist_height'])) { $this->data['config_image_wishlist_height'] = $this->request->post['config_image_wishlist_height']; } else { $this->data['config_image_wishlist_height'] = $this->config->get('config_image_wishlist_height'); } if (isset($this->request->post['config_image_cart_width'])) { $this->data['config_image_cart_width'] = $this->request->post['config_image_cart_width']; } else { $this->data['config_image_cart_width'] = $this->config->get('config_image_cart_width'); } if (isset($this->request->post['config_image_cart_height'])) { $this->data['config_image_cart_height'] = $this->request->post['config_image_cart_height']; } else { $this->data['config_image_cart_height'] = $this->config->get('config_image_cart_height'); } if (isset($this->request->post['config_mail_protocol'])) { $this->data['config_mail_protocol'] = $this->request->post['config_mail_protocol']; } else { $this->data['config_mail_protocol'] = $this->config->get('config_mail_protocol'); } if (isset($this->request->post['config_mail_parameter'])) { $this->data['config_mail_parameter'] = $this->request->post['config_mail_parameter']; } else { $this->data['config_mail_parameter'] = $this->config->get('config_mail_parameter'); } if (isset($this->request->post['config_smtp_host'])) { $this->data['config_smtp_host'] = $this->request->post['config_smtp_host']; } else { $this->data['config_smtp_host'] = $this->config->get('config_smtp_host'); } if (isset($this->request->post['config_smtp_username'])) { $this->data['config_smtp_username'] = $this->request->post['config_smtp_username']; } else { $this->data['config_smtp_username'] = $this->config->get('config_smtp_username'); } if (isset($this->request->post['config_smtp_password'])) { $this->data['config_smtp_password'] = $this->request->post['config_smtp_password']; } else { $this->data['config_smtp_password'] = $this->config->get('config_smtp_password'); } if (isset($this->request->post['config_smtp_port'])) { $this->data['config_smtp_port'] = $this->request->post['config_smtp_port']; } elseif ($this->config->get('config_smtp_port')) { $this->data['config_smtp_port'] = $this->config->get('config_smtp_port'); } else { $this->data['config_smtp_port'] = 25; } if (isset($this->request->post['config_smtp_timeout'])) { $this->data['config_smtp_timeout'] = $this->request->post['config_smtp_timeout']; } elseif ($this->config->get('config_smtp_timeout')) { $this->data['config_smtp_timeout'] = $this->config->get('config_smtp_timeout'); } else { $this->data['config_smtp_timeout'] = 5; } if (isset($this->request->post['config_alert_mail'])) { $this->data['config_alert_mail'] = $this->request->post['config_alert_mail']; } else { $this->data['config_alert_mail'] = $this->config->get('config_alert_mail'); } if (isset($this->request->post['config_account_mail'])) { $this->data['config_account_mail'] = $this->request->post['config_account_mail']; } else { $this->data['config_account_mail'] = $this->config->get('config_account_mail'); } if (isset($this->request->post['config_alert_emails'])) { $this->data['config_alert_emails'] = $this->request->post['config_alert_emails']; } else { $this->data['config_alert_emails'] = $this->config->get('config_alert_emails'); } if (isset($this->request->post['config_fraud_detection'])) { $this->data['config_fraud_detection'] = $this->request->post['config_fraud_detection']; } else { $this->data['config_fraud_detection'] = $this->config->get('config_fraud_detection'); } if (isset($this->request->post['config_fraud_key'])) { $this->data['config_fraud_key'] = $this->request->post['config_fraud_key']; } else { $this->data['config_fraud_key'] = $this->config->get('config_fraud_key'); } if (isset($this->request->post['config_fraud_score'])) { $this->data['config_fraud_score'] = $this->request->post['config_fraud_score']; } else { $this->data['config_fraud_score'] = $this->config->get('config_fraud_score'); } if (isset($this->request->post['config_fraud_status_id'])) { $this->data['config_fraud_status_id'] = $this->request->post['config_fraud_status_id']; } else { $this->data['config_fraud_status_id'] = $this->config->get('config_fraud_status_id'); } if (isset($this->request->post['config_use_ssl'])) { $this->data['config_use_ssl'] = $this->request->post['config_use_ssl']; } else { $this->data['config_use_ssl'] = $this->config->get('config_use_ssl'); } if (isset($this->request->post['config_seo_url'])) { $this->data['config_seo_url'] = $this->request->post['config_seo_url']; } else { $this->data['config_seo_url'] = $this->config->get('config_seo_url'); } if (isset($this->request->post['config_maintenance'])) { $this->data['config_maintenance'] = $this->request->post['config_maintenance']; } else { $this->data['config_maintenance'] = $this->config->get('config_maintenance'); } if (isset($this->request->post['config_encryption'])) { $this->data['config_encryption'] = $this->request->post['config_encryption']; } else { $this->data['config_encryption'] = $this->config->get('config_encryption'); } if (isset($this->request->post['config_compression'])) { $this->data['config_compression'] = $this->request->post['config_compression']; } else { $this->data['config_compression'] = $this->config->get('config_compression'); } if (isset($this->request->post['config_error_display'])) { $this->data['config_error_display'] = $this->request->post['config_error_display']; } else { $this->data['config_error_display'] = $this->config->get('config_error_display'); } if (isset($this->request->post['config_error_log'])) { $this->data['config_error_log'] = $this->request->post['config_error_log']; } else { $this->data['config_error_log'] = $this->config->get('config_error_log'); } if (isset($this->request->post['config_error_filename'])) { $this->data['config_error_filename'] = $this->request->post['config_error_filename']; } else { $this->data['config_error_filename'] = $this->config->get('config_error_filename'); } if (isset($this->request->post['config_google_analytics'])) { $this->data['config_google_analytics'] = $this->request->post['config_google_analytics']; } else { $this->data['config_google_analytics'] = $this->config->get('config_google_analytics'); } $this->template = 'setting/setting.tpl'; $this->children = array( 'common/header', 'common/footer' ); $this->response->setOutput($this->render()); } private function validate() { if (!$this->user->hasPermission('modify', 'setting/setting')) { $this->error['warning'] = $this->language->get('error_permission'); } if (!$this->request->post['config_name']) { $this->error['name'] = $this->language->get('error_name'); } if ((utf8_strlen($this->request->post['config_owner']) < 3) || (utf8_strlen($this->request->post['config_owner']) > 64)) { $this->error['owner'] = $this->language->get('error_owner'); } if ((utf8_strlen($this->request->post['config_address']) < 3) || (utf8_strlen($this->request->post['config_address']) > 256)) { $this->error['address'] = $this->language->get('error_address'); } if ((utf8_strlen($this->request->post['config_email']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['config_email'])) { $this->error['email'] = $this->language->get('error_email'); } if ((utf8_strlen($this->request->post['config_telephone']) < 3) || (utf8_strlen($this->request->post['config_telephone']) > 32)) { $this->error['telephone'] = $this->language->get('error_telephone'); } if (!$this->request->post['config_title']) { $this->error['title'] = $this->language->get('error_title'); } if (!empty($this->request->post['config_customer_group_display']) && !in_array($this->request->post['config_customer_group_id'], $this->request->post['config_customer_group_display'])) { $this->error['customer_group_display'] = $this->language->get('error_customer_group_display'); } if (!$this->request->post['config_voucher_min']) { $this->error['voucher_min'] = $this->language->get('error_voucher_min'); } if (!$this->request->post['config_voucher_max']) { $this->error['voucher_max'] = $this->language->get('error_voucher_max'); } if (!$this->request->post['config_image_category_width'] || !$this->request->post['config_image_category_height']) { $this->error['image_category'] = $this->language->get('error_image_category'); } if (!$this->request->post['config_image_thumb_width'] || !$this->request->post['config_image_thumb_height']) { $this->error['image_thumb'] = $this->language->get('error_image_thumb'); } if (!$this->request->post['config_image_popup_width'] || !$this->request->post['config_image_popup_height']) { $this->error['image_popup'] = $this->language->get('error_image_popup'); } if (!$this->request->post['config_image_product_width'] || !$this->request->post['config_image_product_height']) { $this->error['image_product'] = $this->language->get('error_image_product'); } if (!$this->request->post['config_image_additional_width'] || !$this->request->post['config_image_additional_height']) { $this->error['image_additional'] = $this->language->get('error_image_additional'); } if (!$this->request->post['config_image_related_width'] || !$this->request->post['config_image_related_height']) { $this->error['image_related'] = $this->language->get('error_image_related'); } if (!$this->request->post['config_image_compare_width'] || !$this->request->post['config_image_compare_height']) { $this->error['image_compare'] = $this->language->get('error_image_compare'); } if (!$this->request->post['config_image_wishlist_width'] || !$this->request->post['config_image_wishlist_height']) { $this->error['image_wishlist'] = $this->language->get('error_image_wishlist'); } if (!$this->request->post['config_image_cart_width'] || !$this->request->post['config_image_cart_height']) { $this->error['image_cart'] = $this->language->get('error_image_cart'); } if (!$this->request->post['config_error_filename']) { $this->error['error_filename'] = $this->language->get('error_error_filename'); } if (!$this->request->post['config_admin_limit']) { $this->error['admin_limit'] = $this->language->get('error_limit'); } if (!$this->request->post['config_catalog_limit']) { $this->error['catalog_limit'] = $this->language->get('error_limit'); } if ($this->error && !isset($this->error['warning'])) { $this->error['warning'] = $this->language->get('error_warning'); } if (!$this->error) { return true; } else { return false; } } public function template() { if (file_exists(DIR_IMAGE . 'templates/' . basename($this->request->get['template']) . '.png')) { $image = HTTPS_IMAGE . 'templates/' . basename($this->request->get['template']) . '.png'; } else { $image = HTTPS_IMAGE . 'no_image.jpg'; } $this->response->setOutput('<img src="' . $image . '" alt="" title="" style="border: 1px solid #EEEEEE;" />'); } public function country() { $json = array(); $this->load->model('localisation/country'); $country_info = $this->model_localisation_country->getCountry($this->request->get['country_id']); if ($country_info) { $this->load->model('localisation/zone'); $json = array( 'country_id' => $country_info['country_id'], 'name' => $country_info['name'], 'iso_code_2' => $country_info['iso_code_2'], 'iso_code_3' => $country_info['iso_code_3'], 'address_format' => $country_info['address_format'], 'postcode_required' => $country_info['postcode_required'], 'zone' => $this->model_localisation_zone->getZonesByCountryId($this->request->get['country_id']), 'status' => $country_info['status'] ); } $this->response->setOutput(json_encode($json)); } } ?>
dinoweb/lead_store
local/admin/controller/setting/setting.php
PHP
gpl-3.0
47,643
package com.wordpress.marleneknoche.sea.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Map; import org.junit.Before; import org.junit.Test; public class NucleobaseCounterTest { private NucleobaseCounter nucleobaseCounter; private static final String TEST_STRING = "GTACGCCTGGGAGTCGACTGACTGCTGAAGATACAGAACCTGA"; @Before public void setUp(){ nucleobaseCounter = new NucleobaseCounter(); } @Test public void countNucleobasesTest() { Map<String,Integer> nucleobaseMap = new HashMap<String,Integer>(); nucleobaseMap = nucleobaseCounter.countNucleobases(TEST_STRING); assertEquals(13, nucleobaseMap.get("G"),0); assertEquals(8, nucleobaseMap.get("T"),0); assertEquals(10, nucleobaseMap.get("C"),0); assertEquals(12, nucleobaseMap.get("A"),0); } @Test public void countPurinesTest(){ Map<String,Integer> nucleobaseMap = new HashMap<String,Integer>(); nucleobaseMap.put("G", 13); nucleobaseMap.put("T", 8); nucleobaseMap.put("C", 10); nucleobaseMap.put("A", 12); int numberOfPurines = nucleobaseCounter.countPurines(nucleobaseMap); assertEquals(25, numberOfPurines); } @Test public void countPyrimidinesTest(){ //C+T=py Map<String,Integer> nucleobaseMap = new HashMap<String,Integer>(); nucleobaseMap.put("G", 13); nucleobaseMap.put("T", 8); nucleobaseMap.put("C", 10); nucleobaseMap.put("A", 12); int numberOfPyrimidines = nucleobaseCounter.countPyrimidines(nucleobaseMap); assertEquals(18, numberOfPyrimidines); } @Test public void hasMorePurinesThanPyrimidinesTest(){ Map<String, Integer> nucleobaseMap = new HashMap<String, Integer>(); nucleobaseMap.put("G", 13); nucleobaseMap.put("T", 8); nucleobaseMap.put("C", 10); nucleobaseMap.put("A", 12); assertTrue(nucleobaseCounter.hasMorePurinesThanPyrimidines(nucleobaseMap)); } }
Sanguinik/sea
src/test/java/com/wordpress/marleneknoche/sea/logic/NucleobaseCounterTest.java
Java
gpl-3.0
1,956
package com.gavinflood.edumate; import java.util.ArrayList; import java.util.List; import java.util.Vector; import android.app.Activity; import android.app.Dialog; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.SQLException; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class Assignments extends ListActivity { // Global variables private ImageButton home; private ImageButton newAssignment; private DatabaseAdapter dbAdapter; private Vector<RowData> list; private RowData rd; private LayoutInflater inflater; private CustomAdapter adapter; private SeparatedListAdapter separatedAdapter; private ListView lv; private String tag = getClass().getSimpleName(); // More global variables. private long id; private String subject; private int sem; private String desc; private String descShort; private String date; private String time; public int status; private List<Long> idList; // Called when the Activity is created. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.assignments); // Initialise the variables for the listview. inflater = (LayoutInflater)getSystemService(Activity.LAYOUT_INFLATER_SERVICE); list = new Vector<RowData>(); separatedAdapter = new SeparatedListAdapter(this); idList = new ArrayList<Long>(); // Fetch the assignments from the database and order them by date in a // separated adapter. dbAdapter = new DatabaseAdapter(this); try { dbAdapter.open(); Cursor c = dbAdapter.fetchAllAssignments(); if (c != null) { if (adapter != null) adapter.clear(); if (list != null) list.clear(); if (c.moveToFirst()) { String prevDate = "No Date"; int count = 0; long zero = 0; do { id = c.getLong(c.getColumnIndex(DatabaseAdapter.ASS_ID)); subject = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_SUBJECT)); desc = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_DESC)); status = c.getInt(c.getColumnIndex(DatabaseAdapter.ASS_STATUS)); date = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_DATE)); // Shorten the description if it might extend over the status icon. if (desc.length() >= 30) { descShort = desc.substring(0, 30); descShort += "..."; } else { descShort = desc; } // Create a new RowData object with the fields set to the data obtained. rd = new RowData(subject, descShort, status); // Check if this is the first item in the database and make it's // due date the starting date. if (count == 0) { prevDate = date; } count++; // If the current item's due date is equal to the previous item's due // date, add the item to the list. Otherwise, add it to a new list in // a new section. if (date.equals(prevDate)) { list.add(rd); Log.d(tag, "Added "+subject+", "+date+" = "+prevDate); } else { CustomAdapter adapter = new CustomAdapter(this, R.layout.assignments_list_item, R.id.assignment_list_item_title, list); prevDate = formatDate(prevDate); separatedAdapter.addSection(prevDate, adapter); idList.add(zero); Log.d(tag, "Added section to separatedAdapter."); list = new Vector<RowData>(); list.add(rd); Log.d(tag, "Added "+subject+", "+date+" != "+prevDate); } prevDate = date; idList.add(id); } while (c.moveToNext()); // Add the last item to the appropriate list and section. CustomAdapter adapter = new CustomAdapter(this, R.layout.assignments_list_item, R.id.assignment_list_item_title, list); prevDate = formatDate(prevDate); separatedAdapter.addSection(prevDate, adapter); idList.add(zero); } } c.close(); } catch (SQLException e) { Log.d(tag, "Could not retrieve data..."); } finally { if (dbAdapter != null) dbAdapter.close(); } initListView(); initHome(); initNewAssignment(); } // Initialise home button. private void initHome() { home = (ImageButton)findViewById(R.id.assignments_home); home.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent(Assignments.this, HomeScreen.class)); } }); } // Initialise the newAssignment button. private void initNewAssignment() { newAssignment = (ImageButton)findViewById(R.id.new_assignment); newAssignment.setOnClickListener(new OnClickListener() { public void onClick(View v) { Cursor c; boolean noSubjects = false; int count = 0; try { dbAdapter.open(); String s = PrefManager.readString(getApplicationContext(), PrefManager.SEMESTER, "1"); int se; if (s.equals("Year Long")) se = 0; else se = Integer.parseInt(s); if (se == 1 || se == 0) c = dbAdapter.fetchAllSubjectsSem1(); else c = dbAdapter.fetchAllSubjectsSem2(); if (c != null) { if (c.moveToFirst()) { do { count++; } while (c.moveToNext()); } } Log.d(tag, "Count: " + count); if (count == 0) noSubjects = true; Log.d(tag, "" + noSubjects); } catch (SQLException e) { Log.d(tag, "Could not check number of classes"); } finally { if (dbAdapter != null) dbAdapter.close(); } if (noSubjects == true) { Toast t = Toast.makeText(getApplicationContext(), "Add a class first.", Toast.LENGTH_SHORT); t.show(); } else { startActivity(new Intent(Assignments.this, NewAssignmentScreen.class)); finish(); } } }); } // Initialise the list view functionality. private void initListView() { lv = getListView(); lv.setAdapter(separatedAdapter); lv.setTextFilterEnabled(true); // When the listview is clicked, get the data from the appropriate row in the database // and add it as extras to an intent, which starts the Assignment Screen Activity. lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int pos, long id) { try { Log.d(tag, "Selected position: " + pos); long newId = idList.get(pos - 1); dbAdapter.open(); Cursor c = dbAdapter.fetchAssignment(newId); if (c != null) { if (c.moveToFirst()) { do { subject = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_SUBJECT)); sem = c.getInt(c.getColumnIndex(DatabaseAdapter.ASS_SEM)); desc = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_DESC)); status = c.getInt(c.getColumnIndex(DatabaseAdapter.ASS_STATUS)); date = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_DATE)); time = c.getString(c.getColumnIndex(DatabaseAdapter.ASS_TIME)); } while (c.moveToNext()); } } c.close(); Intent intent = new Intent(Assignments.this, AssignmentScreen.class); intent.putExtra("ASS_SUB", subject); intent.putExtra("ASS_SEM", sem); intent.putExtra("ASS_DESC", desc); intent.putExtra("ASS_STAT", status); intent.putExtra("ASS_DATE", date); intent.putExtra("ASS_TIME", time); intent.putExtra("ASS_ID", newId); startActivity(intent); finish(); } catch (SQLException e) { Log.d(tag, "Could not add data to assignmentScreen."); } finally { if (dbAdapter != null) dbAdapter.close(); } } }); } // Format the date to show it as a worded date, for example: '12th September 2011' private String formatDate(String input) { String[] stringSplit = input.split("-"); String year = stringSplit[0]; String month = stringSplit[1]; String day = stringSplit[2]; if (day.equals("01")) day = "1st"; else if (day.equals("02")) day = "2nd"; else if (day.equals("03")) day = "3rd"; else if (day.equals("04")) day = "4th"; else if (day.equals("05")) day = "5th"; else if (day.equals("06")) day = "6th"; else if (day.equals("07")) day = "7th"; else if (day.equals("08")) day = "8th"; else if (day.equals("09")) day = "9th"; else if (day.equals("10")) day = "10th"; else if (day.equals("11")) day = "11th"; else if (day.equals("12")) day = "12th"; else if (day.equals("13")) day = "13th"; else if (day.equals("14")) day = "14th"; else if (day.equals("15")) day = "15th"; else if (day.equals("16")) day = "16th"; else if (day.equals("17")) day = "17th"; else if (day.equals("18")) day = "18th"; else if (day.equals("19")) day = "19th"; else if (day.equals("20")) day = "20th"; else if (day.equals("21")) day = "21st"; else if (day.equals("22")) day = "22nd"; else if (day.equals("23")) day = "23rd"; else if (day.equals("24")) day = "24th"; else if (day.equals("25")) day = "25th"; else if (day.equals("26")) day = "26th"; else if (day.equals("27")) day = "27th"; else if (day.equals("28")) day = "28th"; else if (day.equals("29")) day = "29th"; else if (day.equals("30")) day = "30th"; else if (day.equals("31")) day = "31st"; if (month.equals("01")) month = "January"; else if (month.equals("02")) month = "February"; else if (month.equals("03")) month = "March"; else if (month.equals("04")) month = "April"; else if (month.equals("05")) month = "May"; else if (month.equals("06")) month = "June"; else if (month.equals("07")) month = "July"; else if (month.equals("08")) month = "August"; else if (month.equals("09")) month = "September"; else if (month.equals("10")) month = "October"; else if (month.equals("02")) month = "November"; else if (month.equals("02")) month = "December"; String fullDate = day + " " + month + " " + year; return fullDate; } // Private class RowData which is called each time a new row needs to be added to the // appropriate section of the SeparatedAdapter. private class RowData { protected int mStatus; protected String mSubject; protected String mDesc; RowData(String title, String desc, int status){ mStatus = status; mSubject = title; mDesc = desc; } @Override public String toString() { return mSubject+" "+mDesc+" "+mStatus; } } // Private class CustomAdapter which initialises any views on the list-item to // the appropriate values. private class CustomAdapter extends ArrayAdapter<RowData> { public CustomAdapter(Context context, int resource, int textViewResourceId, List<RowData> objects) { super(context, resource, textViewResourceId, objects); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; TextView subject = null; TextView desc = null; ImageView status = null; RowData rowData = getItem(position); if (null == convertView) { convertView = inflater.inflate(R.layout.assignments_list_item, null); holder = new ViewHolder(convertView); convertView.setTag(holder); } holder = (ViewHolder)convertView.getTag(); subject = holder.getSubject(); subject.setText(rowData.mSubject); desc = holder.getDesc(); desc.setText(rowData.mDesc); status = holder.getStatus(); // Show incomplete image if status is incomplete, otherwise show complete image. if (rowData.mStatus == 0) status.setImageResource(R.drawable.not_complete); else if (rowData.mStatus == 1) status.setImageResource(R.drawable.completed); return convertView; } } // Private class ViewHolder which returns the views for the list-item to the CustomAdapter. private class ViewHolder { private View mRow; private TextView subject = null; private TextView desc = null; private ImageView status = null; public ViewHolder(View row) { mRow = row; } public TextView getSubject() { if (null == subject) subject = (TextView) mRow.findViewById(R.id.assignment_list_item_title); return subject; } public TextView getDesc() { if (null == desc) desc = (TextView) mRow.findViewById(R.id.assignment_list_item_desc); return desc; } public ImageView getStatus() { if (null == status) status = (ImageView) mRow.findViewById(R.id.assignment_list_item_status); return status; } } //Create the menu. @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_delete_all, menu); return true; } // Implement menu functionality. @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.delete_all_items: final Dialog dialog = new Dialog(Assignments.this); dialog.setContentView(R.layout.yes_no); dialog.setTitle(R.string.delete_all_assignments); dialog.setCancelable(true); Button yes = (Button)dialog.findViewById(R.id.yes); yes.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { dbAdapter.open(); dbAdapter.deleteAssignments(); startActivity(new Intent(Assignments.this, HomeScreen.class)); finish(); } catch (SQLException e) { Log.d(tag, "Could not delete all assignments"); } finally { if (dbAdapter != null) dbAdapter.close(); } } }); Button no = (Button)dialog.findViewById(R.id.no); no.setOnClickListener(new OnClickListener() { public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); return true; default: return super.onOptionsItemSelected(item); } } // Override the back button functionality to finish this Activity and start the HomeScreen. @Override public void onBackPressed() { startActivity(new Intent(Assignments.this, HomeScreen.class)); finish(); } }
gavinflud/edumate
src/com/gavinflood/edumate/Assignments.java
Java
gpl-3.0
15,858
/* * SkyTube * Copyright (C) 2018 Ramon Mifsud * * 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 (version 3 of the 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 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 free.rm.skytube.businessobjects.YouTube.POJOs; import android.content.pm.PackageManager; import android.content.pm.Signature; import com.google.api.client.extensions.android.json.AndroidJsonFactory; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.services.youtube.YouTube; import com.google.common.io.BaseEncoding; import java.io.IOException; import java.security.MessageDigest; import free.rm.skytube.BuildConfig; import free.rm.skytube.app.SkyTubeApp; import free.rm.skytube.businessobjects.Logger; /** * Represents YouTube API service. */ public class YouTubeAPI { /** * Returns a new instance of {@link YouTube}. * * @return {@link YouTube} */ public static YouTube create() { HttpTransport httpTransport = new NetHttpTransport(); JsonFactory jsonFactory = AndroidJsonFactory.getDefaultInstance(); return new YouTube.Builder(httpTransport, jsonFactory, new HttpRequestInitializer() { private String getSha1() { String sha1 = null; try { Signature[] signatures = SkyTubeApp.getContext().getPackageManager().getPackageInfo(BuildConfig.APPLICATION_ID, PackageManager.GET_SIGNATURES).signatures; for (Signature signature: signatures) { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(signature.toByteArray()); sha1 = BaseEncoding.base16().encode(md.digest()); } } catch (Throwable tr) { Logger.e(this, "...", tr); } return sha1; } @Override public void initialize(HttpRequest request) throws IOException { request.getHeaders().set("X-Android-Package", BuildConfig.APPLICATION_ID); request.getHeaders().set("X-Android-Cert", getSha1()); } }).setApplicationName("+").build(); } }
ram-on/SkyTube
app/src/main/java/free/rm/skytube/businessobjects/YouTube/POJOs/YouTubeAPI.java
Java
gpl-3.0
2,605
package nl.knaw.huygens.tei; /* * #%L * VisiTEI * ======= * Copyright (C) 2011 - 2017 Huygens ING * ======= * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ /** * Contains definitions of some character entities. */ public class Entities { public static final String EM_DASH = "&#8212;"; // named: "&mdash;" public static final String LS_QUOTE = "&#8216;"; // named: "&lsquo;" public static final String RS_QUOTE = "&#8217;"; // named: "&rsquo;" public static final String LD_QUOTE = "&#8220;"; // named: "&ldquo;" public static final String RD_QUOTE = "&#8221;"; // named: "&rdquo;" public static final String BULLET = "&#8226;"; // named: "&bull;" }
HuygensING/visitei
src/main/java/nl/knaw/huygens/tei/Entities.java
Java
gpl-3.0
1,302
package org.hofapps.tinyplanet; import android.content.Context; import android.util.AttributeSet; /** * Created by fabian on 02.11.2015. */ public class RangeSeekBar extends android.support.v7.widget.AppCompatSeekBar { private static final int ARRAY_MIN_POS = 0; private static final int ARRAY_MAX_POS = 1; private int[] range; private int id; public RangeSeekBar(final Context context) { super(context); } public RangeSeekBar(final Context context, final AttributeSet attrs) { super(context, attrs); } public RangeSeekBar(final Context context, final AttributeSet attrs, final int defStyle) { super(context, attrs, defStyle); } public void setRange(int[] range) { this.range = range; } public int getSeekBarValue() { int progress = getProgress(); int value = (int) range[ARRAY_MIN_POS] + (getProgress() * (range[ARRAY_MAX_POS] - range[ARRAY_MIN_POS])) / 100; return value; } public void setValue(int value) { int pos; pos = (int) (value - range[ARRAY_MIN_POS]) * 100 / (range[ARRAY_MAX_POS] - range[ARRAY_MIN_POS]); // pos = (int) (value * 100 / (range[ARRAY_MAX_POS] - range[ARRAY_MIN_POS])) - range[ARRAY_MIN_POS]; setProgress(pos); } }
hollaus/TinyPlanetMaker
app/src/main/java/org/hofapps/tinyplanet/RangeSeekBar.java
Java
gpl-3.0
1,322
class CheckPoint extends MasterBlock { constructor(heading, x, y, moving, rotating) { super("img/blocks/ellenorzo.png", heading, x, y, moving, rotating) this._hit = false } get_newDir(dir) { this._hit = true return [dir] } hitStatus() { return this._hit } }
Sch-Tomi/light-breaker
dev_js/blocks/checkpoint.js
JavaScript
gpl-3.0
326
class ColophonController < ApplicationController def chapter @chapters = Chapter.order("title ASC").all end def who @all_chapters = Chapter.order("title ASC").all end def how end def funding end def highlights end def community @social = Social.where('start_time > ?',Time.now).first @gig = Gig.where('end_time > ?',Time.now).order("start_time DESC").first end def calendar @socials = Social.where('start_time > ?',Time.now).order("start_time DESC") @gigs = Gig.where('end_time > ?',Time.now).order("start_time DESC") @events = (@socials + @gigs).sort_by(&:start_time) end def datums # Member statistics @members = {} @members['inactive'] = User.where(:activated => false).count @members['active'] = User.active.count completion_percentages = User.active.map(&:profile_completion) @members['completion_average'] = (completion_percentages.inject{ |sum, el| sum + el }.to_f / completion_percentages.size).to_i @members['shared_comments'] = ((User.where('id in (?)', Comment.all.map(&:user_id).join(',')).count.to_f / @members['active'].to_f) * 100).round @members['shared_contributions'] = ((User.where('id in (?)', Contribution.all.map(&:user_id).join(',')).count.to_f / @members['active'].to_f) * 100).round @members['attended_gigs'] = ((Gig.all.map{ |g| g.users.map(&:id) if g.users.any? }.compact.flatten.uniq.count.to_f / @members['active'].to_f) * 100).round @members['attended_socials'] = ((Social.all.map{ |s| s.users.map(&:id) if s.users.any? }.compact.flatten.uniq.count.to_f / @members['active'].to_f) * 100).round @crew = {} @crew['blog_posts'] = Post.all.count @crew['trills'] = Issue.all.map{ |w| w.trills.published }.flatten.uniq.count @crew['challenges'] = Challenge.activated.count @crew['gigs'] = Gig.all.count @crew['socials'] = Social.all.count @users = {} @users['comments'] = Comment.all.count @users['contributions'] = Contribution.all.count @users['gigs_signed_up'] = Slot.where('gig_id IS NOT NULL').map{ |s| s.users.map(&:id) if s.users.any? }.compact.flatten.uniq.count @users['partner_requests'] = Partner.inactive.count @users['challenge_requests'] = Challenge.inactive.count @ga_profile = Garb::Management::Profile.all.detect {|p| p.web_property_id == 'UA-32250261-2'} @ga_uniques = @ga_profile.newvisits(:start_date => Date.today - 6.months, :end_date => Date.today).first.new_visits mc = Gibbon.new(ENV['MC_API_KEY'], { :throws_exceptions => false}) mc.campaigns({:list_id => ENV['MC_LIST_ID'], :status => 'sent'})['total'] @mailchimp_newsletters = mc.campaigns({:list_id => ENV['MC_LIST_ID'], :status => 'sent'})['total']; @mailchimp_newsletters = 9 #@fb_page = FbGraph::Page.new('g00dfornothing').fetch({:access_token => 'AAAFIALGg4joBACcLZBeYI9ZAD0o0bHE5UPDN5lOEH8hjXHxUnN8ZAZCpYNtZATmp0MlYLzbH94DWfBkUKGrO792ZCUFobdVEZCk27gmWqlpl9fMzFwvViuG'}) @fb_page = FbGraph::Page.new('g00dfornothing').fetch() @fb_likes = @fb_page.raw_attributes['likes']; @fb_posts = 25 #@fb_posts = @fb_page.posts.size @twitter_followers = 2904 #Twitter.user("g00dfornothing").followers_count; @twitter_tweets = 2530 # Twitter.user("g00dfornothing").statuses_count; end def watch @watches = Post.where(:watch => 1).sort_by(&:created_at) end def giftcard end end
goodfornothing/goodfornothing
app/controllers/colophon_controller.rb
Ruby
gpl-3.0
3,394
require 'package' class A2png < Package description 'Converts plain ASCII text into PNG bitmap images.' homepage 'https://sourceforge.net/projects/a2png/' version '0.1.5-1' compatibility 'all' source_url 'https://sourceforge.net/projects/a2png/files/a2png/0.1.5/a2png-0.1.5.tar.bz2' source_sha256 'd3ae1c771f5180d93f35cded76d9bb4c4cc2023dbe65613e78add3eeb43f736b' binary_url ({ aarch64: 'https://dl.bintray.com/chromebrew/chromebrew/a2png-0.1.5-1-chromeos-armv7l.tar.xz', armv7l: 'https://dl.bintray.com/chromebrew/chromebrew/a2png-0.1.5-1-chromeos-armv7l.tar.xz', i686: 'https://dl.bintray.com/chromebrew/chromebrew/a2png-0.1.5-1-chromeos-i686.tar.xz', x86_64: 'https://dl.bintray.com/chromebrew/chromebrew/a2png-0.1.5-1-chromeos-x86_64.tar.xz', }) binary_sha256 ({ aarch64: '72ebf874dee9871949df56eecd9b24e8586b84c1efed1bdf988f9ea9f28e012b', armv7l: '72ebf874dee9871949df56eecd9b24e8586b84c1efed1bdf988f9ea9f28e012b', i686: '76223ed1859aa31f3d93afb5e3705dfff7a8023de08672b4f2216a8fe55e46b5', x86_64: 'b468b226e28cf717c3f38435849bf737067a8b9ec3c1928c01fed5488bb31464', }) depends_on 'cairo' def self.build system "./configure \ --prefix=#{CREW_PREFIX} \ --libdir=#{CREW_LIB_PREFIX} \ --localstatedir=#{CREW_PREFIX}/tmp \ --enable-cairo \ --with-cairo-lib=#{CREW_LIB_PREFIX} \ --with-cairo-include=#{CREW_PREFIX}/include/cairo" system 'make' end def self.install system "make", "DESTDIR=#{CREW_DEST_DIR}", "install" end end
cstrouse/chromebrew
packages/a2png.rb
Ruby
gpl-3.0
1,586
"use strict"; var validMoment = require('../helpers/is-valid-moment-object'); module.exports = function (value, dateFormat) { if (!validMoment(value)) return value; return value.format(dateFormat); };
matfish2/vue-tables-2
compiled/filters/format-date.js
JavaScript
gpl-3.0
206
<?php // Load the plugin files and fire a startup action require_once(dirname(__FILE__) . "/plugins.php"); startup(); require_once(dirname(__FILE__) . "/config.php"); _load_language_file("/index.inc"); /** * * Login page, self posts to become management page * * @author Patrick Lockley * @version 1.0 * @copyright Copyright (c) 2008,2009 University of Nottingham * @package */ include $xerte_toolkits_site->php_library_path . "display_library.php"; require_once(dirname(__FILE__) . "/website_code/php/login_library.php"); login_processing(); login_processing2(); recycle_bin(); /* * Output the main page, including the user's and blank templates */ ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head> <?php head_start();?> <!-- University of Nottingham Xerte Online Toolkits HTML to use to set up the template management page Version 1.0 --> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title><?PHP echo apply_filters("head_title", $xerte_toolkits_site->site_title); ?></title> <link href="website_code/styles/frontpage.css" media="screen" type="text/css" rel="stylesheet" /> <link href="website_code/styles/xerte_buttons.css" media="screen" type="text/css" rel="stylesheet" /> <link href="website_code/styles/folder_popup.css" media="screen" type="text/css" rel="stylesheet" /> <?PHP echo " <script type=\"text/javascript\"> // JAVASCRIPT library for fixed variables\n // management of javascript is set up here\n // SITE SETTINGS var site_url = \"{$xerte_toolkits_site->site_url}\"; var site_apache = \"{$xerte_toolkits_site->apache}\"; var properties_ajax_php_path = \"website_code/php/properties/\"; var management_ajax_php_path = \"website_code/php/management/\"; var ajax_php_path = \"website_code/php/\"; </script>"; ?> <script type="text/javascript" language="javascript" src="website_code/scripts/validation.js" ></script> <?php _include_javascript_file("website_code/scripts/file_system.js"); _include_javascript_file("website_code/scripts/screen_display.js"); _include_javascript_file("website_code/scripts/ajax_management.js"); _include_javascript_file("website_code/scripts/folders.js"); _include_javascript_file("website_code/scripts/template_management.js"); _include_javascript_file("website_code/scripts/logout.js"); _include_javascript_file("website_code/scripts/import.js"); ?> <?php head_end();?></head> <!-- code to sort out the javascript which prevents the text selection of the templates (allowing drag and drop to look nicer body_scroll handles the calculation of the documents actual height in IE. --> <body onload="javascript:sort_display_settings()" onselectstart="return false;" onscroll="body_scroll()"> <?php body_start();?> <!-- Folder popup is the div that appears when creating a new folder --> <div class="folder_popup" id="message_box"> <div class="corner" style="background-image:url(website_code/images/MessBoxTL.gif); background-position:top left;"> </div> <div class="central" style="background-image:url(website_code/images/MessBoxTop.gif);"> </div> <div class="corner" style="background-image:url(website_code/images/MessBoxTR.gif); background-position:top right;"> </div> <div class="main_area_holder_1"> <div class="main_area_holder_2"> <div class="main_area" id="dynamic_section"> <p><?PHP echo INDEX_FOLDER_PROMPT; ?></p><form id="foldernamepopup" action="javascript:create_folder()" method="post" enctype="text/plain"><input type="text" width="200" id="foldername" name="foldername" style="margin:0px; margin-right:5px; padding:3px" /><br /><br /> <button type="submit" class="xerte_button"><img src="website_code/images/Icon_Folder_15x12.gif"/><?php echo INDEX_BUTTON_NEWFOLDER; ?></button><button type="button" class="xerte_button" onclick="javascript:popup_close()"><?php echo INDEX_BUTTON_CANCEL; ?></button></form> <p><span id="folder_feedback"></span></p> </div> </div> </div> <div class="corner" style="background-image:url(website_code/images/MessBoxBL.gif); background-position:top left;"> </div> <div class="central" style="background-image:url(website_code/images/MessBoxBottom.gif);"> </div> <div class="corner" style="background-image:url(website_code/images/MessBoxBR.gif); background-position:top right;"> </div> </div> <div class="topbar"> <div style="width:50%; height:100%; float:right; position:relative; background-image:url(<?php echo $xerte_toolkits_site->site_url . $xerte_toolkits_site->organisational_logo ?>); background-repeat:no-repeat; background-position:right; margin-right:10px; float:right"> <p style="float:right; margin:0px; color:#a01a13;"><button type="button" class="xerte_button" onclick="javascript:logout()" ><?PHP echo INDEX_BUTTON_LOGOUT; ?></button></p> </div> <img src="<?php echo $xerte_toolkits_site->site_logo; ?>" style="margin-left:10px; float:left" /> </div> <!-- Main part of the page --> <div class="pagecontainer"> <div class="file_mgt_area"> <div class="file_mgt_area_top"> <div class="top_left sign_in_TL m_b_d_2_child"> <div class="top_right sign_in_TR m_b_d_2_child"> <p class="heading"> <?PHP echo apply_filters('page_title', INDEX_WORKSPACE_TITLE);?> </p> </div> </div> </div> <div class="file_mgt_area_middle"> <div class="file_mgt_area_middle_button"> <!-- File area menu --> <div class="file_mgt_area_middle_button_left"> <button type="button" class="xerte_button" id="newfolder" onclick="javascript:make_new_folder()"><img src="website_code/images/Icon_Folder_15x12.gif"/><?php echo INDEX_BUTTON_NEWFOLDER; ?></button> </div> <div class="file_mgt_area_middle_button_left"> <button type="button" class="xerte_button_disabled" disabled="disabled" id="properties"><?php echo INDEX_BUTTON_PROPERTIES; ?></button> <button type="button" class="xerte_button_disabled" disabled="disabled" id="edit"><?php echo INDEX_BUTTON_EDIT; ?></button> <button type="button" class="xerte_button_disabled" disabled="disabled" id="preview"><?php echo INDEX_BUTTON_PREVIEW; ?></button> </div> <div class="file_mgt_area_middle_button_right"> <button type="button" class="xerte_button_disabled" disabled="disabled" id="delete"><?php echo INDEX_BUTTON_DELETE; ?></button> <button type="button" class="xerte_button_disabled" disabled="disabled" id="duplicate"><?php echo INDEX_BUTTON_DUPLICATE; ?></button> <button type="button" class="xerte_button_disabled" disabled="disabled" id="publish"><?php echo INDEX_BUTTON_PUBLISH; ?></button> </div> <div id="file_area" onscroll="scroll_check(event,this)" onmousemove="mousecoords(event)" onmouseup="file_drag_stop(event,this)"><?PHP list_users_projects("data_down"); ?></div> </div> <!-- Everything from the end of the file system to the top of the blank templates area --> </div> <div class="file_mgt_area_bottom" style="height:30px;"> <div class="bottom_left sign_in_BL m_b_d_2_child" style="height:30px;"> <div class="bottom_right sign_in_BR m_b_d_2_child" style="height:30px;"> <form name="sorting" style="display:inline"> <p style="padding:0px; margin:3px 0 0 5px"> <?PHP echo INDEX_SORT; ?> <select name="type"> <option value="alpha_up"><?PHP echo INDEX_SORT_A; ?></option> <option value="alpha_down"><?PHP echo INDEX_SORT_Z; ?></option> <option value="date_down"><?PHP echo INDEX_SORT_NEW; ?></option> <option value="date_up"><?PHP echo INDEX_SORT_OLD; ?></option> </select> <button type="button" class="xerte_button" onclick="javascript:selection_changed()"><?php echo INDEX_BUTTON_SORT; ?></button> </p> </form> </div> </div> </div> <div class="border" style="margin-top:10px"></div> <div class="help" style="width:48%"> <?PHP echo apply_filters('editor_pod_one', $xerte_toolkits_site->pod_one); ?> </div> <div class="help" style="width:48%; float:right;"> <?PHP echo apply_filters('editor_pod_two', $xerte_toolkits_site->pod_two); ?> </div> </div> <div class="new_template_area"> <div class="top_left sign_in_TL m_b_d_2_child new_template_mod"> <div class="top_right sign_in_TR m_b_d_2_child"> <?php display_language_selectionform("general"); ?> <p class="heading"> <?PHP echo INDEX_CREATE; ?> </p> <p class="general"> <?PHP echo INDEX_TEMPLATES; ?> </p> </div> </div> <div class="new_template_area_middle"> <!-- Top of the blank templates section --> <div id="new_template_area_middle_ajax" class="new_template_area_middle_scroll"><?PHP list_blank_templates(); ?><!-- End of the blank templates section, through to end of page --> <?PHP echo "&nbsp;&nbsp;&nbsp;" . INDEX_LOGGED_IN_AS . " " . $_SESSION['toolkits_firstname'] ." " .$_SESSION['toolkits_surname'];?> </div> </div> <div class="file_mgt_area_bottom" style="width:100%"> <div class="bottom_left sign_in_BL m_b_d_2_child"> <div class="bottom_right sign_in_BR m_b_d_2_child" style="height:10px;"> </div> </div> </div> </div> <div class="border"> </div> <p class="copyright"> <img src="website_code/images/lt_logo.gif" /><br/> <?PHP echo $xerte_toolkits_site->copyright; ?></p> </div> <?php body_end();?></body> </html> <?php shutdown();?>
sdc/xerte
index.php
PHP
gpl-3.0
11,968