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
<?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
<?php namespace Tests\Feature; use stdClass; use Tests\TestCase; use App\Models\Submission; use App\Events\SubmissionCreated; use App\Events\SubmissionUpdated; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Event; use App\Core\Connect\ConnectorsRepository; use App\Core\Connect\Connectors\SubmissionsConnector; class OpenRosaTest extends TestCase { public function setUp() { parent::setUp(); // Truncate collections $this->truncateCollections([ 'photos', 'connects', 'submissions', 'settings', ]); // Create test binding $this->insertTestConnects(); } public function testSubmissionsAreStored() { Event::fake(); $meta = $this->openRosaMeta(); $response = $this->makeOpenRosaCall($meta); $this->assertEquals(201, $response->status()); Event::assertDispatched(SubmissionCreated::class); $submission = Submission::where('form_id', 'aSVuyzAa5EXGoKdZLRvDds') ->where('instance_id', $meta->instanceId) ->first(); $this->assertNotNull($submission); $this->assertEquals(1, $submission->photos()->count()); $photo = $submission->photos()->first(); $this->assertNotEmpty($photo->url()); $this->assertNotNull($submission->geolocation); } public function testSubmissionsAreUpdated() { Event::fake(); Submission::create([ 'form_id' => 'aSVuyzAa5EXGoKdZLRvDds', 'instance_id' => 'instance1', 'deprecated_id' => null ]); $meta = $this->openRosaMeta('instance1', false); $request = $this->makeOpenRosaCall($meta); $this->assertEquals(201, $request->status()); Event::assertDispatched(SubmissionUpdated::class); $previousInstance = Submission::where('instance_id', 'instance1')->exists(); $updatedInstance = Submission::where('instance_id', $meta->instanceId)->exists(); $this->assertFalse($previousInstance); $this->assertTrue($updatedInstance); } /** * @test */ public function it_disallows_unauthenticated_submissions() { resolve('settings')->updateSettings([ 'requires_authentication' => true ]); $meta = $this->openRosaMeta('instance1', false); $request = $this->makeOpenRosaCall($meta); $this->assertEquals(401, $request->status()); } protected function makeOpenRosaCall($meta) { return $this->call( 'POST', '/openrosa/submissions', $meta->body, [], // cookies $meta->files, $meta->headers ); } protected function getXmlFile() { $temp = tempnam(sys_get_temp_dir(), 'test'); copy(base_path('tests/fixtures/instance.xml'), $temp); return new UploadedFile($temp, $temp, 'text/xml', filesize($temp), null, true); } protected function getFakeImage() { return UploadedFile::fake()->image('file.png', 600, 600); } protected function openRosaMeta($updatedInstanceId = null, $attachment = true) { $meta = new stdClass(); $meta->instanceId = uniqid(); $meta->headers = [ 'HTTP_X-OpenRosa-Version' => '1.0', 'HTTP_X-OpenRosa-Instance-Id' => $meta->instanceId ]; $meta->body = [ 'Date' => date('r') ]; $meta->files = [ 'xml_submission_file' => $this->getXmlFile(), ]; if (!is_null($updatedInstanceId)) { $meta->headers['HTTP_X-OpenRosa-Deprecated-Id'] = $updatedInstanceId; } if ($attachment !== false) { $meta->files['test_jpg'] = $this->getFakeImage(); } return $meta; } protected function insertTestConnects() { $repository = app()->make(ConnectorsRepository::class); $connector = app()->make(SubmissionsConnector::class); $connector->fromArray([ 'links' => [ 'coordinates' => [ 'type' => 'code', 'value' => 'return {lat: data.get(\'LG2.GPS\', "").split(" ")[0], lng: data.get(\'LG2.GPS\', "").split(" ")[1]}' ] ], ]); $repository->save($connector); } }
swiftmade/ssas-core
tests/Feature/OpenRosaTest.php
PHP
gpl-3.0
4,413
//////////////////////////////////////////////////////////////////// // // // 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
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. * * Copyright (C) Joakim Kennedy, 2018 */ package clinote import ( "bytes" "testing" "github.com/stretchr/testify/assert" ) func TestWritingNoteAndNotebookTables(t *testing.T) { assert := assert.New(t) nbs := []*Notebook{ &Notebook{GUID: "GUID1", Name: "Notebook1"}, &Notebook{GUID: "GUID2", Name: "Notebook2"}, &Notebook{GUID: "GUID3", Name: "Notebook3"}, } notes := []*Note{ &Note{Title: "Note1", Notebook: &Notebook{GUID: "GUID1"}, Created: int64(0), Updated: int64(0)}, &Note{Title: "Note2", Notebook: &Notebook{GUID: "GUID2"}, Created: int64(0), Updated: int64(0)}, &Note{Title: "Note3", Notebook: &Notebook{GUID: "GUID3"}, Created: int64(0), Updated: int64(0)}, } t.Run("NotebookList", func(t *testing.T) { buf := new(bytes.Buffer) WriteNotebookListing(buf, nbs) assert.Equal(expectedNotebooklist, string(buf.Bytes()), "Notebook list table doesn't match") }) t.Run("NoteList", func(t *testing.T) { buf := new(bytes.Buffer) WriteNoteListing(buf, notes, nbs) assert.Equal(expectedNotelist, string(buf.Bytes()), "Note list table doesn't match") }) } func TestCredentialTable(t *testing.T) { assert := assert.New(t) creds := []*Credential{ &Credential{Name: "Cred1", Secret: "test12", CredType: EvernoteCredential}, &Credential{Name: "Cred2", Secret: "test23", CredType: EvernoteSandboxCredential}, } t.Run("print without secret", func(t *testing.T) { buf := new(bytes.Buffer) WriteCredentialListing(buf, creds) assert.Equal(expectedCredentialList, string(buf.Bytes())) }) t.Run("print with secret", func(t *testing.T) { buf := new(bytes.Buffer) WriteCredentialListingWithSecret(buf, creds) assert.Equal(expectedCredentialListWithSecret, string(buf.Bytes())) }) } func TestSettingsTable(t *testing.T) { assert := assert.New(t) buf := new(bytes.Buffer) WriteSettingsListing(buf, []string{"credential"}, []string{"An index value."}, []string{"Set the active credential for the user."}) assert.Equal(expectedSettingList, string(buf.Bytes())) } const expectedNotebooklist = `+---+-----------+ | # | NAME | +---+-----------+ | 1 | Notebook1 | | 2 | Notebook2 | | 3 | Notebook3 | +---+-----------+ ` const expectedNotelist = `+---+-------+-----------+------------+------------+ | # | TITLE | NOTEBOOK | MODIFIED | CREATED | +---+-------+-----------+------------+------------+ | 1 | Note1 | Notebook1 | 1970-01-01 | 1970-01-01 | | 2 | Note2 | Notebook2 | 1970-01-01 | 1970-01-01 | | 3 | Note3 | Notebook3 | 1970-01-01 | 1970-01-01 | +---+-------+-----------+------------+------------+ ` const expectedCredentialList = `+---+-------+------------------+ | # | NAME | TYPE | +---+-------+------------------+ | 1 | Cred1 | Evernote | | 2 | Cred2 | Evernote Sandbox | +---+-------+------------------+ ` const expectedCredentialListWithSecret = `+---+-------+------------------+--------+ | # | NAME | TYPE | SECRET | +---+-------+------------------+--------+ | 1 | Cred1 | Evernote | test12 | | 2 | Cred2 | Evernote Sandbox | test23 | +---+-------+------------------+--------+ ` const expectedSettingList = `+------------+-----------------+--------------------------------+ | SETTING | ARGUMENTS | DESCRIPTION | +------------+-----------------+--------------------------------+ | credential | An index value. | Set the active credential for | | | | the user. | +------------+-----------------+--------------------------------+ `
TcM1911/clinote
write_test.go
GO
gpl-3.0
4,176
#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
using Hurricane.Music.Playlist; using Hurricane.Music.Track; namespace Hurricane.Music.Data { public class TrackPlaylistPair { public PlayableBase Track { get; set; } public IPlaylist Playlist { get; set; } public TrackPlaylistPair(PlayableBase track, IPlaylist playlist) { Track = track; Playlist = playlist; } } }
Alkalinee/Hurricane
Hurricane/Music/Data/TrackPlaylistPair.cs
C#
gpl-3.0
397
/* * Copyright (C) 2013 Mamadou DIOP * Copyright (C) 2013 Doubango Telecom <http://www.doubango.org> * License: GPLv3 * This file is part of the open source SIP TelePresence system <https://code.google.com/p/telepresence/> */ #include "opentelepresence/OTMixerMgr.h" #include "opentelepresence/OTMixerMgrAudio.h" #include "opentelepresence/OTMixerMgrVideo.h" #include "tsk_debug.h" #include <assert.h> OTMixerMgr::OTMixerMgr(OTMediaType_t eMediaType, OTObjectWrapper<OTBridgeInfo*> oBridgeInfo) :OTObject() { m_eMediaType = eMediaType; m_oBridgeInfo = oBridgeInfo; } OTMixerMgr::~OTMixerMgr() { // FIXME: loop and release()? m_OTCodecs.clear(); } /** Finds the best codec to use. /!\Function not thread safe @param listOfCodecsToSearchInto List of codecs combined using binary OR (|). @return The best codec if exist, otherwise NULL */ OTObjectWrapper<OTCodec*> OTMixerMgr::findBestCodec(OTCodec_Type_t eListOfCodecsToSearchInto) { std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter = m_OTCodecs.begin(); while(iter != m_OTCodecs.end()) { if(((*iter).first & eListOfCodecsToSearchInto) == (*iter).first) { return (*iter).second; } ++iter; } return NULL; } /** Removes a list of codecs /!\Function not thread safe @param listOfCodecsToSearchInto List of codecs combined using binary OR (|). @return True if removed, False otherwise */ bool OTMixerMgr::removeCodecs(OTCodec_Type_t eListOfCodecsToSearchInto) { bool bFound = false; std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter; again: iter = m_OTCodecs.begin(); while(iter != m_OTCodecs.end()) { if(((*iter).first & eListOfCodecsToSearchInto) == (*iter).first) { (*iter).second->releaseRef(); m_OTCodecs.erase(iter); bFound = true; goto again; } ++iter; } return bFound; } /** Adds a new codec to the list of supported codecs. /!\Function not thread safe @param oCodec The codec to add. Must not be NULL. @return True if codec successfully added, False otherwise */ bool OTMixerMgr::addCodec(OTObjectWrapper<OTCodec*> oCodec) { OT_ASSERT(*oCodec); std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter = m_OTCodecs.find(oCodec->getType()); if(iter != m_OTCodecs.end()) { OT_DEBUG_ERROR("Codec with type = %d already exist", oCodec->getType()); return false; } m_OTCodecs.insert(std::pair<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >(oCodec->getType(), oCodec)); return true; } /** Executes action on all codecs. /!\Function not thread safe @return True if codec successfully added, False otherwise */ bool OTMixerMgr::executeActionOnCodecs(OTCodecAction_t eAction) { std::map<OTCodec_Type_t, OTObjectWrapper<OTCodec*> >::iterator iter = m_OTCodecs.begin(); while(iter != m_OTCodecs.end()) { (*iter).second->executeAction(eAction); ++iter; } return true; } OTObjectWrapper<OTMixerMgr*> OTMixerMgr::New(OTMediaType_t eMediaType, OTObjectWrapper<OTBridgeInfo*> oBridgeInfo) { OTObjectWrapper<OTMixerMgr*> pOTMixer; switch(eMediaType) { case OTMediaType_Audio: { pOTMixer = new OTMixerMgrAudio(oBridgeInfo); break; } case OTMediaType_Video: { pOTMixer = new OTMixerMgrVideo(oBridgeInfo); break; } } if(pOTMixer && !pOTMixer->isValid()) { OTObjectSafeRelease(pOTMixer); } return pOTMixer; }
Fossa/teleprescence
source/OTMixerMgr.cc
C++
gpl-3.0
3,445
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2015-2017 Stephane Caron <stephane.caron@normalesup.org> # # This file is part of fip-walkgen # <https://github.com/stephane-caron/fip-walkgen>. # # fip-walkgen 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. # # fip-walkgen 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 # fip-walkgen. If not, see <http://www.gnu.org/licenses/>. from cop_nmpc import COPPredictiveController from double_support import DoubleSupportController from fip_nmpc import FIPPredictiveController from regulation import FIPRegulator from wrench_nmpc import WrenchPredictiveController __all__ = [ 'COPPredictiveController', 'DoubleSupportController', 'FIPPredictiveController', 'FIPRegulator', 'WrenchPredictiveController', ]
stephane-caron/dynamic-walking
wpg/com_control/__init__.py
Python
gpl-3.0
1,231
package org.sapia.corus.client.services.deployer.dist; import static org.sapia.corus.client.services.deployer.dist.ConfigAssertions.attributeNotNullOrEmpty; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.text.StrLookup; import org.apache.commons.lang.text.StrSubstitutor; import org.sapia.console.CmdLine; import org.sapia.corus.client.common.CompositeStrLookup; import org.sapia.corus.client.common.Env; import org.sapia.corus.client.common.EnvVariableStrLookup; import org.sapia.corus.client.common.FileUtil; import org.sapia.corus.client.common.FileUtil.FileInfo; import org.sapia.corus.client.common.PathFilter; import org.sapia.corus.client.common.PropertiesStrLookup; import org.sapia.corus.client.exceptions.misc.MissingDataException; import org.sapia.corus.interop.InteropCodec.InteropWireFormat; import org.sapia.corus.interop.api.Consts; import org.sapia.ubik.util.Strings; import org.sapia.util.xml.confix.ConfigurationException; /** * This helper class can be inherited from to implement {@link Starter}s that * launch Java processes. * * @author Yanick Duchesne */ public abstract class BaseJavaStarter implements Starter, Serializable { static final long serialVersionUID = 1L; protected String javaHome = System.getProperty("java.home"); protected String javaCmd = "java"; protected String vmType; protected String profile; protected String corusHome = System.getProperty("corus.home"); protected List<VmArg> vmArgs = new ArrayList<VmArg>(); protected List<Property> vmProps = new ArrayList<Property>(); protected List<Option> options = new ArrayList<Option>(); protected List<XOption> xoptions = new ArrayList<XOption>(); private List<Dependency> dependencies = new ArrayList<Dependency>(); private boolean interopEnabled = true; private boolean numaEnabled = true; private InteropWireFormat interopWireFormat = InteropWireFormat.PROTOBUF; /** * Sets the Corus home. * * @param home * the Corus home. */ public void setCorusHome(String home) { corusHome = home; } /** * @param numaEnabled if <code>ttue</code>, indicates that NUMA is enabled for process corresponding to this instance. */ public void setNumaEnabled(boolean numaEnabled) { this.numaEnabled = numaEnabled; } @Override public boolean isNumaEnabled() { return numaEnabled; } /** * @param interopEnabled if <code>true</code>, indicates that interop is enabled (<code>true</code> by default). */ public void setInteropEnabled(boolean interopEnabled) { this.interopEnabled = interopEnabled; } public boolean isInteropEnabled() { return interopEnabled; } /** * @param interopWireFormat the interop wire format type to use for the process. */ public void setInteropWireFormat(String interopWireFormat) { this.interopWireFormat = InteropWireFormat.forType(interopWireFormat); } public InteropWireFormat getInteropWireFormat() { return interopWireFormat; } /** * Sets this instance's profile. * * @param profile * a profile name. */ public void setProfile(String profile) { this.profile = profile; } /** * Returns this instance's profile. * * @return a profile name. */ public String getProfile() { return profile; } /** * Adds the given {@link VmArg} to this instance. * * @param arg * a {@link VmArg}. */ public void addArg(VmArg arg) { vmArgs.add(arg); } /** * Adds the given property to this instance. * * @param prop * a {@link Property} instance. */ public void addProperty(Property prop) { vmProps.add(prop); } /** * Adds the given VM option to this instance. * * @param opt * an {@link Option} instance. */ public void addOption(Option opt) { options.add(opt); } /** * Adds the given "X" option to this instance. * * @param opt * a {@link XOption} instance. */ public void addXoption(XOption opt) { xoptions.add(opt); } /** * Sets this instance's JDK home directory. * * @param home * the full path to a JDK installation directory */ public void setJavaHome(String home) { javaHome = home; } /** * Sets the name of the 'java' executable. * * @param cmdName * the name of the 'java' executable */ public void setJavaCmd(String cmdName) { javaCmd = cmdName; } public void setVmType(String aType) { vmType = aType; } /** * Adds a dependency to this instance. * * @param dep * a {@link Dependency} */ public void addDependency(Dependency dep) { if (dep.getProfile() == null) { dep.setProfile(profile); } dependencies.add(dep); } public Dependency createDependency() { Dependency dep = new Dependency(); dep.setProfile(profile); dependencies.add(dep); return dep; } public List<Dependency> getDependencies() { return new ArrayList<Dependency>(dependencies); } protected CmdLineBuildResult buildCommandLine(Env env) { Map<String, String> cmdLineVars = new HashMap<String, String>(); cmdLineVars.put("user.dir", env.getCommonDir()); cmdLineVars.put("java.home", javaHome); Property[] envProperties = env.getProperties(); CompositeStrLookup propContext = new CompositeStrLookup() .add(StrLookup.mapLookup(cmdLineVars)) .add(PropertiesStrLookup.getInstance(envProperties)) .add(PropertiesStrLookup.getSystemInstance()) .add(new EnvVariableStrLookup()); CmdLine cmd = new CmdLine(); File javaHomeDir = env.getFileSystem().getFile(javaHome); if (!javaHomeDir.exists()) { throw new MissingDataException("java.home not found"); } cmd.addArg(FileUtil.toPath(javaHomeDir.getAbsolutePath(), "bin", javaCmd)); if (vmType != null) { if (!vmType.startsWith("-")) { cmd.addArg("-" + vmType); } else { cmd.addArg(vmType); } } for (VmArg arg : vmArgs) { String value = render(propContext, arg.getValue()); if (!Strings.isBlank(value)) { VmArg copy = new VmArg(); copy.setValue(value); cmd.addElement(copy.convert()); } } for (XOption opt : xoptions) { String value = render(propContext, opt.getValue()); XOption copy = new XOption(); copy.setName(opt.getName()); copy.setValue(value); if (!Strings.isBlank(copy.getName())) { cmdLineVars.put(copy.getName(), value); } cmd.addElement(copy.convert()); } for (Option opt : options) { String value = render(propContext, opt.getValue()); Option copy = new Option(); copy.setName(opt.getName()); copy.setValue(value); if (!Strings.isBlank(copy.getName())) { cmdLineVars.put(copy.getName(), value); } cmd.addElement(copy.convert()); } for (Property prop : vmProps) { String value = render(propContext, prop.getValue()); Property copy = new Property(); copy.setName(prop.getName()); copy.setValue(value); cmdLineVars.put(copy.getName(), value); cmd.addElement(copy.convert()); } for (Property prop : envProperties) { if (propContext.lookup(prop.getName()) != null) { cmd.addElement(prop.convert()); } } // adding interop option Property interopWireFormatProp = new Property(Consts.CORUS_PROCESS_INTEROP_PROTOCOL, interopWireFormat.type()); cmd.addElement(interopWireFormatProp.convert()); CmdLineBuildResult ctx = new CmdLineBuildResult(); ctx.command = cmd; ctx.variables = propContext; return ctx; } protected String getOptionalCp(String libDirs, StrLookup envVars, Env env) { String processUserDir; if ((processUserDir = env.getCommonDir()) == null || !env.getFileSystem().getFile(env.getCommonDir()).exists()) { processUserDir = System.getProperty("user.dir"); } String[] baseDirs; if (libDirs == null) { return ""; } else { baseDirs = FileUtil.splitFilePaths(render(envVars, libDirs)); } StringBuffer buf = new StringBuffer(); for (int dirIndex = 0; dirIndex < baseDirs.length; dirIndex++) { String baseDir = baseDirs[dirIndex]; String currentDir; if (FileUtil.isAbsolute(baseDir)) { currentDir = baseDir; } else { currentDir = FileUtil.toPath(processUserDir, baseDir); } FileInfo fileInfo = FileUtil.getFileInfo(currentDir); PathFilter filter = env.createPathFilter(fileInfo.directory); if (fileInfo.isClasses) { if (buf.length() > 0) { buf.append(File.pathSeparator); } buf.append(fileInfo.directory); } else { if (fileInfo.fileName == null) { filter.setIncludes(new String[] { "**/*.jar", "**/*.zip" }); } else { filter.setIncludes(new String[] { fileInfo.fileName }); } if (buf.length() > 0) { buf.append(File.pathSeparator); } String[] jars = filter.filter(); Arrays.sort(jars); for (int i = 0; i < jars.length; i++) { buf.append(fileInfo.directory).append(File.separator).append(jars[i]); if (i < (jars.length - 1)) { buf.append(File.pathSeparator); } } } } return render(envVars, buf.toString()); } protected String render(StrLookup context, String value) { StrSubstitutor substitutor = new StrSubstitutor(context); return substitutor.replace(value); } protected String getCp(Env env, String basedir) { PathFilter filter = env.createPathFilter(basedir); filter.setIncludes(new String[] { "**/*.jar" }); String[] jars = filter.filter(); StringBuffer buf = new StringBuffer(); for (int i = 0; i < jars.length; i++) { buf.append(basedir).append(File.separator).append(jars[i]); if (i < (jars.length - 1)) { buf.append(File.pathSeparator); } } return buf.toString(); } protected void doValidate(String elementName) throws ConfigurationException { attributeNotNullOrEmpty(elementName, "corusHome", corusHome); attributeNotNullOrEmpty(elementName, "javaCmd", javaCmd); attributeNotNullOrEmpty(elementName, "javaHome", javaHome); attributeNotNullOrEmpty(elementName, "profile", profile); } static final class CmdLineBuildResult { CmdLine command; StrLookup variables; } }
sapia-oss/corus
modules/client/src/main/java/org/sapia/corus/client/services/deployer/dist/BaseJavaStarter.java
Java
gpl-3.0
10,837
package org.voyanttools.trombone.tool.corpus; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.util.List; import org.junit.Test; import org.voyanttools.trombone.model.DocumentToken; import org.voyanttools.trombone.storage.Storage; import org.voyanttools.trombone.tool.build.RealCorpusCreator; import org.voyanttools.trombone.util.FlexibleParameters; import org.voyanttools.trombone.util.TestHelper; public class DocumentTokensTest { @Test public void test() throws IOException { for (Storage storage : TestHelper.getDefaultTestStorages()) { System.out.println("Testing with "+storage.getClass().getSimpleName()+": "+storage.getLuceneManager().getClass().getSimpleName()); test(storage); } } public void test(Storage storage) throws IOException { FlexibleParameters parameters; parameters = new FlexibleParameters(); parameters.addParameter("string", "It was a dark and stormy night."); parameters.addParameter("string", "It was the best of times it was the worst of times."); RealCorpusCreator creator = new RealCorpusCreator(storage, parameters); creator.run(); parameters.setParameter("corpus", creator.getStoredId()); DocumentTokens docTokens; List<DocumentToken> tokens; docTokens = new DocumentTokens(storage, parameters); docTokens.run(); tokens = docTokens.getDocumentTokens(); assertEquals(44, tokens.size()); assertEquals("It", tokens.get(2).getTerm()); parameters.setParameter("withPosLemmas", "true"); docTokens = new DocumentTokens(storage, parameters); docTokens.run(); tokens = docTokens.getDocumentTokens(); assertEquals(44, tokens.size()); assertEquals("it", tokens.get(2).getLemma()); storage.destroy(); } @Test public void testLanguages() throws IOException { for (Storage storage : TestHelper.getDefaultTestStorages()) { System.out.println("Testing with "+storage.getClass().getSimpleName()+": "+storage.getLuceneManager().getClass().getSimpleName()); testLanguages(storage); } } public void testLanguages(Storage storage) throws IOException { FlexibleParameters parameters; parameters = new FlexibleParameters(); parameters.addParameter("file", new String[]{TestHelper.getResource("udhr/udhr-en.txt").getPath(),TestHelper.getResource("udhr/udhr-es.txt").getPath(),TestHelper.getResource("udhr/udhr-fr.txt").getPath()}); parameters.addParameter("string", "我们第一届全国人民代表大会第一次会议"); RealCorpusCreator creator = new RealCorpusCreator(storage, parameters); creator.run(); parameters.setParameter("corpus", creator.getStoredId()); DocumentTokens docTokens; List<DocumentToken> tokens; parameters.setParameter("withPosLemmas", "true"); parameters.setParameter("noOthers", "true"); parameters.setParameter("docIndex", "0"); docTokens = new DocumentTokens(storage, parameters); docTokens.run(); tokens = docTokens.getDocumentTokens(); assertEquals(50, tokens.size()); assertEquals("universal", tokens.get(0).getLemma()); // parameters.setParameter("docIndex", "1"); // docTokens = new DocumentTokens(storage, parameters); // docTokens.run(); // tokens = docTokens.getDocumentTokens(); // assertEquals(50, tokens.size()); // assertEquals("todo", tokens.get(2).getLemma()); parameters.setParameter("docIndex", "2"); docTokens = new DocumentTokens(storage, parameters); docTokens.run(); tokens = docTokens.getDocumentTokens(); assertEquals(50, tokens.size()); assertEquals("article", tokens.get(6).getLemma()); parameters.setParameter("docIndex", "3"); docTokens = new DocumentTokens(storage, parameters); boolean hasException = false; try { docTokens.run(); } catch (Exception e) { hasException = true; } assertTrue(hasException); storage.destroy(); } }
sgsinclair/trombone
src/test/java/org/voyanttools/trombone/tool/corpus/DocumentTokensTest.java
Java
gpl-3.0
3,879
package com.example.solomon; import android.annotation.SuppressLint; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import com.estimote.mustard.rx_goodness.rx_requirements_wizard.Requirement; import com.estimote.mustard.rx_goodness.rx_requirements_wizard.RequirementsWizardFactory; import com.estimote.proximity_sdk.api.EstimoteCloudCredentials; import com.estimote.proximity_sdk.api.ProximityObserver; import com.estimote.proximity_sdk.api.ProximityObserverBuilder; import com.estimote.proximity_sdk.api.ProximityZone; import com.estimote.proximity_sdk.api.ProximityZoneBuilder; import com.estimote.proximity_sdk.api.ProximityZoneContext; import com.example.solomon.networkPackets.UserData; import com.example.solomon.runnables.SendLocationDataRunnable; import android.support.design.widget.AppBarLayout; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import kotlin.Unit; import kotlin.jvm.functions.Function0; import kotlin.jvm.functions.Function1; public class MainActivity extends AppCompatActivity { //Beacon variables public Date currentTime; private ProximityObserver proximityObserver; public static TextView feedBackTextView; public int userId; public ObjectOutputStream objectOutputStream; public ObjectInputStream objectInputStream; //UI variables private TabLayout tabLayout; private ViewPager viewPager; private ViewPagerAdapter viewPagerAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initUI(); //getUserData UserData userData = (UserData) getIntent().getSerializableExtra("UserData"); userId = userData.getUserId(); objectOutputStream = LoginActivity.objectOutputStream; objectInputStream = LoginActivity.objectInputStream; //initialized cloud credentials EstimoteCloudCredentials cloudCredentials = new EstimoteCloudCredentials("solomon-app-ge4", "97f78b20306bb6a15ed1ddcd24b9ca21"); //instantiated the proximity observer this.proximityObserver = new ProximityObserverBuilder(getApplicationContext(), cloudCredentials) .onError(new Function1<Throwable, Unit>() { @Override public Unit invoke(Throwable throwable) { Log.e("app", "proximity observer error: " + throwable); feedBackTextView.setText("proximity error"); return null; } }) .withBalancedPowerMode() .build(); //instantiated a proximity zone final ProximityZone zone1 = new ProximityZoneBuilder() .forTag("Room1") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room1", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room1", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); final ProximityZone zone2 = new ProximityZoneBuilder() .forTag("Room2") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room2", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room2", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); final ProximityZone zone3 = new ProximityZoneBuilder() .forTag("Room3") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room3", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room3", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); final ProximityZone zone4 = new ProximityZoneBuilder() .forTag("Room4") .inCustomRange(3.0) .onEnter(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Entered the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room4", true, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .onExit(new Function1<ProximityZoneContext, Unit>() { @Override public Unit invoke(ProximityZoneContext context) { feedBackTextView.setText("Left the: " + context.getTag()); //get current time currentTime = Calendar.getInstance().getTime(); Thread sendLocationDataThread = new Thread(new SendLocationDataRunnable(userId, 1, "Room4", false, currentTime, objectOutputStream)); sendLocationDataThread.start(); return null; } }) .build(); //set bluetooth functionality RequirementsWizardFactory .createEstimoteRequirementsWizard() .fulfillRequirements(this, // onRequirementsFulfilled new Function0<Unit>() { @Override public Unit invoke() { Log.d("app", "requirements fulfilled"); proximityObserver.startObserving(zone1); proximityObserver.startObserving(zone2); proximityObserver.startObserving(zone3); proximityObserver.startObserving(zone4); feedBackTextView.setText("requirements fulfiled"); return null; } }, // onRequirementsMissing new Function1<List<? extends Requirement>, Unit>() { @Override public Unit invoke(List<? extends Requirement> requirements) { Log.e("app", "requirements missing: " + requirements); feedBackTextView.setText("requirements missing"); return null; } }, // onError new Function1<Throwable, Unit>() { @Override public Unit invoke(Throwable throwable) { Log.e("app", "requirements error: " + throwable); feedBackTextView.setText("requirements error"); return null; } }); } @SuppressLint("ResourceAsColor") public void initUI() { //get UI references tabLayout = (TabLayout) findViewById(R.id.tabLayoutId); viewPager = (ViewPager) findViewById(R.id.viewPagerId); viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); feedBackTextView = findViewById(R.id.feedBackTextView); //set tabbed layout StoreAdvertisementFragment storeAdvertisementFragment = new StoreAdvertisementFragment(); Bundle bundle1 = new Bundle(); ArrayList<String> storeAdvertisementsData = new ArrayList<>(); bundle1.putStringArrayList("storeAdvertisementsData", storeAdvertisementsData); storeAdvertisementFragment.setArguments(bundle1, "storeAdvertisementsData"); UserStatsFragment userStatsFragment = new UserStatsFragment(); Bundle bundle2 = new Bundle(); ArrayList<String> userStatsData = new ArrayList<>(); bundle2.putStringArrayList("userStatsData", userStatsData); userStatsFragment.setArguments(bundle2, "userStatsData"); SettingsFragment settingsFragment = new SettingsFragment(); Bundle bundle3 = new Bundle(); ArrayList<String> profileDataAndSettingsData = new ArrayList<>(); bundle3.putStringArrayList("profileDataAndSettingsData", profileDataAndSettingsData); settingsFragment.setArguments(bundle3, "profileDataAndSettingsData"); //add the fragment to the viewPagerAdapter int numberOfTabs = 3; viewPagerAdapter.addFragment(storeAdvertisementFragment, "storeAdvertisementsData"); viewPagerAdapter.addFragment(userStatsFragment, "userStatsData"); viewPagerAdapter.addFragment(settingsFragment, "profileDataAndSettingsData"); //set my ViewPagerAdapter to the ViewPager viewPager.setAdapter(viewPagerAdapter); //set the tabLayoutViewPager tabLayout.setupWithViewPager(viewPager); //set images instead of title text for each tab tabLayout.getTabAt(0).setIcon(R.drawable.store_ads_icon); tabLayout.getTabAt(1).setIcon(R.drawable.stats_icon); tabLayout.getTabAt(2).setIcon(R.drawable.settings_icon); } }
beia/beialand
projects/solomon/Android/Solomon/app/src/main/java/com/example/solomon/MainActivity.java
Java
gpl-3.0
13,065
/* ** Taiga ** Copyright (C) 2010-2014, Eren Okka ** ** 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 <curl/curlver.h> #include <jsoncpp/json/json.h> #include <pugixml/pugixml.hpp> #include <utf8proc/utf8proc.h> #include <zlib/zlib.h> #include "base/file.h" #include "base/gfx.h" #include "base/string.h" #include "taiga/orange.h" #include "taiga/resource.h" #include "taiga/stats.h" #include "taiga/taiga.h" #include "ui/dlg/dlg_about.h" namespace ui { enum ThirdPartyLibrary { kJsoncpp, kLibcurl, kPugixml, kUtf8proc, kZlib, }; static std::wstring GetLibraryVersion(ThirdPartyLibrary library) { switch (library) { case kJsoncpp: return StrToWstr(JSONCPP_VERSION_STRING); case kLibcurl: return StrToWstr(LIBCURL_VERSION); case kPugixml: { base::SemanticVersion version((PUGIXML_VERSION / 100), (PUGIXML_VERSION % 100) / 10, (PUGIXML_VERSION % 100) % 10); return version; } case kUtf8proc: return StrToWstr(utf8proc_version()); case kZlib: return StrToWstr(ZLIB_VERSION); break; } return std::wstring(); } //////////////////////////////////////////////////////////////////////////////// class AboutDialog DlgAbout; AboutDialog::AboutDialog() { RegisterDlgClass(L"TaigaAboutW"); } BOOL AboutDialog::OnDestroy() { taiga::orange.Stop(); return TRUE; } BOOL AboutDialog::OnInitDialog() { rich_edit_.Attach(GetDlgItem(IDC_RICHEDIT_ABOUT)); auto schemes = L"http:https:irc:"; rich_edit_.SendMessage(EM_AUTOURLDETECT, TRUE /*= AURL_ENABLEURL*/, reinterpret_cast<LPARAM>(schemes)); rich_edit_.SetEventMask(ENM_LINK); std::wstring text = L"{\\rtf1\\ansi\\deff0\\deflang1024" L"{\\fonttbl" L"{\\f0\\fnil\\fcharset0 Segoe UI;}" L"}" L"\\fs24\\b " TAIGA_APP_NAME L"\\b0 " + std::wstring(Taiga.version) + L"\\line\\fs18\\par " L"\\b Author:\\b0\\line " L"Eren 'erengy' Okka\\line\\par " L"\\b Contributors:\\b0\\line " L"saka, Diablofan, slevir, LordGravewish, cassist, rr-, sunjayc, LordHaruto, Keelhauled, thesethwalker, Soinou\\line\\par " L"\\b Third-party components:\\b0\\line " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/yusukekamiyamane/fugue-icons\"}}{\\fldrslt{Fugue Icons 3.4.5}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/open-source-parsers/jsoncpp\"}}{\\fldrslt{JsonCpp " + GetLibraryVersion(kJsoncpp) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/bagder/curl\"}}{\\fldrslt{libcurl " + GetLibraryVersion(kLibcurl) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/zeux/pugixml\"}}{\\fldrslt{pugixml " + GetLibraryVersion(kPugixml) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/JuliaLang/utf8proc\"}}{\\fldrslt{utf8proc " + GetLibraryVersion(kUtf8proc) + L"}}}, " L"{\\field{\\*\\fldinst{HYPERLINK \"https://github.com/madler/zlib\"}}{\\fldrslt{zlib " + GetLibraryVersion(kZlib) + L"}}}\\line\\par " L"\\b Links:\\b0\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"http://taiga.erengy.com\"}}{\\fldrslt{Home page}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"https://github.com/erengy/taiga\"}}{\\fldrslt{GitHub repository}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"https://hummingbird.me/groups/taiga\"}}{\\fldrslt{Hummingbird group}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"http://myanimelist.net/clubs.php?cid=21400\"}}{\\fldrslt{MyAnimeList club}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"https://twitter.com/taigaapp\"}}{\\fldrslt{Twitter account}}}\\line " L"\u2022 {\\field{\\*\\fldinst{HYPERLINK \"irc://irc.rizon.net/taiga\"}}{\\fldrslt{IRC channel}}}" L"}"; rich_edit_.SetTextEx(WstrToStr(text)); return TRUE; } BOOL AboutDialog::DialogProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_COMMAND: { // Icon click if (HIWORD(wParam) == STN_DBLCLK) { SetText(L"Orange"); Stats.tigers_harmed++; taiga::orange.Start(); return TRUE; } break; } case WM_NOTIFY: { switch (reinterpret_cast<LPNMHDR>(lParam)->code) { // Execute link case EN_LINK: { auto en_link = reinterpret_cast<ENLINK*>(lParam); if (en_link->msg == WM_LBUTTONUP) { ExecuteLink(rich_edit_.GetTextRange(&en_link->chrg)); return TRUE; } break; } } break; } } return DialogProcDefault(hwnd, uMsg, wParam, lParam); } void AboutDialog::OnPaint(HDC hdc, LPPAINTSTRUCT lpps) { win::Dc dc = hdc; win::Rect rect; win::Rect rect_edit; rich_edit_.GetWindowRect(GetWindowHandle(), &rect_edit); const int margin = rect_edit.top; const int sidebar_width = rect_edit.left - margin; // Paint background GetClientRect(&rect); rect.left = sidebar_width; dc.FillRect(rect, ::GetSysColor(COLOR_WINDOW)); // Paint application icon rect.Set(margin / 2, margin, sidebar_width - (margin / 2), rect.bottom); DrawIconResource(IDI_MAIN, dc.Get(), rect, true, false); win::Window label = GetDlgItem(IDC_STATIC_APP_ICON); label.SetPosition(nullptr, rect, SWP_NOACTIVATE | SWP_NOREDRAW | SWP_NOOWNERZORDER | SWP_NOZORDER); label.SetWindowHandle(nullptr); } } // namespace ui
halfa/taiga
src/ui/dlg/dlg_about.cpp
C++
gpl-3.0
6,076
<?php define('a1cms', 'energy', true); define('akina', 'photohost', true); define('root', substr(dirname( __FILE__ ), 0, -14)); if (!$_COOKIE['PHPSESSID'] or preg_match('/^[a-z0-9]{26}$/', $_COOKIE['PHPSESSID']))//если куки нет совсем или идентификатор нормальный session_start(); include_once root.'sys/config.php'; include_once root.'sys/engine.php'; include_once root.'sys/functions.php'; include_once 'akinaconfig.php'; include_once 'functions.php'; if(!in_array ($_SESSION['user_group'], $config['allow_control'])) die('Access denied!'); if ($config['site_work']!=true) die ("Проводятся сервисные работы. Сервис временно недоступен."); $parse_main=array(); $view = isset($_GET['v']) ? (boolean)$_GET['v'] : false; $action = isset($_POST['action']) ? (string)$_POST['action'] : ''; // if ($_POST) // { // var_dump ($_POST); // var_dump ($_FILES); // } if(!$view && $action=='' && !$_GET['p']) $parse_main['{content}']=parse_template(get_img_template('upload'), array()); elseif($action=='upload') { include_once 'engine.php'; include_once 'upload.php'; include_once 'view.php'; } elseif($view) include_once 'view.php'; elseif($_GET['p']) { preg_match('/\w+/',$_GET['p'],$matches); $page=$config['template_path']."/".$matches['0'].".static.tpl"; if(is_file($page)) $parse_main['{content}']= file_get_contents($page); else include_once 'error404.php'; } else include_once 'error404.php'; $parse_main['{max_height}']=$config['max_height']; $parse_main['{max_width}']=$config['max_width']; $parse_main['{max_size_mb}']=$config['max_size_mb']; $parse_main['{max_quantity}']=ini_get('max_file_uploads'); $parse_main['{template}']=$config['template_url']; if(is_array($error)) $parse_main['{error}']=parse_template (get_template('info'), array("{type}" =>'error',"{title}" =>"Ошибка!","{text}" => implode("<br />", $error))); else $parse_main['{error}']=''; $cachefile=$config['site_dir']."/cache"; if (time()-@filemtime($cachefile)>$config['cache_time']) { touch($cachefile);//чтобы только один пользователь запускал подсчет list($size, $images_total, $images_h24)=get_dir_size($config['uploaddir']); $size = formatfilesize($size); file_put_contents( $cachefile, "$images_total|$size|$images_h24"); } elseif (file_exists($cachefile)) list($images_total, $size, $images_h24) = explode("|", file_get_contents($cachefile)); $parse_main['{size}']=$size; $parse_main['{images}']=$images_total; $parse_main['{images24}']=$images_h24; $parse_main['{site_http_path}']=$config['site_url']; if(!$parse_main['{content}']) $parse_main['{content}']=''; echo parse_template(get_img_template('index'), $parse_main); // $result_img['result_img']=parse_template(get_img_template('index'), $parse_main); // echo json_encode($result_img); ?>
sal3/a1cms
plugins/images/index.php
PHP
gpl-3.0
2,918
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. # Copyright (C) NIWA & British Crown (Met Office) & Contributors. # # 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/>. """General utilities for the integration test infrastructure. These utilities are not intended for direct use by tests (hence the underscore function names). Use the fixtures provided in the conftest instead. """ import asyncio def _rm_if_empty(path): """Convenience wrapper for removing empty directories.""" try: path.rmdir() except OSError: return False return True
oliver-sanders/cylc
tests/integration/utils/__init__.py
Python
gpl-3.0
1,157
package com.gmail.mrphpfan; import com.gmail.mrphpfan.mccombatlevel.calculator.JavaScriptCalculator; import com.gmail.mrphpfan.mccombatlevel.calculator.LevelCalculator; import com.gmail.nossr50.config.Config; import com.gmail.nossr50.datatypes.player.PlayerProfile; import com.gmail.nossr50.datatypes.skills.PrimarySkillType; import javax.script.ScriptEngineManager; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assume.assumeThat; import static org.mockito.Matchers.any; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.mockStatic; import static org.powermock.api.mockito.PowerMockito.when; @PrepareForTest({PrimarySkillType.class, Config.class}) @RunWith(PowerMockRunner.class) public class CalculationTest { @Before public void before() { //ignore test in Java 10 in combination with PowerMock, because of bugs assumeThat(new ScriptEngineManager().getEngineByName("JavaScript"), notNullValue()); mockStatic(Config.class); Config fakeConfig = mock(Config.class); when(Config.getInstance()).thenReturn(fakeConfig); when(fakeConfig.getLocale()).thenReturn("en_US"); } @Test @Ignore public void testScript() { String formula = "Math.round((unarmed + swords + axes + archery + .25 * acrobatics + .25 * taming) / 45)"; LevelCalculator levelCalculator = new JavaScriptCalculator(formula); PlayerProfile playerProfile = mock(PlayerProfile.class); when(playerProfile.getSkillLevel(any(PrimarySkillType.class))).thenReturn(100); assertThat(10, is(levelCalculator.calculateLevel(playerProfile))); } }
games647/McCombatLevel
src/test/java/com/gmail/mrphpfan/CalculationTest.java
Java
gpl-3.0
2,019
<?php define("LOG_LEVEL", -1); /* quality assurance */ define("DEBUG_MSG", false); //define("REQUEST_URI", $_SERVER["REQUEST_URI"]); # root directory //define("REQUEST_URI", substr($_SERVER["REQUEST_URI"], LENGTH)); # replace LENGTH with (path-length) to avoid useless function call define("REQUEST_URI", ($_SERVER["SCRIPT_NAME"] == "/index.php") ? $_SERVER["REQUEST_URI"] : substr($_SERVER["REQUEST_URI"], strlen(dirname($_SERVER["SCRIPT_NAME"])))); # portable alternative. cost: 1 eval + 3 function call. //define("EPR", "/var/opt"); define("EPR", strtr(dirname(__FILE__), "\\", "/")); # portable alternative. define("FWK", EPR); # only if not in public folder require_once FWK."/classes/FrontController.php"; require_once FWK."/classes/CGI.php"; ?>
wilaheng/wila
index.php
PHP
gpl-3.0
755
namespace MQCloud.Transport.Implementation { internal class ThematicOperationResponse<T> : ThematicMessage<T> { public int CallbackId { get; set; } } }
mqcloud/csharp
Transport/TransportAPI/Implementation/ThematicOperationResponse.cs
C#
gpl-3.0
167
var inherit = function(){ $('*[inherit="source"]').change(function(){ $.get('/admin/libio/variety/hierarchy/' + $(this).val(), function(data){ $('*[inherit="target"]').each(function(key, input){ var id = $(input).prop('id'); var fieldName = id.substring(id.indexOf('_') + 1); $(input).val(data[fieldName]); if( $(input).prop('tagName') == 'SELECT' ) $(input).trigger('change'); }); }); }); }; $(document).ready(inherit); $(document).on('sonata-admin-setup-list-modal sonata-admin-append-form-element', inherit);
libre-informatique/SymfonyLibrinfoVarietiesBundle
src/Resources/public/js/inherit.js
JavaScript
gpl-3.0
651
using System.Collections; using System.Collections.Generic; using BaiRong.Core; using SiteServer.CMS.Core; using SiteServer.CMS.Model; namespace SiteServer.CMS.ImportExport { public class SiteTemplateManager { private readonly string _rootPath; private SiteTemplateManager(string rootPath) { _rootPath = rootPath; DirectoryUtils.CreateDirectoryIfNotExists(_rootPath); } public static SiteTemplateManager GetInstance(string rootPath) { return new SiteTemplateManager(rootPath); } public static SiteTemplateManager Instance => new SiteTemplateManager(PathUtility.GetSiteTemplatesPath(string.Empty)); public void DeleteSiteTemplate(string siteTemplateDir) { var directoryPath = PathUtils.Combine(_rootPath, siteTemplateDir); DirectoryUtils.DeleteDirectoryIfExists(directoryPath); var filePath = PathUtils.Combine(_rootPath, siteTemplateDir + ".zip"); FileUtils.DeleteFileIfExists(filePath); } public bool IsSiteTemplateDirectoryExists(string siteTemplateDir) { var siteTemplatePath = PathUtils.Combine(_rootPath, siteTemplateDir); return DirectoryUtils.IsDirectoryExists(siteTemplatePath); } public int GetSiteTemplateCount() { var directorys = DirectoryUtils.GetDirectoryPaths(_rootPath); return directorys.Length; } public List<string> GetDirectoryNameLowerList() { var directorys = DirectoryUtils.GetDirectoryNames(_rootPath); var list = new List<string>(); foreach (var directoryName in directorys) { list.Add(directoryName.ToLower().Trim()); } return list; } public SortedList GetSiteTemplateSortedList() { var sortedlist = new SortedList(); var directoryPaths = DirectoryUtils.GetDirectoryPaths(_rootPath); foreach (var siteTemplatePath in directoryPaths) { var metadataXmlFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileMetadata); if (FileUtils.IsFileExists(metadataXmlFilePath)) { var siteTemplateInfo = Serializer.ConvertFileToObject(metadataXmlFilePath, typeof(SiteTemplateInfo)) as SiteTemplateInfo; if (siteTemplateInfo != null) { var directoryName = PathUtils.GetDirectoryName(siteTemplatePath); sortedlist.Add(directoryName, siteTemplateInfo); } } } return sortedlist; } public void ImportSiteTemplateToEmptyPublishmentSystem(int publishmentSystemId, string siteTemplateDir, bool isUseTables, bool isImportContents, bool isImportTableStyles, string administratorName) { var siteTemplatePath = PathUtility.GetSiteTemplatesPath(siteTemplateDir); if (DirectoryUtils.IsDirectoryExists(siteTemplatePath)) { var publishmentSystemInfo = PublishmentSystemManager.GetPublishmentSystemInfo(publishmentSystemId); var templateFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTemplate); var tableDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Table); var menuDisplayFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileMenuDisplay); var tagStyleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTagStyle); var adFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileAd); var seoFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileSeo); var stlTagPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileStlTag); var gatherRuleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileGatherRule); var inputDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Input); var configurationFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileConfiguration); var siteContentDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.SiteContent); var contentModelPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath,DirectoryUtils.SiteTemplates.FileContentModel); var importObject = new ImportObject(publishmentSystemId); importObject.ImportFiles(siteTemplatePath, true); importObject.ImportTemplates(templateFilePath, true, administratorName); importObject.ImportAuxiliaryTables(tableDirectoryPath, isUseTables); importObject.ImportMenuDisplay(menuDisplayFilePath, true); importObject.ImportTagStyle(tagStyleFilePath, true); importObject.ImportAd(adFilePath, true); importObject.ImportSeo(seoFilePath, true); importObject.ImportStlTag(stlTagPath, true); importObject.ImportGatherRule(gatherRuleFilePath, true); importObject.ImportInput(inputDirectoryPath, true); importObject.ImportConfiguration(configurationFilePath); importObject.ImportContentModel(contentModelPath, true); var filePathArrayList = ImportObject.GetSiteContentFilePathArrayList(siteContentDirectoryPath); foreach (string filePath in filePathArrayList) { importObject.ImportSiteContent(siteContentDirectoryPath, filePath, isImportContents); } DataProvider.NodeDao.UpdateContentNum(publishmentSystemInfo); if (isImportTableStyles) { importObject.ImportTableStyles(tableDirectoryPath); } importObject.RemoveDbCache(); } } public static void ExportPublishmentSystemToSiteTemplate(PublishmentSystemInfo publishmentSystemInfo, string siteTemplateDir) { var exportObject = new ExportObject(publishmentSystemInfo.PublishmentSystemId); var siteTemplatePath = PathUtility.GetSiteTemplatesPath(siteTemplateDir); //导出模板 var templateFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTemplate); exportObject.ExportTemplates(templateFilePath); //导出辅助表及样式 var tableDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Table); exportObject.ExportTablesAndStyles(tableDirectoryPath); //导出下拉菜单 var menuDisplayFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileMenuDisplay); exportObject.ExportMenuDisplay(menuDisplayFilePath); //导出模板标签样式 var tagStyleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileTagStyle); exportObject.ExportTagStyle(tagStyleFilePath); //导出广告 var adFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileAd); exportObject.ExportAd(adFilePath); //导出采集规则 var gatherRuleFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileGatherRule); exportObject.ExportGatherRule(gatherRuleFilePath); //导出提交表单 var inputDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.Input); exportObject.ExportInput(inputDirectoryPath); //导出站点属性以及站点属性表单 var configurationFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileConfiguration); exportObject.ExportConfiguration(configurationFilePath); //导出SEO var seoFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileSeo); exportObject.ExportSeo(seoFilePath); //导出自定义模板语言 var stlTagFilePath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileStlTag); exportObject.ExportStlTag(stlTagFilePath); //导出关联字段 var relatedFieldDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.RelatedField); exportObject.ExportRelatedField(relatedFieldDirectoryPath); //导出内容模型(自定义添加的) var contentModelDirectoryPath = PathUtility.GetSiteTemplateMetadataPath(siteTemplatePath, DirectoryUtils.SiteTemplates.FileContentModel); exportObject.ExportContentModel(contentModelDirectoryPath); } } }
kk141242/siteserver
source/SiteServer.CMS/ImportExport/SiteTemplateManager.cs
C#
gpl-3.0
9,736
<?php function smarty_function_chart_date_range($params, &$smarty) { global $L; $name_id = $params["name_id"]; $default = $params["default"]; $lines = array(); $lines[] = "<select name=\"$name_id\" id=\"$name_id\">"; $lines[] = "<option value=\"everything\" " . (($default == "everything") ? "selected" : "") . ">{$L["phrase_all_time"]}</option>"; $lines[] = "<optgroup label=\"{$L["phrase_days_or_weeks"]}\">"; $lines[] = "<option value=\"last_7_days\" " . (($default == "last_7_days") ? "selected" : "") . ">{$L["phrase_last_7_days"]}</option>"; $lines[] = "<option value=\"last_10_days\" " . (($default == "last_10_days") ? "selected" : "") . ">{$L["phrase_last_10_days"]}</option>"; $lines[] = "<option value=\"last_14_days\" " . (($default == "last_14_days") ? "selected" : "") . ">{$L["phrase_last_2_weeks"]}</option>"; $lines[] = "<option value=\"last_21_days\" " . (($default == "last_21_days") ? "selected" : "") . ">{$L["phrase_last_3_weeks"]}</option>"; $lines[] = "<option value=\"last_30_days\" " . (($default == "last_30_days") ? "selected" : "") . ">{$L["phrase_last_30_days"]}</option>"; $lines[] = "</optgroup>"; $lines[] = "<optgroup label=\"{$L["word_months"]}\">"; $lines[] = "<option value=\"year_to_date\" " . (($default == "year_to_date") ? "selected" : "") . ">{$L["phrase_year_to_date"]}</option>"; $lines[] = "<option value=\"month_to_date\" " . (($default == "month_to_date") ? "selected" : "") . ">{$L["phrase_month_to_date"]}</option>"; $lines[] = "<option value=\"last_2_months\" " . (($default == "last_2_months") ? "selected" : "") . ">{$L["phrase_last_2_months"]}</option>"; $lines[] = "<option value=\"last_3_months\" " . (($default == "last_3_months") ? "selected" : "") . ">{$L["phrase_last_3_months"]}</option>"; $lines[] = "<option value=\"last_4_months\" " . (($default == "last_4_months") ? "selected" : "") . ">{$L["phrase_last_4_months"]}</option>"; $lines[] = "<option value=\"last_5_months\" " . (($default == "last_5_months") ? "selected" : "") . ">{$L["phrase_last_5_months"]}</option>"; $lines[] = "<option value=\"last_6_months\" " . (($default == "last_6_months") ? "selected" : "") . ">{$L["phrase_last_6_months"]}</option>"; $lines[] = "</optgroup>"; $lines[] = "<optgroup label=\"{$L["word_years"]}\">"; $lines[] = "<option value=\"last_12_months\" " . (($default == "last_12_months") ? "selected" : "") . ">{$L["phrase_last_12_months"]}</option>"; $lines[] = "<option value=\"last_2_years\" " . (($default == "last_2_years") ? "selected" : "") . ">{$L["phrase_last_2_years"]}</option>"; $lines[] = "<option value=\"last_3_years\" " . (($default == "last_3_years") ? "selected" : "") . ">{$L["phrase_last_3_years"]}</option>"; $lines[] = "<option value=\"last_4_years\" " . (($default == "last_4_years") ? "selected" : "") . ">{$L["phrase_last_4_years"]}</option>"; $lines[] = "<option value=\"last_5_years\" " . (($default == "last_5_years") ? "selected" : "") . ">{$L["phrase_last_5_years"]}</option>"; $lines[] = "</optgroup>"; $lines[] = "</select>"; echo implode("\n", $lines); }
formtools/module-data_visualization
smarty_plugins/function.chart_date_range.php
PHP
gpl-3.0
3,073
# Qt library # # Notes: # There's no performance penalty for importing all Qt modules into whichever modules # need access to at least some Qt modules, so for simplicity's sake that's what we'll do. from util import RequiredImportError from constants import PYSIDE, PYQT4 import qt_helper _qtLib = qt_helper.qtLib def QtLib(): """Returns PYSIDE or PYQT4, whichever is being used by the program.""" return _qtLib if _qtLib == PYSIDE: from PySide import QtGui, QtCore, QtSql from PySide.QtGui import * from PySide.QtCore import * from PySide.QtSql import * from PySide.phonon import Phonon elif _qtLib == PYQT4: import sip sip.setapi('QString', 2) # Prevent QString from being returned by PyQt4 functions. sip.setapi('QVariant', 2) # Prevent QVariant from being returned by PyQt4 functions. from PyQt4 import QtGui, QtCore, QtSql from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtSql import * from PyQt4.phonon import Phonon else: raise RequiredImportError('No Qt library found.')
pylonsoflight/kea
qt.py
Python
gpl-3.0
1,023
/* * This file is part of the L2J Global project. * * 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 com.l2jglobal.gameserver.network.clientpackets; import com.l2jglobal.Config; import com.l2jglobal.commons.network.PacketReader; import com.l2jglobal.gameserver.model.actor.instance.L2PcInstance; import com.l2jglobal.gameserver.network.client.L2GameClient; import com.l2jglobal.gameserver.network.serverpackets.NpcHtmlMessage; /** * @author Global */ public class ExPCCafeRequestOpenWindowWithoutNPC implements IClientIncomingPacket { @Override public boolean read(L2GameClient client, PacketReader packet) { return true; } @Override public void run(L2GameClient client) { final L2PcInstance activeChar = client.getActiveChar(); if ((activeChar != null) && Config.PC_CAFE_ENABLED) { final NpcHtmlMessage html = new NpcHtmlMessage(); html.setFile(activeChar.getHtmlPrefix(), "data/html/pccafe.htm"); activeChar.sendPacket(html); } } }
rubenswagner/L2J-Global
java/com/l2jglobal/gameserver/network/clientpackets/ExPCCafeRequestOpenWindowWithoutNPC.java
Java
gpl-3.0
1,579
<?php /** * Copyright (c) 2014 Educ-Action * * This file is part of ADES. * * ADES 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. * * ADES 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 ADES. If not, see <http://www.gnu.org/licenses/>. */ include ("inc/prive.inc.php"); include ("inc/funcdate.inc.php"); include ("inc/fonctions.inc.php"); include ("config/constantes.inc.php"); Normalisation(); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title><?php echo ECOLE ?></title> <link media="screen" rel="stylesheet" href="config/screen.css" type="text/css"> <link media="print" rel="stylesheet" href="config/print.css" type="text/css"> <link rel="stylesheet" href="config/menu.css" type="text/css" media="screen"> <script type="text/javascript" src="inc/overlib/overlib.js"><!-- overLIB (c) Erik Bosrup --> </script> </head> <body> <div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div> <?php // autorisations pour la page autoriser (); // tout le monde // menu require ("inc/menu.inc.php"); ?> <div id="texte"> <h2>Sélection du nom de l'élève</h2> <?php $classe=(isset($_REQUEST['classe'])?$_REQUEST['classe']:Null); include ("config/confbd.inc.php"); $lienDB = mysql_connect($sql_serveur, $sql_user, $sql_passwd); mysql_select_db ($sql_bdd); // Recherche des élèves qui figurent dans la classe $classe $sql = "select ideleve, nom, prenom FROM ades_eleves "; $sql .= "WHERE classe = '$classe' ORDER BY nom, prenom"; $listeEleves = @mysql_query($sql); // on passe les élèves en revue echo "<h3>$classe</h3>\n"; $n=1; while ($eleve = mysql_fetch_array($listeEleves)) { foreach ($eleve as $key=>$rubrique) $$key = $rubrique; echo "<a href=\"ficheel.php?mode=voir&amp;ideleve=$ideleve\">"; echo "$n -> $nom $prenom</a><br>\n"; $n++; } echo retourIndex (); mysql_close ($lienDB); ?> </div> <div id="pied"><?php require ("inc/notice.inc.php"); ?></div> </body> </html>
doc212/ades
web/nomeleve.php
PHP
gpl-3.0
2,540
/* Generated By:JJTree: Do not edit this line. ASTSQLOrderByElem.java */ package com.hardcode.gdbms.parser; public class ASTSQLOrderByElem extends SimpleNode { public ASTSQLOrderByElem(int id) { super(id); } public ASTSQLOrderByElem(SQLEngine p, int id) { super(p, id); } /** Accept the visitor. **/ public Object jjtAccept(SQLEngineVisitor visitor, Object data) { return visitor.visit(this, data); } }
iCarto/siga
libGDBMS/src/main/java/com/hardcode/gdbms/parser/ASTSQLOrderByElem.java
Java
gpl-3.0
434
#!/usr/bin/python -tt # An incredibly simple agent. All we do is find the closest enemy tank, drive # towards it, and shoot. Note that if friendly fire is allowed, you will very # often kill your own tanks with this code. ################################################################# # NOTE TO STUDENTS # This is a starting point for you. You will need to greatly # modify this code if you want to do anything useful. But this # should help you to know how to interact with BZRC in order to # get the information you need. # # After starting the bzrflag server, this is one way to start # this code: # python agent0.py [hostname] [port] # # Often this translates to something like the following (with the # port name being printed out by the bzrflag server): # python agent0.py localhost 49857 ################################################################# import sys import math import time from bzrc import BZRC, Command class Agent(object): """Class handles all command and control logic for a teams tanks.""" def __init__(self, bzrc): self.go_straight = True self.bzrc = bzrc self.constants = self.bzrc.get_constants() self.commands = [] def tick(self, time_diff, shoot=False): print 'time_dif', time_diff """Some time has passed; decide what to do next.""" mytanks, othertanks, flags, shots = self.bzrc.get_lots_o_stuff() self.mytanks = mytanks self.othertanks = othertanks self.flags = flags self.shots = shots self.enemies = [tank for tank in othertanks if tank.color != self.constants['team']] self.commands = [] if shoot: print 'shooting' for tank in mytanks: self.tanks_shoot(tank) else: print 'go straight' if self.go_straight else 'turn instead' for tank in mytanks: self.testing_tanks(tank) self.go_straight = not self.go_straight results = self.bzrc.do_commands(self.commands) return self.go_straight def tanks_shoot(self, tank): self.bzrc.shoot(tank.index) def testing_tanks(self, tank): if self.go_straight: command = Command(tank.index, 1, 0, 0) else: command = Command(tank.index, 0, 0.6, 0) self.commands.append(command) def attack_enemies(self, tank): """Find the closest enemy and chase it, shooting as you go.""" best_enemy = None best_dist = 2 * float(self.constants['worldsize']) for enemy in self.enemies: if enemy.status != 'alive': continue dist = math.sqrt((enemy.x - tank.x)**2 + (enemy.y - tank.y)**2) if dist < best_dist: best_dist = dist best_enemy = enemy if best_enemy is None: command = Command(tank.index, 0, 0, False) self.commands.append(command) else: self.move_to_position(tank, best_enemy.x, best_enemy.y) def move_to_position(self, tank, target_x, target_y): """Set command to move to given coordinates.""" target_angle = math.atan2(target_y - tank.y, target_x - tank.x) relative_angle = self.normalize_angle(target_angle - tank.angle) command = Command(tank.index, 1, 2 * relative_angle, True) self.commands.append(command) def normalize_angle(self, angle): """Make any angle be between +/- pi.""" angle -= 2 * math.pi * int (angle / (2 * math.pi)) if angle <= -math.pi: angle += 2 * math.pi elif angle > math.pi: angle -= 2 * math.pi return angle def main(): # Process CLI arguments. try: execname, host, port = sys.argv except ValueError: execname = sys.argv[0] print >>sys.stderr, '%s: incorrect number of arguments' % execname print >>sys.stderr, 'usage: %s hostname port' % sys.argv[0] sys.exit(-1) # Connect. #bzrc = BZRC(host, int(port), debug=True) bzrc = BZRC(host, int(port)) agent = Agent(bzrc) prev_time = time.time() prev_time_shoot = time.time() wait = 8 # Run the agent try: while True: if time.time() > prev_time_shoot + 2: agent.tick(time.time() - prev_time_shoot, True) prev_time_shoot = time.time() if time.time() > prev_time + wait: went_straight = agent.tick(time.time() - prev_time) wait = 3 if went_straight else 8 prev_time = time.time() except KeyboardInterrupt: print "Exiting due to keyboard interrupt." bzrc.close() if __name__ == '__main__': main() # vim: et sw=4 sts=4
sm-github/bzrflag
bzagents/dumb_agent.py
Python
gpl-3.0
4,903
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. $string['multichoicewiris'] = 'Multiple choice - science'; $string['multichoicewiris_help'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['editingmultichoicewiris'] = 'Editing a multiple choice - math & science question by WIRIS'; $string['addingmultichoicewiris'] = 'Adding a multiple choice - math & science question by WIRIS'; $string['multichoicewirissummary'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['multichoicewiris_algorithm'] = 'Algorithm'; $string['multichoicewiris_wiris_variables'] = 'WIRIS variables '; $string['multichoicewiris_cantimportoverride'] = 'The multiple choice - math & science question could not be imported properly from Moodle 1.9 format. The question can be manually fixed following the instructions at <a href="http://www.wiris.com/quizzes/docs/moodle/manual/multiple-choice#frommoodle1">http://www.wiris.com/quizzes/docs/moodle/manual/multiple-choice#frommoodle1</a>.'; // From Moodle 2.3. $string['pluginname'] = 'Multiple choice - science'; $string['pluginname_help'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['pluginnamesummary'] = 'Like the standard Multiple choice, but you can deliver different question text and choices by inserting random numbers, formulas or plots. The feedback can also use the random values.'; $string['pluginnameadding'] = 'Adding a multiple choice - math & science question by WIRIS'; $string['pluginnameediting'] = 'Editing a multiple choice - math & science question by WIRIS';
nitro2010/moodle
question/type/multichoicewiris/lang/en/qtype_multichoicewiris.php
PHP
gpl-3.0
2,595
package tripbooker.dto.domain.ticket; /** * * @author Pablo Albaladejo Mestre <pablo.albaladejo.mestre@gmail.com> */ public class TicketDOImp implements ITicketDO{ private int ticketID; private String code; private int userID; private int flightID; @Override public int getTicketID() { return ticketID; } @Override public void setTicketID(int ticketID) { this.ticketID = ticketID; } @Override public String getCode() { return code; } @Override public void setCode(String code) { this.code = code; } @Override public int getUserID() { return userID; } @Override public void setUserID(int userID) { this.userID = userID; } @Override public int getFlightID() { return flightID; } @Override public void setFlightID(int flightID) { this.flightID = flightID; } @Override public String toString() { return "TicketDOImp{" + "ticketID=" + ticketID + ", code=" + code + ", userID=" + userID + ", flightID=" + flightID + '}'; } }
pablo-albaladejo/javaee
proyecto/base/tripbooker/src/tripbooker/dto/domain/ticket/TicketDOImp.java
Java
gpl-3.0
1,133
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace multiFormList { public partial class FormLogin : Form { const string USERNAME = "admin"; const string PASSWORD = "0000"; public static string username; public FormLogin() { InitializeComponent(); } private void FormLogin_Load(object sender, EventArgs e) { textBox1.Focus(); username = ""; textBox1.Text = ""; textBox2.Text = ""; CenterToScreen(); textBox2.UseSystemPasswordChar = true; } private void button1_Click(object sender, EventArgs e) { if(textBox1.Text == USERNAME && textBox2.Text == PASSWORD) { username = USERNAME; this.Close(); } else { MessageBox.Show("帳號或密碼錯誤!", "錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error); username = ""; } textBox1.Text = ""; textBox2.Text = ""; } private void button2_Click(object sender, EventArgs e) { username = ""; textBox1.Text = ""; textBox2.Text = ""; this.Close(); } } }
aben20807/window_programming
practice/multiFormList/multiFormList/FormLogin.cs
C#
gpl-3.0
1,456
package br.edu.curso.mockito.exercicio.interacao.game; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestName; import br.edu.curso.mockito.exercicio.interacao.game.Dicionario.Tema; // TODO tratar espacos para incluir palavras compostas ou com hífen // TODO quando repetir letra que acertou, mostrar aviso, e se insistir, gameover com frase,: apelou! // TODO randomizar o tipo: fruta, pais public class ForcaTest { private Forca forca; private Dicionario dicionarioMock; private Desenhista desenhistaMock; private Coletor coletorMock; @Rule public TestName name = new TestName(); @Before public void before() { // mocks this.dicionarioMock = mock( Dicionario.class ); this.desenhistaMock = mock( Desenhista.class ); this.coletorMock = mock( Coletor.class ); // real this.forca = this.montarJogo(); System.out.println( "\n\n#" + name.getMethodName() ); } @Test public void acertoDireto() { when( dicionarioMock.eleger(any(Tema.class)) ).thenReturn("leopardo"); when( coletorMock.obter() ).thenReturn( "l" ); forca.jogar( Tema.animais ); verify( desenhistaMock, never() ).desenha( anyInt() ); } @Test public void acerto6Erros() { when( dicionarioMock.eleger(any(Tema.class)) ).thenReturn("leopardo"); when( coletorMock.obter() ).thenReturn( "x", "y", "w" ); forca.jogar( Tema.animais ); verify( desenhistaMock, times(7) ).desenha( anyInt() ); } private Forca montarJogo() { return Forca.builder() .dicionario( this.dicionarioMock ) .desenhista( this.desenhistaMock ) .coletor( coletorMock ) .build(); } }
rafarocha/ceshi
unit/ceshi-mockito/src/test/java/br/edu/curso/mockito/exercicio/interacao/game/ForcaTest.java
Java
gpl-3.0
1,935
package net.ramso.dita.bookmap; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import net.ramso.dita.utils.GenericData; /** * <p>Java class for frontmatter.class complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="frontmatter.class"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{}frontmatter.content"/> * &lt;/sequence> * &lt;attGroup ref="{}frontmatter.attributes"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "frontmatter.class", propOrder = { "booklistsOrNoticesOrDedication" }) @XmlSeeAlso({ Frontmatter.class }) public class FrontmatterClass extends GenericData { @XmlElements({ @XmlElement(name = "booklists", type = Booklists.class), @XmlElement(name = "notices", type = Notices.class), @XmlElement(name = "dedication", type = Dedication.class), @XmlElement(name = "colophon", type = Colophon.class), @XmlElement(name = "bookabstract", type = Bookabstract.class), @XmlElement(name = "draftintro", type = Draftintro.class), @XmlElement(name = "preface", type = Preface.class), @XmlElement(name = "topicref", type = Topicref.class), @XmlElement(name = "anchorref", type = Anchorref.class), @XmlElement(name = "keydef", type = Keydef.class), @XmlElement(name = "mapref", type = Mapref.class), @XmlElement(name = "topicgroup", type = Topicgroup.class), @XmlElement(name = "topichead", type = Topichead.class), @XmlElement(name = "topicset", type = Topicset.class), @XmlElement(name = "topicsetref", type = Topicsetref.class) }) protected List<java.lang.Object> booklistsOrNoticesOrDedication; @XmlAttribute(name = "keyref") protected String keyref; @XmlAttribute(name = "query") protected String query; @XmlAttribute(name = "outputclass") protected String outputclass; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NMTOKEN") protected String id; @XmlAttribute(name = "conref") protected String conref; @XmlAttribute(name = "conrefend") protected String conrefend; @XmlAttribute(name = "conaction") protected ConactionAttClass conaction; @XmlAttribute(name = "conkeyref") protected String conkeyref; @XmlAttribute(name = "translate") protected YesnoAttClass translate; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") protected String lang; @XmlAttribute(name = "dir") protected DirAttsClass dir; @XmlAttribute(name = "base") protected String base; @XmlAttribute(name = "rev") protected String rev; @XmlAttribute(name = "importance") protected ImportanceAttsClass importance; @XmlAttribute(name = "status") protected StatusAttsClass status; @XmlAttribute(name = "props") protected String props; @XmlAttribute(name = "platform") protected String platform; @XmlAttribute(name = "product") protected String product; @XmlAttribute(name = "audience") protected String audienceMod; @XmlAttribute(name = "otherprops") protected String otherprops; @XmlAttribute(name = "collection-type") protected CollectionTypeClass collectionType; @XmlAttribute(name = "type") protected String type; @XmlAttribute(name = "processing-role") protected ProcessingRoleAttClass processingRole; @XmlAttribute(name = "scope") protected ScopeAttClass scope; @XmlAttribute(name = "locktitle") protected YesnoAttClass locktitle; @XmlAttribute(name = "format") protected String format; @XmlAttribute(name = "linking") protected LinkingtypesClass linking; @XmlAttribute(name = "toc") protected YesnoAttClass toc; @XmlAttribute(name = "print") protected PrintAttClass print; @XmlAttribute(name = "search") protected YesnoAttClass search; @XmlAttribute(name = "chunk") protected String chunk; @XmlAttribute(name = "xtrc") protected String xtrc; @XmlAttribute(name = "xtrf") protected String xtrf; /** * Gets the value of the booklistsOrNoticesOrDedication property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the booklistsOrNoticesOrDedication property. * * <p> * For example, to add a new item, do as follows: * <pre> * getBooklistsOrNoticesOrDedication().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Booklists } * {@link Notices } * {@link Dedication } * {@link Colophon } * {@link Bookabstract } * {@link Draftintro } * {@link Preface } * {@link Topicref } * {@link Anchorref } * {@link Keydef } * {@link Mapref } * {@link Topicgroup } * {@link Topichead } * {@link Topicset } * {@link Topicsetref } * * */ public List<java.lang.Object> getBooklistsOrNoticesOrDedication() { if (booklistsOrNoticesOrDedication == null) { booklistsOrNoticesOrDedication = new ArrayList<java.lang.Object>(); } return this.booklistsOrNoticesOrDedication; } /** * Gets the value of the keyref property. * * @return * possible object is * {@link String } * */ public String getKeyref() { return keyref; } /** * Sets the value of the keyref property. * * @param value * allowed object is * {@link String } * */ public void setKeyref(String value) { this.keyref = value; } /** * Gets the value of the query property. * * @return * possible object is * {@link String } * */ public String getQuery() { return query; } /** * Sets the value of the query property. * * @param value * allowed object is * {@link String } * */ public void setQuery(String value) { this.query = value; } /** * Gets the value of the outputclass property. * * @return * possible object is * {@link String } * */ public String getOutputclass() { return outputclass; } /** * Sets the value of the outputclass property. * * @param value * allowed object is * {@link String } * */ public void setOutputclass(String value) { this.outputclass = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the conref property. * * @return * possible object is * {@link String } * */ public String getConref() { return conref; } /** * Sets the value of the conref property. * * @param value * allowed object is * {@link String } * */ public void setConref(String value) { this.conref = value; } /** * Gets the value of the conrefend property. * * @return * possible object is * {@link String } * */ public String getConrefend() { return conrefend; } /** * Sets the value of the conrefend property. * * @param value * allowed object is * {@link String } * */ public void setConrefend(String value) { this.conrefend = value; } /** * Gets the value of the conaction property. * * @return * possible object is * {@link ConactionAttClass } * */ public ConactionAttClass getConaction() { return conaction; } /** * Sets the value of the conaction property. * * @param value * allowed object is * {@link ConactionAttClass } * */ public void setConaction(ConactionAttClass value) { this.conaction = value; } /** * Gets the value of the conkeyref property. * * @return * possible object is * {@link String } * */ public String getConkeyref() { return conkeyref; } /** * Sets the value of the conkeyref property. * * @param value * allowed object is * {@link String } * */ public void setConkeyref(String value) { this.conkeyref = value; } /** * Gets the value of the translate property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getTranslate() { return translate; } /** * Sets the value of the translate property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setTranslate(YesnoAttClass value) { this.translate = value; } /** * Gets the value of the lang property. * * @return * possible object is * {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is * {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the dir property. * * @return * possible object is * {@link DirAttsClass } * */ public DirAttsClass getDir() { return dir; } /** * Sets the value of the dir property. * * @param value * allowed object is * {@link DirAttsClass } * */ public void setDir(DirAttsClass value) { this.dir = value; } /** * Gets the value of the base property. * * @return * possible object is * {@link String } * */ public String getBase() { return base; } /** * Sets the value of the base property. * * @param value * allowed object is * {@link String } * */ public void setBase(String value) { this.base = value; } /** * Gets the value of the rev property. * * @return * possible object is * {@link String } * */ public String getRev() { return rev; } /** * Sets the value of the rev property. * * @param value * allowed object is * {@link String } * */ public void setRev(String value) { this.rev = value; } /** * Gets the value of the importance property. * * @return * possible object is * {@link ImportanceAttsClass } * */ public ImportanceAttsClass getImportance() { return importance; } /** * Sets the value of the importance property. * * @param value * allowed object is * {@link ImportanceAttsClass } * */ public void setImportance(ImportanceAttsClass value) { this.importance = value; } /** * Gets the value of the status property. * * @return * possible object is * {@link StatusAttsClass } * */ public StatusAttsClass getStatus() { return status; } /** * Sets the value of the status property. * * @param value * allowed object is * {@link StatusAttsClass } * */ public void setStatus(StatusAttsClass value) { this.status = value; } /** * Gets the value of the props property. * * @return * possible object is * {@link String } * */ public String getProps() { return props; } /** * Sets the value of the props property. * * @param value * allowed object is * {@link String } * */ public void setProps(String value) { this.props = value; } /** * Gets the value of the platform property. * * @return * possible object is * {@link String } * */ public String getPlatform() { return platform; } /** * Sets the value of the platform property. * * @param value * allowed object is * {@link String } * */ public void setPlatform(String value) { this.platform = value; } /** * Gets the value of the product property. * * @return * possible object is * {@link String } * */ public String getProduct() { return product; } /** * Sets the value of the product property. * * @param value * allowed object is * {@link String } * */ public void setProduct(String value) { this.product = value; } /** * Gets the value of the audienceMod property. * * @return * possible object is * {@link String } * */ public String getAudienceMod() { return audienceMod; } /** * Sets the value of the audienceMod property. * * @param value * allowed object is * {@link String } * */ public void setAudienceMod(String value) { this.audienceMod = value; } /** * Gets the value of the otherprops property. * * @return * possible object is * {@link String } * */ public String getOtherprops() { return otherprops; } /** * Sets the value of the otherprops property. * * @param value * allowed object is * {@link String } * */ public void setOtherprops(String value) { this.otherprops = value; } /** * Gets the value of the collectionType property. * * @return * possible object is * {@link CollectionTypeClass } * */ public CollectionTypeClass getCollectionType() { return collectionType; } /** * Sets the value of the collectionType property. * * @param value * allowed object is * {@link CollectionTypeClass } * */ public void setCollectionType(CollectionTypeClass value) { this.collectionType = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } /** * Gets the value of the processingRole property. * * @return * possible object is * {@link ProcessingRoleAttClass } * */ public ProcessingRoleAttClass getProcessingRole() { return processingRole; } /** * Sets the value of the processingRole property. * * @param value * allowed object is * {@link ProcessingRoleAttClass } * */ public void setProcessingRole(ProcessingRoleAttClass value) { this.processingRole = value; } /** * Gets the value of the scope property. * * @return * possible object is * {@link ScopeAttClass } * */ public ScopeAttClass getScope() { return scope; } /** * Sets the value of the scope property. * * @param value * allowed object is * {@link ScopeAttClass } * */ public void setScope(ScopeAttClass value) { this.scope = value; } /** * Gets the value of the locktitle property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getLocktitle() { return locktitle; } /** * Sets the value of the locktitle property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setLocktitle(YesnoAttClass value) { this.locktitle = value; } /** * Gets the value of the format property. * * @return * possible object is * {@link String } * */ public String getFormat() { return format; } /** * Sets the value of the format property. * * @param value * allowed object is * {@link String } * */ public void setFormat(String value) { this.format = value; } /** * Gets the value of the linking property. * * @return * possible object is * {@link LinkingtypesClass } * */ public LinkingtypesClass getLinking() { return linking; } /** * Sets the value of the linking property. * * @param value * allowed object is * {@link LinkingtypesClass } * */ public void setLinking(LinkingtypesClass value) { this.linking = value; } /** * Gets the value of the toc property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getToc() { return toc; } /** * Sets the value of the toc property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setToc(YesnoAttClass value) { this.toc = value; } /** * Gets the value of the print property. * * @return * possible object is * {@link PrintAttClass } * */ public PrintAttClass getPrint() { return print; } /** * Sets the value of the print property. * * @param value * allowed object is * {@link PrintAttClass } * */ public void setPrint(PrintAttClass value) { this.print = value; } /** * Gets the value of the search property. * * @return * possible object is * {@link YesnoAttClass } * */ public YesnoAttClass getSearch() { return search; } /** * Sets the value of the search property. * * @param value * allowed object is * {@link YesnoAttClass } * */ public void setSearch(YesnoAttClass value) { this.search = value; } /** * Gets the value of the chunk property. * * @return * possible object is * {@link String } * */ public String getChunk() { return chunk; } /** * Sets the value of the chunk property. * * @param value * allowed object is * {@link String } * */ public void setChunk(String value) { this.chunk = value; } /** * Gets the value of the xtrc property. * * @return * possible object is * {@link String } * */ public String getXtrc() { return xtrc; } /** * Sets the value of the xtrc property. * * @param value * allowed object is * {@link String } * */ public void setXtrc(String value) { this.xtrc = value; } /** * Gets the value of the xtrf property. * * @return * possible object is * {@link String } * */ public String getXtrf() { return xtrf; } /** * Sets the value of the xtrf property. * * @param value * allowed object is * {@link String } * */ public void setXtrf(String value) { this.xtrf = value; } }
ramsodev/DitaManagement
dita/dita.bookmap/src/net/ramso/dita/bookmap/FrontmatterClass.java
Java
gpl-3.0
21,779
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@angular/core"); var user_service_1 = require("../../services/user.service"); var HomeComponent = (function () { function HomeComponent(userService) { this.userService = userService; this.users = []; } HomeComponent.prototype.ngOnInit = function () { var _this = this; // get users from secure api end point this.userService.getUsers() .subscribe(function (users) { _this.users = users; }); }; return HomeComponent; }()); HomeComponent = __decorate([ core_1.Component({ moduleId: module.id, templateUrl: 'home.component.html' }), __metadata("design:paramtypes", [user_service_1.UserService]) ], HomeComponent); exports.HomeComponent = HomeComponent; //# sourceMappingURL=home.component.js.map
umeshsohaliya/AngularSampleA
app/components/home/home.component.js
JavaScript
gpl-3.0
1,660
'use strict'; var BarcodeScan = require('com.tlantic.plugins.device.barcodescan.BarcodeScan'); var barcodeScan; exports.init = function (success, fail, args) { if (!barcodeScan) { barcodeScan = new BarcodeScan(); barcodeScan.onReceive = exports.rcMessage; barcodeScan.init(success, fail); } else { barcodeScan.endReceivingData(function () { barcodeScan.onReceive = exports.rcMessage; barcodeScan.init(success, fail); }); } }; exports.stop = function stop(success, fail, args) { barcodeScan.endReceivingData(success); }; // callback to receive data written on socket inputStream exports.rcMessage = function (scanLabel, scanData, scanType) { window.tlantic.plugins.device.barcodescan.receive(scanLabel, scanData, scanType); }; require('cordova/windows8/commandProxy').add('DeviceBarcodeScan', exports);
Tlantic/cdv-device-barcodescan-plugin
src/windows8/BarcodeScanProxy.js
JavaScript
gpl-3.0
897
// // njhseq - A library for analyzing sequence data // Copyright (C) 2012-2018 Nicholas Hathaway <nicholas.hathaway@umassmed.edu>, // // This file is part of njhseq. // // njhseq 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. // // njhseq 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 njhseq. If not, see <http://www.gnu.org/licenses/>. // /* * AlignerPool.cpp * * Created on: Jan 7, 2016 * Author: nick */ #include "AlignerPool.hpp" namespace njhseq { namespace concurrent { AlignerPool::AlignerPool(uint64_t startingMaxLen, const gapScoringParameters & gapInfo, const substituteMatrix & scoring, const size_t size) : startingMaxLen_(startingMaxLen), gapInfo_(gapInfo), scoring_(scoring), size_(size) { for(uint32_t i = 0; i < size_; ++i){ aligners_.emplace_back(aligner(startingMaxLen_, gapInfo_, scoring_)); } } AlignerPool::AlignerPool(const aligner & alignerObj, const size_t size) : startingMaxLen_(alignerObj.parts_.maxSize_), gapInfo_(alignerObj.parts_.gapScores_), scoring_( alignerObj.parts_.scoring_), size_(size) { for (uint32_t i = 0; i < size_; ++i) { aligners_.emplace_back(alignerObj); } } AlignerPool::AlignerPool(const size_t size) : size_(size) { startingMaxLen_ = 400; gapInfo_ = gapScoringParameters(5, 1); scoring_.setWithSimple(2, -2); for(uint32_t i = 0; i < size_; ++i){ aligners_.emplace_back(aligner(startingMaxLen_, gapInfo_, scoring_)); } } AlignerPool::AlignerPool(const AlignerPool& that) : startingMaxLen_(that.startingMaxLen_), gapInfo_(that.gapInfo_), scoring_(that.scoring_), size_( that.size_) { for(uint32_t i = 0; i < size_; ++i){ aligners_.emplace_back(aligner(startingMaxLen_, gapInfo_, scoring_)); } } AlignerPool::~AlignerPool() { std::lock_guard<std::mutex> lock(poolmtx_); // GUARD destoryAlignersNoLock(); } void AlignerPool::initAligners(){ std::lock_guard<std::mutex> lock(poolmtx_); // GUARD // now push them onto the queue for (aligner& alignerObj : aligners_) { alignerObj.processAlnInfoInput(inAlnDir_); pushAligner(alignerObj); } } void AlignerPool::destoryAligners(){ std::lock_guard<std::mutex> lock(poolmtx_); // GUARD destoryAlignersNoLock(); } void AlignerPool::destoryAlignersNoLock(){ closing_ = true; { //merge the alignment of the other aligners into one and then write to avoid duplications PooledAligner first_aligner_ptr; queue_.waitPop(first_aligner_ptr); if(size_ > 1){ for (size_t i = 1; i < size_; ++i) { PooledAligner aligner_ptr; queue_.waitPop(aligner_ptr); if("" != outAlnDir_){ first_aligner_ptr->alnHolder_.mergeOtherHolder(aligner_ptr->alnHolder_); } } } if("" != outAlnDir_){ first_aligner_ptr->processAlnInfoOutput(outAlnDir_, false); } } } void AlignerPool::pushAligner(aligner& alignerObj){ if(!closing_){ AlignerPool* p = this; queue_.push( std::shared_ptr<aligner>(&alignerObj, [p](aligner* alignerObj) { p->pushAligner(*alignerObj); })); } } PooledAligner AlignerPool::popAligner() { PooledAligner aligner_ptr; queue_.waitPop(aligner_ptr); return aligner_ptr; } } // namespace concurrent } // namespace njhseq
bailey-lab/bibseq
src/njhseq/concurrency/pools/AlignerPool.cpp
C++
gpl-3.0
3,615
<?php /* * Copyright (C) 2015 Biospex * biospex@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 <https://www.gnu.org/licenses/>. */ namespace App\Listeners; use Illuminate\Support\Facades\Cache; /** * Class CacheEventSubscriber * * @package App\Listeners */ class CacheEventSubscriber { /** * Register the listeners for the subscriber. * * @param $events */ public function subscribe($events) { $events->listen( 'cache.flush', 'App\Listeners\CacheEventSubscriber@flush' ); } /** * Flush tag * @param $tag */ public function flush($tag) { Cache::tags((string) $tag)->flush(); } }
iDigBio/Biospex
app/Listeners/CacheEventSubscriber.php
PHP
gpl-3.0
1,285
/* * Copyright (C) 2017 Timo Vesalainen <timo.vesalainen@iki.fi> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.vesalainen.vfs.attributes; import java.nio.ByteBuffer; import java.nio.file.attribute.AclFileAttributeView; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.DosFileAttributeView; import java.nio.file.attribute.FileAttributeView; import java.nio.file.attribute.FileOwnerAttributeView; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.GroupPrincipal; import java.nio.file.attribute.PosixFileAttributeView; import java.nio.file.attribute.UserDefinedFileAttributeView; import java.nio.file.attribute.UserPrincipal; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.vesalainen.util.Bijection; import org.vesalainen.util.HashBijection; import org.vesalainen.util.HashMapSet; import org.vesalainen.util.CollectionHelp; import org.vesalainen.util.MapSet; import org.vesalainen.vfs.unix.UnixFileAttributeView; /** * * @author Timo Vesalainen <timo.vesalainen@iki.fi> */ public final class FileAttributeName { public static final String BASIC_VIEW = "basic"; public static final String ACL_VIEW = "acl"; public static final String POSIX_VIEW = "posix"; public static final String OWNER_VIEW = "owner"; public static final String DOS_VIEW = "dos"; public static final String USER_VIEW = "user"; public static final String UNIX_VIEW = "org.vesalainen.vfs.unix"; public static final String DIGEST_VIEW = "org.vesalainen.vfs.digest"; // digest public static final String CONTENT = DIGEST_VIEW+":org.vesalainen.vfs.content"; public static final String CPIO_CHECKSUM = DIGEST_VIEW+":org.vesalainen.vfs.cpiochecksum"; public static final String CRC32 = DIGEST_VIEW+":org.vesalainen.vfs.crc32"; public static final String MD5 = DIGEST_VIEW+":org.vesalainen.vfs.md5"; public static final String SHA1 = DIGEST_VIEW+":org.vesalainen.vfs.sha1"; public static final String SHA256 = DIGEST_VIEW+":org.vesalainen.vfs.sha256"; public static final String DEVICE = UNIX_VIEW+":org.vesalainen.vfs.device"; public static final String INODE = UNIX_VIEW+":org.vesalainen.vfs.inode"; public static final String NLINK = UNIX_VIEW+":org.vesalainen.vfs.nlink"; public static final String SETUID = UNIX_VIEW+":org.vesalainen.vfs.setuid"; public static final String SETGID = UNIX_VIEW+":org.vesalainen.vfs.setgid"; public static final String STICKY = UNIX_VIEW+":org.vesalainen.vfs.sticky"; // posix public static final String PERMISSIONS = "posix:permissions"; public static final String GROUP = "posix:group"; // basic public static final String LAST_MODIFIED_TIME = "basic:lastModifiedTime"; public static final String LAST_ACCESS_TIME = "basic:lastAccessTime"; public static final String CREATION_TIME = "basic:creationTime"; public static final String SIZE = "basic:size"; public static final String IS_REGULAR = "basic:isRegularFile"; public static final String IS_DIRECTORY = "basic:isDirectory"; public static final String IS_SYMBOLIC_LINK = "basic:isSymbolicLink"; public static final String IS_OTHER = "basic:isOther"; public static final String FILE_KEY = "basic:fileKey"; public static final String OWNER = "owner:owner"; public static final String ACL = "acl:acl"; public static final String READONLY = "dos:readonly"; public static final String HIDDEN = "dos:hidden"; public static final String SYSTEM = "dos:system"; public static final String ARCHIVE = "dos:archive"; private static final Map<String,Class<?>> types; private static final Bijection<String,Class<? extends FileAttributeView>> nameView; private static final MapSet<String,String> impliesMap = new HashMapSet<>(); private static final Map<String,Name> nameMap = new HashMap<>(); static { addName(DEVICE); addName(INODE); addName(NLINK); addName(SETUID); addName(SETGID); addName(STICKY); // posix addName(PERMISSIONS); addName(GROUP); // basic addName(LAST_MODIFIED_TIME); addName(LAST_ACCESS_TIME); addName(CREATION_TIME); addName(SIZE); addName(IS_REGULAR); addName(IS_DIRECTORY); addName(IS_SYMBOLIC_LINK); addName(IS_OTHER); addName(FILE_KEY); addName(OWNER); addName(ACL); addName(READONLY); addName(HIDDEN); addName(SYSTEM); addName(ARCHIVE); addName(CONTENT); addName(CPIO_CHECKSUM); addName(CRC32); addName(MD5); addName(SHA1); addName(SHA256); types = new HashMap<>(); types.put(DEVICE, Integer.class); types.put(INODE, Integer.class); types.put(NLINK, Integer.class); types.put(SETUID, Boolean.class); types.put(SETGID, Boolean.class); types.put(STICKY, Boolean.class); types.put(PERMISSIONS, Set.class); types.put(GROUP, GroupPrincipal.class); types.put(OWNER, UserPrincipal.class); types.put(LAST_MODIFIED_TIME, FileTime.class); types.put(LAST_ACCESS_TIME, FileTime.class); types.put(CREATION_TIME, FileTime.class); types.put(SIZE, Long.class); types.put(IS_REGULAR, Boolean.class); types.put(IS_DIRECTORY, Boolean.class); types.put(IS_SYMBOLIC_LINK, Boolean.class); types.put(IS_OTHER, Boolean.class); types.put(FILE_KEY, Boolean.class); nameView = new HashBijection<>(); nameView.put(BASIC_VIEW, BasicFileAttributeView.class); nameView.put(ACL_VIEW, AclFileAttributeView.class); nameView.put(DOS_VIEW, DosFileAttributeView.class); nameView.put(OWNER_VIEW, FileOwnerAttributeView.class); nameView.put(POSIX_VIEW, PosixFileAttributeView.class); nameView.put(USER_VIEW, UserDefinedFileAttributeView.class); nameView.put(UNIX_VIEW, UnixFileAttributeView.class); nameView.put(DIGEST_VIEW, DigestFileAttributeView.class); initImplies(BASIC_VIEW); initImplies(ACL_VIEW); initImplies(DOS_VIEW); initImplies(OWNER_VIEW); initImplies(POSIX_VIEW); initImplies(USER_VIEW); initImplies(UNIX_VIEW); initImplies(DIGEST_VIEW); } private static void initImplies(String view) { Class<? extends FileAttributeView> viewClass = nameView.getSecond(view); initImplies(view, viewClass); } private static void initImplies(String view, Class<? extends FileAttributeView> viewClass) { String name = nameView.getFirst(viewClass); if (name != null) { impliesMap.add(view, name); } for (Class<?> itf : viewClass.getInterfaces()) { if (FileAttributeView.class.isAssignableFrom(itf)) { initImplies(view, (Class<? extends FileAttributeView>) itf); } } } /** * Returns a set that contains given views as well as all implied views. * @param views * @return */ public static final Set<String> impliedSet(String... views) { Set<String> set = new HashSet<>(); for (String view : views) { set.addAll(impliesMap.get(view)); } return set; } public static final Set<String> topViews(Set<String> views) { return topViews(CollectionHelp.toArray(views, String.class)); } public static final Set<String> topViews(String... views) { Set<String> set = Arrays.stream(views).collect(Collectors.toSet()); int len = views.length; for (int ii=0;ii<len;ii++) { String view = views[ii]; for (int jj=0;jj<len;jj++) { if (ii != jj) { Set<String> is = impliesMap.get(views[jj]); if (is.contains(view)) { set.remove(view); } } } } return set; } public static final Class<?> type(Name name) { return types.get(name.toString()); } public static final void check(Name name, Object value) { Objects.requireNonNull(value, "value can't be null"); if (DIGEST_VIEW.equals(name.view)) { if (!value.getClass().equals(byte[].class) && !(value instanceof ByteBuffer)) { throw new ClassCastException(value+" not expected type byte[]/ByteBuffer"); } } else { if (USER_VIEW.equals(name.view)) { if (!value.getClass().equals(byte[].class) && !(value instanceof ByteBuffer)) { throw new ClassCastException(value+" not expected type byte[]/ByteBuffer"); } } else { Class<?> type = FileAttributeName.type(name); if (type == null || !type.isAssignableFrom(value.getClass())) { throw new ClassCastException(value+" not expected type "+type); } } } } private static void addName(String attr) { Name name = getInstance(attr); Name old = nameMap.put(name.name, name); if (old != null) { throw new IllegalArgumentException(name+" ambiguous"); } } public static class FileAttributeNameMatcher { private Set<String> views; private String[] attributes; public FileAttributeNameMatcher(String expr) { String view = BASIC_VIEW; int idx = expr.indexOf(':'); if (idx != -1) { view = expr.substring(0, idx); expr = expr.substring(idx+1); } if (expr.startsWith("*")) { if (expr.length() != 1) { throw new IllegalArgumentException(expr+" invalid"); } } else { attributes = expr.split(","); } views = impliesMap.get(view); if (views == null) { throw new UnsupportedOperationException(view+" not supported"); } } public boolean any(String name) { return any(getInstance(name)); } public boolean any(Name name) { if (!views.contains(name.view)) { return false; } if (attributes == null) { return true; } else { for (String at : attributes) { if (at.equals(name.name)) { return true; } } } return false; } } public static final Name getInstance(String attribute) { Name name = nameMap.get(attribute); if (name == null) { String view; String attr; int idx = attribute.indexOf(':'); if (idx != -1) { view = attribute.substring(0, idx); attr = attribute.substring(idx+1); name = new Name(view, attr); } else { view = BASIC_VIEW; attr = attribute; name = new Name(view, attr); nameMap.put(attr, name); } nameMap.put(attribute, name); } return name; } public static class Name { private String view; private String name; private String string; public Name(String view, String name) { this.view = view; this.name = name; this.string = view+':'+name; } public String getView() { return view; } public String getName() { return name; } @Override public String toString() { return string; } } }
tvesalainen/util
vfs/src/main/java/org/vesalainen/vfs/attributes/FileAttributeName.java
Java
gpl-3.0
13,646
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 2011 OpenFOAM Foundation \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>. InNamespace Foam Description Bound the given scalar field if it has gone unbounded. Used extensively in RAS and LES turbulence models, but also of use within solvers. SourceFiles bound.C \*---------------------------------------------------------------------------*/ #ifndef bound_H #define bound_H #include "OpenFOAM-2.1.x/src/OpenFOAM/dimensionedTypes/dimensionedScalar/dimensionedScalar.H" #include "OpenFOAM-2.1.x/src/finiteVolume/fields/volFields/volFieldsFwd.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { // * * * * * * * * * * * * * * * Global Functions * * * * * * * * * * * * * // //- Bound the given scalar field if it has gone unbounded. // Return the bounded field. // Used extensively in RAS and LES turbulence models. volScalarField& bound(volScalarField&, const dimensionedScalar& lowerBound); // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
kempj/OpenFOAM-win
src/finiteVolume/cfdTools/general/bound/bound.H
C++
gpl-3.0
2,244
package de.macbury.botlogic.core.ui.code_editor.js; import java.io.Reader; /** * A simple Java source file parser for syntax highlighting. * * @author Matthias Mann */ public class JavaScriptScanner { public enum Kind { /** End of file - this token has no text */ EOF, /** End of line - this token has no text */ NEWLINE, /** Normal text - does not include line breaks */ NORMAL, /** A keyword */ KEYWORD, /** A string or character constant */ STRING, /** A comment - multi line comments are split up and {@link NEWLINE} tokens are inserted */ COMMENT, /** A javadoc tag inside a comment */ COMMENT_TAG, NUMBER, SPECIAL_KEYWORD } private static final KeywordList KEYWORD_LIST = new KeywordList( "function", "true", "false", "var", "for", "while", "if", "else", "null", "this", "new", "switch", "case", "break", "try", "catch", "do", "instanceof", "return", "throw", "typeof", "with", "prototype"); private static final KeywordList SPECIAL_KEYWORD_LIST = new KeywordList("robot", "led", "sonar", "console"); private final CharacterIterator iterator; private boolean inMultiLineComment; public JavaScriptScanner(CharSequence cs) { this.iterator = new CharacterIterator(cs); } public JavaScriptScanner(Reader r) { this.iterator = new CharacterIterator(r); } /** * Scans for the next token. * Read errors result in EOF. * * Use {@link #getString()} to retrieve the string for the parsed token. * * @return the next token. */ public Kind scan() { iterator.clear(); if(inMultiLineComment) { return scanMultiLineComment(false); } int ch = iterator.next(); switch(ch) { case CharacterIterator.EOF: return Kind.EOF; case '\n': return Kind.NEWLINE; case '\"': case '\'': scanString(ch); return Kind.STRING; case '/': switch(iterator.peek()) { case '/': iterator.advanceToEOL(); return Kind.COMMENT; case '*': inMultiLineComment = true; iterator.next(); // skip '*' return scanMultiLineComment(true); } // fall through default: return scanNormal(ch); } } /** * Returns the string for the last token returned by {@link #scan() } * * @return the string for the last token */ public String getString() { return iterator.getString(); } public int getCurrentPosition() { return iterator.getCurrentPosition(); } private void scanString(int endMarker) { for(;;) { int ch = iterator.next(); if(ch == '\\') { iterator.next(); } else if(ch == '\n') { iterator.pushback(); return; } else if(ch == endMarker || ch == '\n' || ch == '\r' || ch < 0) { return; } } } private Kind scanMultiLineComment(boolean start) { int ch = iterator.next(); if(!start && ch == '\n') { return Kind.NEWLINE; } if(ch == '@') { iterator.advanceIdentifier(); return Kind.COMMENT_TAG; } for(;;) { if(ch < 0 || (ch == '*' && iterator.peek() == '/')) { iterator.next(); inMultiLineComment = false; return Kind.COMMENT; } if(ch == '\n') { iterator.pushback(); return Kind.COMMENT; } if(ch == '@') { iterator.pushback(); return Kind.COMMENT; } ch = iterator.next(); } } private Kind scanNormal(int ch) { for(;;) { switch(ch) { case '\n': case '\"': case '\'': case CharacterIterator.EOF: iterator.pushback(); return Kind.NORMAL; case '/': if(iterator.check("/*")) { iterator.pushback(); return Kind.NORMAL; } break; default: if(Character.isJavaIdentifierStart(ch)) { iterator.setMarker(true); iterator.advanceIdentifier(); if(iterator.isKeyword(KEYWORD_LIST)) { if(iterator.isMarkerAtStart()) { return Kind.KEYWORD; } iterator.rewindToMarker(); return Kind.NORMAL; } else if(iterator.isKeyword(SPECIAL_KEYWORD_LIST)) { if(iterator.isMarkerAtStart()) { return Kind.SPECIAL_KEYWORD; } iterator.rewindToMarker(); return Kind.NORMAL; } else if (Character.isDigit(ch)) { return Kind.NUMBER; } } break; } ch = iterator.next(); } } }
macbury/BotLogic
src/de/macbury/botlogic/core/ui/code_editor/js/JavaScriptScanner.java
Java
gpl-3.0
4,698
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org> # # This file is part of qutebrowser. # # qutebrowser 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. # # qutebrowser 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 qutebrowser. If not, see <https://www.gnu.org/licenses/>. """Tests for qutebrowser.misc.ipc.""" import os import pathlib import getpass import logging import json import hashlib import dataclasses from unittest import mock from typing import Optional, List import pytest from PyQt5.QtCore import pyqtSignal, QObject from PyQt5.QtNetwork import QLocalServer, QLocalSocket, QAbstractSocket from PyQt5.QtTest import QSignalSpy import qutebrowser from qutebrowser.misc import ipc from qutebrowser.utils import standarddir, utils from helpers import stubs, utils as testutils pytestmark = pytest.mark.usefixtures('qapp') @pytest.fixture(autouse=True) def shutdown_server(): """If ipc.send_or_listen was called, make sure to shut server down.""" yield if ipc.server is not None: ipc.server.shutdown() @pytest.fixture def ipc_server(qapp, qtbot): server = ipc.IPCServer('qute-test') yield server if (server._socket is not None and server._socket.state() != QLocalSocket.UnconnectedState): with qtbot.waitSignal(server._socket.disconnected, raising=False): server._socket.abort() try: server.shutdown() except ipc.Error: pass @pytest.fixture def qlocalserver(qapp): server = QLocalServer() yield server server.close() server.deleteLater() @pytest.fixture def qlocalsocket(qapp): socket = QLocalSocket() yield socket socket.disconnectFromServer() if socket.state() != QLocalSocket.UnconnectedState: socket.waitForDisconnected(1000) @pytest.fixture(autouse=True) def fake_runtime_dir(monkeypatch, short_tmpdir): monkeypatch.setenv('XDG_RUNTIME_DIR', str(short_tmpdir)) standarddir._init_runtime(args=None) return short_tmpdir class FakeSocket(QObject): """A stub for a QLocalSocket. Args: _can_read_line_val: The value returned for canReadLine(). _error_val: The value returned for error(). _state_val: The value returned for state(). _connect_successful: The value returned for waitForConnected(). """ readyRead = pyqtSignal() # noqa: N815 disconnected = pyqtSignal() def __init__(self, *, error=QLocalSocket.UnknownSocketError, state=None, data=None, connect_successful=True, parent=None): super().__init__(parent) self._error_val = error self._state_val = state self._data = data self._connect_successful = connect_successful self.error = stubs.FakeSignal('error', func=self._error) def _error(self): return self._error_val def state(self): return self._state_val def canReadLine(self): return bool(self._data) def readLine(self): firstline, mid, rest = self._data.partition(b'\n') self._data = rest return firstline + mid def errorString(self): return "Error string" def abort(self): self.disconnected.emit() def disconnectFromServer(self): pass def connectToServer(self, _name): pass def waitForConnected(self, _time): return self._connect_successful def writeData(self, _data): pass def waitForBytesWritten(self, _time): pass def waitForDisconnected(self, _time): pass class FakeServer: def __init__(self, socket): self._socket = socket def nextPendingConnection(self): socket = self._socket self._socket = None return socket def close(self): pass def deleteLater(self): pass def test_getpass_getuser(): """Make sure getpass.getuser() returns something sensible.""" assert getpass.getuser() def md5(inp): return hashlib.md5(inp.encode('utf-8')).hexdigest() class TestSocketName: WINDOWS_TESTS = [ (None, 'qutebrowser-testusername'), ('/x', 'qutebrowser-testusername-{}'.format(md5('/x'))), ] @pytest.fixture(autouse=True) def patch_user(self, monkeypatch): monkeypatch.setattr(ipc.getpass, 'getuser', lambda: 'testusername') @pytest.mark.parametrize('basedir, expected', WINDOWS_TESTS) @pytest.mark.windows def test_windows(self, basedir, expected): socketname = ipc._get_socketname(basedir) assert socketname == expected @pytest.mark.parametrize('basedir, expected', WINDOWS_TESTS) def test_windows_on_posix(self, basedir, expected): socketname = ipc._get_socketname_windows(basedir) assert socketname == expected def test_windows_broken_getpass(self, monkeypatch): def _fake_username(): raise ImportError monkeypatch.setattr(ipc.getpass, 'getuser', _fake_username) with pytest.raises(ipc.Error, match='USERNAME'): ipc._get_socketname_windows(basedir=None) @pytest.mark.mac @pytest.mark.parametrize('basedir, expected', [ (None, 'i-{}'.format(md5('testusername'))), ('/x', 'i-{}'.format(md5('testusername-/x'))), ]) def test_mac(self, basedir, expected): socketname = ipc._get_socketname(basedir) parts = socketname.split(os.sep) assert parts[-2] == 'qutebrowser' assert parts[-1] == expected @pytest.mark.linux @pytest.mark.parametrize('basedir, expected', [ (None, 'ipc-{}'.format(md5('testusername'))), ('/x', 'ipc-{}'.format(md5('testusername-/x'))), ]) def test_linux(self, basedir, fake_runtime_dir, expected): socketname = ipc._get_socketname(basedir) expected_path = str(fake_runtime_dir / 'qutebrowser' / expected) assert socketname == expected_path def test_other_unix(self): """Fake test for POSIX systems which aren't Linux/macOS. We probably would adjust the code first to make it work on that platform. """ if utils.is_windows: pass elif utils.is_mac: pass elif utils.is_linux: pass else: raise Exception("Unexpected platform!") class TestExceptions: def test_listen_error(self, qlocalserver): qlocalserver.listen(None) exc = ipc.ListenError(qlocalserver) assert exc.code == 2 assert exc.message == "QLocalServer::listen: Name error" msg = ("Error while listening to IPC server: QLocalServer::listen: " "Name error (error 2)") assert str(exc) == msg with pytest.raises(ipc.Error): raise exc def test_socket_error(self, qlocalserver): socket = FakeSocket(error=QLocalSocket.ConnectionRefusedError) exc = ipc.SocketError("testing", socket) assert exc.code == QLocalSocket.ConnectionRefusedError assert exc.message == "Error string" assert str(exc) == "Error while testing: Error string (error 0)" with pytest.raises(ipc.Error): raise exc class TestListen: @pytest.mark.posix def test_remove_error(self, ipc_server, monkeypatch): """Simulate an error in _remove_server.""" monkeypatch.setattr(ipc_server, '_socketname', None) with pytest.raises(ipc.Error, match="Error while removing server None!"): ipc_server.listen() def test_error(self, ipc_server, monkeypatch): """Simulate an error while listening.""" monkeypatch.setattr(ipc.QLocalServer, 'removeServer', lambda self: True) monkeypatch.setattr(ipc_server, '_socketname', None) with pytest.raises(ipc.ListenError): ipc_server.listen() @pytest.mark.posix def test_in_use(self, qlocalserver, ipc_server, monkeypatch): monkeypatch.setattr(ipc.QLocalServer, 'removeServer', lambda self: True) qlocalserver.listen('qute-test') with pytest.raises(ipc.AddressInUseError): ipc_server.listen() def test_successful(self, ipc_server): ipc_server.listen() @pytest.mark.windows def test_permissions_windows(self, ipc_server): opts = ipc_server._server.socketOptions() assert opts == QLocalServer.UserAccessOption @pytest.mark.posix def test_permissions_posix(self, ipc_server): ipc_server.listen() sockfile = ipc_server._server.fullServerName() sockdir = pathlib.Path(sockfile).parent file_stat = os.stat(sockfile) dir_stat = sockdir.stat() # pylint: disable=no-member,useless-suppression file_owner_ok = file_stat.st_uid == os.getuid() dir_owner_ok = dir_stat.st_uid == os.getuid() # pylint: enable=no-member,useless-suppression file_mode_ok = file_stat.st_mode & 0o777 == 0o700 dir_mode_ok = dir_stat.st_mode & 0o777 == 0o700 print('sockdir: {} / owner {} / mode {:o}'.format( sockdir, dir_stat.st_uid, dir_stat.st_mode)) print('sockfile: {} / owner {} / mode {:o}'.format( sockfile, file_stat.st_uid, file_stat.st_mode)) assert file_owner_ok or dir_owner_ok assert file_mode_ok or dir_mode_ok @pytest.mark.posix def test_atime_update(self, qtbot, ipc_server): ipc_server._atime_timer.setInterval(500) # We don't want to wait ipc_server.listen() old_atime = os.stat(ipc_server._server.fullServerName()).st_atime_ns with qtbot.waitSignal(ipc_server._atime_timer.timeout, timeout=2000): pass # Make sure the timer is not singleShot with qtbot.waitSignal(ipc_server._atime_timer.timeout, timeout=2000): pass new_atime = os.stat(ipc_server._server.fullServerName()).st_atime_ns assert old_atime != new_atime @pytest.mark.posix def test_atime_update_no_name(self, qtbot, caplog, ipc_server): with caplog.at_level(logging.ERROR): ipc_server.update_atime() assert caplog.messages[-1] == "In update_atime with no server path!" @pytest.mark.posix def test_atime_shutdown_typeerror(self, qtbot, ipc_server): """This should never happen, but let's handle it gracefully.""" ipc_server._atime_timer.timeout.disconnect(ipc_server.update_atime) ipc_server.shutdown() @pytest.mark.posix def test_vanished_runtime_file(self, qtbot, caplog, ipc_server): ipc_server._atime_timer.setInterval(500) # We don't want to wait ipc_server.listen() sockfile = pathlib.Path(ipc_server._server.fullServerName()) sockfile.unlink() with caplog.at_level(logging.ERROR): with qtbot.waitSignal(ipc_server._atime_timer.timeout, timeout=2000): pass msg = 'Failed to update IPC socket, trying to re-listen...' assert caplog.messages[-1] == msg assert ipc_server._server.isListening() assert sockfile.exists() class TestOnError: def test_closed(self, ipc_server): ipc_server._socket = QLocalSocket() ipc_server._timer.timeout.disconnect() ipc_server._timer.start() ipc_server.on_error(QLocalSocket.PeerClosedError) assert not ipc_server._timer.isActive() def test_other_error(self, ipc_server, monkeypatch): socket = QLocalSocket() ipc_server._socket = socket monkeypatch.setattr(socket, 'error', lambda: QLocalSocket.ConnectionRefusedError) monkeypatch.setattr(socket, 'errorString', lambda: "Connection refused") socket.setErrorString("Connection refused.") with pytest.raises(ipc.Error, match=r"Error while handling IPC " r"connection: Connection refused \(error 0\)"): ipc_server.on_error(QLocalSocket.ConnectionRefusedError) class TestHandleConnection: def test_ignored(self, ipc_server, monkeypatch): m = mock.Mock(spec=[]) monkeypatch.setattr(ipc_server._server, 'nextPendingConnection', m) ipc_server.ignored = True ipc_server.handle_connection() m.assert_not_called() def test_no_connection(self, ipc_server, caplog): ipc_server.handle_connection() assert caplog.messages[-1] == "No new connection to handle." def test_double_connection(self, qlocalsocket, ipc_server, caplog): ipc_server._socket = qlocalsocket ipc_server.handle_connection() msg = ("Got new connection but ignoring it because we're still " "handling another one") assert any(message.startswith(msg) for message in caplog.messages) def test_disconnected_immediately(self, ipc_server, caplog): socket = FakeSocket(state=QLocalSocket.UnconnectedState) ipc_server._server = FakeServer(socket) ipc_server.handle_connection() assert "Socket was disconnected immediately." in caplog.messages def test_error_immediately(self, ipc_server, caplog): socket = FakeSocket(error=QLocalSocket.ConnectionError) ipc_server._server = FakeServer(socket) with pytest.raises(ipc.Error, match=r"Error while handling IPC " r"connection: Error string \(error 7\)"): ipc_server.handle_connection() assert "We got an error immediately." in caplog.messages def test_read_line_immediately(self, qtbot, ipc_server, caplog): data = ('{{"args": ["foo"], "target_arg": "tab", ' '"protocol_version": {}}}\n'.format(ipc.PROTOCOL_VERSION)) socket = FakeSocket(data=data.encode('utf-8')) ipc_server._server = FakeServer(socket) with qtbot.waitSignal(ipc_server.got_args) as blocker: ipc_server.handle_connection() assert blocker.args == [['foo'], 'tab', ''] assert "We can read a line immediately." in caplog.messages @pytest.fixture def connected_socket(qtbot, qlocalsocket, ipc_server): if utils.is_mac: pytest.skip("Skipping connected_socket test - " "https://github.com/qutebrowser/qutebrowser/issues/1045") ipc_server.listen() with qtbot.waitSignal(ipc_server._server.newConnection): qlocalsocket.connectToServer('qute-test') yield qlocalsocket qlocalsocket.disconnectFromServer() def test_disconnected_without_data(qtbot, connected_socket, ipc_server, caplog): """Disconnect without sending data. This means self._socket will be None on on_disconnected. """ connected_socket.disconnectFromServer() def test_partial_line(connected_socket): connected_socket.write(b'foo') OLD_VERSION = str(ipc.PROTOCOL_VERSION - 1).encode('utf-8') NEW_VERSION = str(ipc.PROTOCOL_VERSION + 1).encode('utf-8') @pytest.mark.parametrize('data, msg', [ (b'\x80\n', 'invalid utf-8'), (b'\n', 'invalid json'), (b'{"is this invalid json?": true\n', 'invalid json'), (b'{"valid json without args": true}\n', 'Missing args'), (b'{"args": []}\n', 'Missing target_arg'), (b'{"args": [], "target_arg": null, "protocol_version": ' + OLD_VERSION + b'}\n', 'incompatible version'), (b'{"args": [], "target_arg": null, "protocol_version": ' + NEW_VERSION + b'}\n', 'incompatible version'), (b'{"args": [], "target_arg": null, "protocol_version": "foo"}\n', 'invalid version'), (b'{"args": [], "target_arg": null}\n', 'invalid version'), ]) def test_invalid_data(qtbot, ipc_server, connected_socket, caplog, data, msg): signals = [ipc_server.got_invalid_data, connected_socket.disconnected] with caplog.at_level(logging.ERROR): with qtbot.assertNotEmitted(ipc_server.got_args): with qtbot.waitSignals(signals, order='strict'): connected_socket.write(data) invalid_msg = 'Ignoring invalid IPC data from socket ' assert caplog.messages[-1].startswith(invalid_msg) assert caplog.messages[-2].startswith(msg) def test_multiline(qtbot, ipc_server, connected_socket): spy = QSignalSpy(ipc_server.got_args) data = ('{{"args": ["one"], "target_arg": "tab",' ' "protocol_version": {version}}}\n' '{{"args": ["two"], "target_arg": null,' ' "protocol_version": {version}}}\n'.format( version=ipc.PROTOCOL_VERSION)) with qtbot.assertNotEmitted(ipc_server.got_invalid_data): with qtbot.waitSignals([ipc_server.got_args, ipc_server.got_args], order='strict'): connected_socket.write(data.encode('utf-8')) assert len(spy) == 2 assert spy[0] == [['one'], 'tab', ''] assert spy[1] == [['two'], '', ''] class TestSendToRunningInstance: def test_no_server(self, caplog): sent = ipc.send_to_running_instance('qute-test', [], None) assert not sent assert caplog.messages[-1] == "No existing instance present (error 2)" @pytest.mark.parametrize('has_cwd', [True, False]) @pytest.mark.linux(reason="Causes random trouble on Windows and macOS") def test_normal(self, qtbot, tmp_path, ipc_server, mocker, has_cwd): ipc_server.listen() with qtbot.assertNotEmitted(ipc_server.got_invalid_data): with qtbot.waitSignal(ipc_server.got_args, timeout=5000) as blocker: with qtbot.waitSignal(ipc_server.got_raw, timeout=5000) as raw_blocker: with testutils.change_cwd(tmp_path): if not has_cwd: m = mocker.patch('qutebrowser.misc.ipc.os') m.getcwd.side_effect = OSError sent = ipc.send_to_running_instance( 'qute-test', ['foo'], None) assert sent expected_cwd = str(tmp_path) if has_cwd else '' assert blocker.args == [['foo'], '', expected_cwd] raw_expected = {'args': ['foo'], 'target_arg': None, 'version': qutebrowser.__version__, 'protocol_version': ipc.PROTOCOL_VERSION} if has_cwd: raw_expected['cwd'] = str(tmp_path) assert len(raw_blocker.args) == 1 parsed = json.loads(raw_blocker.args[0].decode('utf-8')) assert parsed == raw_expected def test_socket_error(self): socket = FakeSocket(error=QLocalSocket.ConnectionError) with pytest.raises(ipc.Error, match=r"Error while writing to running " r"instance: Error string \(error 7\)"): ipc.send_to_running_instance('qute-test', [], None, socket=socket) def test_not_disconnected_immediately(self): socket = FakeSocket() ipc.send_to_running_instance('qute-test', [], None, socket=socket) def test_socket_error_no_server(self): socket = FakeSocket(error=QLocalSocket.ConnectionError, connect_successful=False) with pytest.raises(ipc.Error, match=r"Error while connecting to " r"running instance: Error string \(error 7\)"): ipc.send_to_running_instance('qute-test', [], None, socket=socket) @pytest.mark.not_mac(reason="https://github.com/qutebrowser/qutebrowser/" "issues/975") def test_timeout(qtbot, caplog, qlocalsocket, ipc_server): ipc_server._timer.setInterval(100) ipc_server.listen() with qtbot.waitSignal(ipc_server._server.newConnection): qlocalsocket.connectToServer('qute-test') with caplog.at_level(logging.ERROR): with qtbot.waitSignal(qlocalsocket.disconnected, timeout=5000): pass assert caplog.messages[-1].startswith("IPC connection timed out") def test_ipcserver_socket_none_readyread(ipc_server, caplog): assert ipc_server._socket is None assert ipc_server._old_socket is None with caplog.at_level(logging.WARNING): ipc_server.on_ready_read() msg = "In on_ready_read with None socket and old_socket!" assert msg in caplog.messages @pytest.mark.posix def test_ipcserver_socket_none_error(ipc_server, caplog): assert ipc_server._socket is None ipc_server.on_error(0) msg = "In on_error with None socket!" assert msg in caplog.messages class TestSendOrListen: @dataclasses.dataclass class Args: no_err_windows: bool basedir: str command: List[str] target: Optional[str] @pytest.fixture def args(self): return self.Args(no_err_windows=True, basedir='/basedir/for/testing', command=['test'], target=None) @pytest.fixture def qlocalserver_mock(self, mocker): m = mocker.patch('qutebrowser.misc.ipc.QLocalServer', autospec=True) m().errorString.return_value = "Error string" m().newConnection = stubs.FakeSignal() return m @pytest.fixture def qlocalsocket_mock(self, mocker): m = mocker.patch('qutebrowser.misc.ipc.QLocalSocket', autospec=True) m().errorString.return_value = "Error string" for name in ['UnknownSocketError', 'UnconnectedState', 'ConnectionRefusedError', 'ServerNotFoundError', 'PeerClosedError']: setattr(m, name, getattr(QLocalSocket, name)) return m @pytest.mark.linux(reason="Flaky on Windows and macOS") def test_normal_connection(self, caplog, qtbot, args): ret_server = ipc.send_or_listen(args) assert isinstance(ret_server, ipc.IPCServer) assert "Starting IPC server..." in caplog.messages assert ret_server is ipc.server with qtbot.waitSignal(ret_server.got_args): ret_client = ipc.send_or_listen(args) assert ret_client is None @pytest.mark.posix(reason="Unneeded on Windows") def test_correct_socket_name(self, args): server = ipc.send_or_listen(args) expected_dir = ipc._get_socketname(args.basedir) assert '/' in expected_dir assert server._socketname == expected_dir def test_address_in_use_ok(self, qlocalserver_mock, qlocalsocket_mock, stubs, caplog, args): """Test the following scenario. - First call to send_to_running_instance: -> could not connect (server not found) - Trying to set up a server and listen -> AddressInUseError - Second call to send_to_running_instance: -> success """ qlocalserver_mock().listen.return_value = False err = QAbstractSocket.AddressInUseError qlocalserver_mock().serverError.return_value = err qlocalsocket_mock().waitForConnected.side_effect = [False, True] qlocalsocket_mock().error.side_effect = [ QLocalSocket.ServerNotFoundError, QLocalSocket.UnknownSocketError, QLocalSocket.UnknownSocketError, # error() gets called twice ] ret = ipc.send_or_listen(args) assert ret is None assert "Got AddressInUseError, trying again." in caplog.messages @pytest.mark.parametrize('has_error, exc_name, exc_msg', [ (True, 'SocketError', 'Error while writing to running instance: Error string (error 0)'), (False, 'AddressInUseError', 'Error while listening to IPC server: Error string (error 8)'), ]) def test_address_in_use_error(self, qlocalserver_mock, qlocalsocket_mock, stubs, caplog, args, has_error, exc_name, exc_msg): """Test the following scenario. - First call to send_to_running_instance: -> could not connect (server not found) - Trying to set up a server and listen -> AddressInUseError - Second call to send_to_running_instance: -> not sent / error """ qlocalserver_mock().listen.return_value = False err = QAbstractSocket.AddressInUseError qlocalserver_mock().serverError.return_value = err # If the second connection succeeds, we will have an error later. # If it fails, that's the "not sent" case above. qlocalsocket_mock().waitForConnected.side_effect = [False, has_error] qlocalsocket_mock().error.side_effect = [ QLocalSocket.ServerNotFoundError, QLocalSocket.ServerNotFoundError, QLocalSocket.ConnectionRefusedError, QLocalSocket.ConnectionRefusedError, # error() gets called twice ] with caplog.at_level(logging.ERROR): with pytest.raises(ipc.Error): ipc.send_or_listen(args) error_msgs = [ 'Handling fatal misc.ipc.{} with --no-err-windows!'.format( exc_name), '', 'title: Error while connecting to running instance!', 'pre_text: ', 'post_text: ', 'exception text: {}'.format(exc_msg), ] assert caplog.messages == ['\n'.join(error_msgs)] @pytest.mark.posix(reason="Flaky on Windows") def test_error_while_listening(self, qlocalserver_mock, caplog, args): """Test an error with the first listen call.""" qlocalserver_mock().listen.return_value = False err = QAbstractSocket.SocketResourceError qlocalserver_mock().serverError.return_value = err with caplog.at_level(logging.ERROR): with pytest.raises(ipc.Error): ipc.send_or_listen(args) error_msgs = [ 'Handling fatal misc.ipc.ListenError with --no-err-windows!', '', 'title: Error while connecting to running instance!', 'pre_text: ', 'post_text: ', ('exception text: Error while listening to IPC server: Error ' 'string (error 4)'), ] assert caplog.messages[-1] == '\n'.join(error_msgs) @pytest.mark.windows @pytest.mark.mac def test_long_username(monkeypatch): """See https://github.com/qutebrowser/qutebrowser/issues/888.""" username = 'alexandercogneau' basedir = '/this_is_a_long_basedir' monkeypatch.setattr(getpass, 'getuser', lambda: username) name = ipc._get_socketname(basedir=basedir) server = ipc.IPCServer(name) expected_md5 = md5('{}-{}'.format(username, basedir)) assert expected_md5 in server._socketname try: server.listen() finally: server.shutdown() def test_connect_inexistent(qlocalsocket): """Make sure connecting to an inexistent server fails immediately. If this test fails, our connection logic checking for the old naming scheme would not work properly. """ qlocalsocket.connectToServer('qute-test-inexistent') assert qlocalsocket.error() == QLocalSocket.ServerNotFoundError @pytest.mark.posix def test_socket_options_address_in_use_problem(qlocalserver, short_tmpdir): """Qt seems to ignore AddressInUseError when using socketOptions. With this test we verify this bug still exists. If it fails, we can probably start using setSocketOptions again. """ servername = str(short_tmpdir / 'x') s1 = QLocalServer() ok = s1.listen(servername) assert ok s2 = QLocalServer() s2.setSocketOptions(QLocalServer.UserAccessOption) ok = s2.listen(servername) print(s2.errorString()) # We actually would expect ok == False here - but we want the test to fail # when the Qt bug is fixed. assert ok
fiete201/qutebrowser
tests/unit/misc/test_ipc.py
Python
gpl-3.0
28,342
package es.udc.tfg_es.clubtriatlon.utils.dao; /* BSD License */ import java.io.Serializable; import es.udc.tfg_es.clubtriatlon.utils.exceptions.InstanceNotFoundException; public interface GenericDao <E, PK extends Serializable>{ void save(E entity); E find(PK id) throws InstanceNotFoundException; boolean exists(PK id); void remove(PK id) throws InstanceNotFoundException; }
Al-Mikitinskis/ClubTriatlon
src/main/java/es/udc/tfg_es/clubtriatlon/utils/dao/GenericDao.java
Java
gpl-3.0
388
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleTutorial1 { class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Hello"); Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine("World"); Console.Read(); } } }
Easelm/ProgrammingNomEntertainment
Tutorials/C# Console Tutorials/ConsoleTutorial1/ConsoleTutorial1/Program.cs
C#
gpl-3.0
472
/***************************************************************************** The Dark Mod GPL Source Code This file is part of the The Dark Mod Source Code, originally based on the Doom 3 GPL Source Code as published in 2011. The Dark Mod Source Code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For details, see LICENSE.TXT. Project: The Dark Mod (http://www.thedarkmod.com/) $Revision: 5935 $ (Revision of last commit) $Date: 2014-02-15 19:19:00 +0000 (Sat, 15 Feb 2014) $ (Date of last commit) $Author: grayman $ (Author of last commit) ******************************************************************************/ #include "precompiled_game.h" #pragma hdrstop static bool versioned = RegisterVersionedFile("$Id: PathWaitForTriggerTask.cpp 5935 2014-02-15 19:19:00Z grayman $"); #include "../Memory.h" #include "PathWaitForTriggerTask.h" #include "../Library.h" namespace ai { PathWaitForTriggerTask::PathWaitForTriggerTask() : PathTask() {} PathWaitForTriggerTask::PathWaitForTriggerTask(idPathCorner* path) : PathTask(path) { _path = path; } // Get the name of this task const idStr& PathWaitForTriggerTask::GetName() const { static idStr _name(TASK_PATH_WAIT_FOR_TRIGGER); return _name; } void PathWaitForTriggerTask::Init(idAI* owner, Subsystem& subsystem) { PathTask::Init(owner, subsystem); owner->AI_ACTIVATED = false; } bool PathWaitForTriggerTask::Perform(Subsystem& subsystem) { DM_LOG(LC_AI, LT_INFO)LOGSTRING("Path WaitForTrigger Task performing.\r"); //idPathCorner* path = _path.GetEntity(); idAI* owner = _owner.GetEntity(); // This task may not be performed with empty entity pointers assert( owner != NULL ); if (owner->AI_ACTIVATED) { owner->AI_ACTIVATED = false; // Trigger path targets, now that the owner has been activated // grayman #3670 - this activates owner targets, not path targets owner->ActivateTargets(owner); // NextPath(); // Move is done, fall back to PatrolTask DM_LOG(LC_AI, LT_INFO)LOGSTRING("Waiting for trigger is done.\r"); return true; // finish this task } return false; } PathWaitForTriggerTaskPtr PathWaitForTriggerTask::CreateInstance() { return PathWaitForTriggerTaskPtr(new PathWaitForTriggerTask); } // Register this task with the TaskLibrary TaskLibrary::Registrar pathWaitForTriggerTaskRegistrar( TASK_PATH_WAIT_FOR_TRIGGER, // Task Name TaskLibrary::CreateInstanceFunc(&PathWaitForTriggerTask::CreateInstance) // Instance creation callback ); } // namespace ai
Extant-1/ThieVR
game/ai/Tasks/PathWaitForTriggerTask.cpp
C++
gpl-3.0
2,703
/* * Copyright (C) 2008-2009 Daniel Prevost <dprevost@photonsoftware.org> * * This file is part of Photon (photonsoftware.org). * * This file may be distributed and/or modified under the terms of the * GNU General Public License version 2 or version 3 as published by the * Free Software Foundation and appearing in the file COPYING.GPL2 and * COPYING.GPL3 included in the packaging of this software. * * Licensees holding a valid Photon Commercial license can use this file * in accordance with the terms of their license. * * This software 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. */ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace Photon { public partial class Lifo { // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- // Track whether Dispose has been called. private bool disposed = false; private IntPtr handle; private IntPtr sessionHandle; // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoClose(IntPtr objectHandle); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoDefinition( IntPtr objectHandle, ref ObjectDefinition definition); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoGetFirst( IntPtr objectHandle, byte[] buffer, UInt32 bufferLength, ref UInt32 returnedLength); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoGetNext( IntPtr objectHandle, byte[] buffer, UInt32 bufferLength, ref UInt32 returnedLength); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoOpen( IntPtr sessionHandle, string queueName, UInt32 nameLengthInBytes, ref IntPtr objectHandle); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoPop( IntPtr objectHandle, byte[] buffer, UInt32 bufferLength, ref UInt32 returnedLength); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoPush( IntPtr objectHandle, byte[] pItem, UInt32 length); [DllImport("photon.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int psoLifoStatus( IntPtr objectHandle, ref ObjStatus pStatus); // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- private void Dispose(bool disposing) { // Check to see if Dispose has already been called. if (!this.disposed) { psoLifoClose(handle); } disposed = true; } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- ~Lifo() { Dispose(false); } // --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- } }
dprevost/photon
src/CS/PhotonLib/PrivateLifo.cs
C#
gpl-3.0
3,740
package io.github.davidm98.crescent.detection.checks.inventory.inventorytweaks; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.inventory.InventoryClickEvent; import io.github.davidm98.crescent.detection.checks.Check; import io.github.davidm98.crescent.detection.checks.CheckVersion; public class InventoryTweaksA extends CheckVersion { public InventoryTweaksA(Check check) { super(check, "A", "Check if the player is performing impossible actions whilst moving."); } @Override public void call(Event event) { if (event instanceof InventoryClickEvent) { // The player has clicked. final Player player = profile.getPlayer(); if (player.isSprinting() || player.isSneaking() || player.isBlocking() || player.isSleeping() || player.isConversing()) { // The player has clicked in their inventory impossibly. callback(true); } } } }
awesome90/Crescent
src/io/github/davidm98/crescent/detection/checks/inventory/inventorytweaks/InventoryTweaksA.java
Java
gpl-3.0
942
//------------------------------------------------------------------------------ // // Module 08939 : Advanced Graphics // Bicubic B-Spline Assessment // Curve1D.cpp // //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // include files #include <iostream> #include <string> #include <fstream> #include <GL/glut.h> #pragma hdrstop #include "Curve1D.h" #include "Curve.h" #include "Constants.h" //------------------------------------------------------------------------------ // namespace using namespace std; using namespace ComputerGraphics; //------------------------------------------------------------------------------ // constructor Curve1D::Curve1D() : _position(0) { } //------------------------------------------------------------------------------ // render data points void Curve1D::render(bool markers, bool animation) { glDisable(GL_LIGHTING); glDisable(GL_DEPTH_TEST); const double BORDER = 0.2; int width = glutGet(GLUT_WINDOW_WIDTH); int height = glutGet(GLUT_WINDOW_HEIGHT); int point; glViewport(0, 0, width, height); glBegin(GL_LINES); glColor3d(0.5, 0.5, 0.5); glVertex2d(-1.0 + BORDER * 2.0, -1.0); glVertex2d(-1.0 + BORDER * 2.0, 1.0); glVertex2d(-1.0, -1.0 + BORDER * 2.0); glVertex2d(1.0, -1.0 + BORDER * 2.0); glEnd(); // main window glViewport(BORDER * width, BORDER * height, (1.0 - BORDER) * width, (1.0 - BORDER) * height); glColor3d(0.0, 0.0, 0.0); glRasterPos2d(-1.0, -1.0); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, '('); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'Y'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, ')'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, '('); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'T'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, ')'); glLineWidth(LINE_WIDTH); glDisable(GL_LINE_SMOOTH); glBegin(GL_LINE_STRIP); glColor3d(0.0, 0.0, 1.0); for (point = 0; point <= RESOLUTION; point++) { double tPoint = t(0) + (double)point / (double)RESOLUTION * (t(n() - 1) - t(0)); glVertex2d(tPoint, x().vertex(tPoint)); } glEnd(); if (markers) { glPointSize(POINT_SIZE); glEnable(GL_POINT_SMOOTH); glBegin(GL_POINTS); glColor3d(0.0, 0.0, 1.0); for (point = 0; point < n(); point++) { glVertex2d(x().t(point), x().f(point)); } glColor3d(1.0, 0.0, 0.0); glVertex2d(x().t(x().i()), x().f(x().i())); glEnd(); } if (animation) { glPointSize(POINT_SIZE); glEnable(GL_POINT_SMOOTH); glBegin(GL_POINTS); glColor3d(1.0, 0.0, 1.0); double tPoint = t(0) + (double)_position / (double)RESOLUTION * (t(n() - 1) - t(0)); glVertex2d(tPoint, x().vertex(tPoint)); _position = (_position + 1) % RESOLUTION; glEnd(); } else { _position = 0; } // y window glViewport(0, BORDER * height, BORDER * width, (1.0 - BORDER) * height); glColor3d(0.0, 0.0, 0.0); glRasterPos2d(-1.0, -1.0); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'Y'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, '('); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, 'T'); glutBitmapCharacter(GLUT_BITMAP_8_BY_13, ')'); x().render(markers); } //------------------------------------------------------------------------------ // get x const Curve &Curve1D::x() const { return _x; } //------------------------------------------------------------------------------ // read data points void Curve1D::read(const string &filename) { ifstream in(filename.c_str()); if (!in.good()) { throw string("Error : Invalid file name = " + filename); } clear(); int n; in >> n; for (int i = 0; i < n; i++) { double x; in >> x; add(x); } } //------------------------------------------------------------------------------ // write data points void Curve1D::write(const string &filename) const { ofstream out(filename.c_str()); if (!out.good()) { throw string("Error : Invalid file name = " + filename); } out << n() << endl; for (int i = 0; i < n(); i++) { out << _x.f(i) << endl; } } //------------------------------------------------------------------------------ // add data point void Curve1D::add(double x) { _x.add(x); } //------------------------------------------------------------------------------ // modify data point void Curve1D::modify(double x) { _x.modify(x); } //------------------------------------------------------------------------------ // insert data point void Curve1D::insert() { _x.insert(); } //------------------------------------------------------------------------------ // remove data point void Curve1D::remove() { _x.remove(); } //------------------------------------------------------------------------------ // clear arrays void Curve1D::clear() { _x.clear(); } //------------------------------------------------------------------------------ // next data point void Curve1D::next() { _x.next(); } //------------------------------------------------------------------------------ // previous data point void Curve1D::previous() { _x.previous(); } //------------------------------------------------------------------------------ // first data point void Curve1D::first() { _x.first(); } //------------------------------------------------------------------------------ // last data point void Curve1D::last() { _x.last(); } //------------------------------------------------------------------------------ // get index of data point int Curve1D::i() const { return x().i(); } //------------------------------------------------------------------------------ // get number of data points int Curve1D::n() const { return x().n(); } //------------------------------------------------------------------------------ // get data point parameter double Curve1D::t(int m) const { return x().t(m); } //------------------------------------------------------------------------------
sihart25/BicubicBSpline
Source/Curve1D.cpp
C++
gpl-3.0
6,272
var btimer; var isclosed=true; var current_show_id=1; var current_site_id; var wurl; var comment_recapcha_id; function hideVBrowser() { isclosed=true; $('#websiteviewer_background').fadeOut(); } function submitTest(view_token) { $('#websiteviewer_browserheader').html('<center>...در حال بررسی</center>'); $.ajax({ url:wurl+'/websites/api/submitpoint?website_id='+current_site_id+'&view_token='+view_token, success:function(dr) { if(dr.ok===true) { $('#websiteviewer_browserheader').html(`<center style="color:#00aa00;">`+dr.text+`<center>`); } else { $('#websiteviewer_browserheader').html(`<center style="color:#ff0000;">`+dr.text+`<center>`); } $("#pointviewer").html('امتیاز شما : '+ dr.point ); } }); } function showTester() { $('#websiteviewer_browserheader').html('<center>لطفا کمی صبر کنید</center>'); $.ajax({ url:wurl+'/websites/api/requestpoint?website_id='+current_site_id, success:function(dr) { if(dr.able==false) { alert('متاسفانه امکان ثبت امتیاز وجود ندارد!'); return; } $('#websiteviewer_browserheader').html(`<center> <img id=\"validation_image\" src=\"`+wurl+`/websites/api/current_image.png?s=`+dr.rand_session+`\"> <button onclick=\"submitTest(\'`+dr.v0.value+`\')\">`+dr.v0.name+`</button> <button onclick=\"submitTest(\'`+dr.v1.value+`\')\">`+dr.v1.name+`</button> <button onclick=\"submitTest(\'`+dr.v2.value+`\')\">`+dr.v2.name+`</button> گزینه ی صحیح را انتخاب کنید </center>`); } }); } function browserTimer(_reset=false) { if(_reset===true) browserTimer.csi=current_show_id; if(isclosed===true|| browserTimer.csi!== current_show_id) return; btimer-=1; $('#websiteviewer_browserheader').html(' <center> &nbsp;لطفا&nbsp; '+parseInt(btimer)+' &nbsp;ثانیه صبر کنید&nbsp; </center> '); if(btimer>0) setTimeout(browserTimer,1000); else showTester(); } function showwebsite(weburl,websiteid,watchonly=false) { $('#websiteviewer_background').css('visibility','visible'); $('#websiteviewer_browserheader').html('<center>...در حال بارگزاری</center>'); $('#websiteviewer_browser').html(''); $("#websiteviewer_browser").css('display','block'); $("#websiteviewer_comments").css('display','none'); $('#websiteviewer_background').fadeIn(); $('#website_detials').html(' '); current_show_id++; isclosed=false; $.ajax({ url:weburl+'/websites/api/requestvisit?website_id='+websiteid, success:function(dr) { $('#websiteviewer_browser').html('<iframe sandbox=\'\' style=\'width: 100%;height: 100%;\' src=\''+dr.weburl+'\'></iframe>'); if(watchonly) { $('#websiteviewer_browserheader').html('<center>'+dr.title+' <a href="'+weburl+'/websites/editwebsite?website_id='+websiteid+'"><button>اصلاح مشخصات</button></a> '+'</center>'); } else if(dr.selfwebsite===true) { $('#websiteviewer_browserheader').html('<center> این وبسایت توسط خود شما ثبت شده است </center>'); } else if(dr.thepoint<=0) { $('#websiteviewer_browserheader').html('<center> امتیازی جهت کسب کردن وجود ندارد</center>'); } else if(dr.able===false) { $('#websiteviewer_browserheader').html('<center>شما اخیرا از این سایت بازدید کرده اید . لطفا بعدا تلاش کنید</center>'); } else if(dr.nopoint===true) { $('#websiteviewer_browserheader').html('<center>متاسفانه مقدار امتیاز صاحب سایت برای دریافت امتیاز شما کافی نیست</center>'); } else { $('#websiteviewer_browserheader').html('<center> &nbsp;لطفا&nbsp; '+parseInt(dr.timer)+'&nbsp;ثانیه صبر کنید &nbsp;</center>'); setTimeout(function(){browserTimer(true);},1000); } btimer=dr.timer; current_site_id=websiteid; wurl=weburl; if(dr.liked) { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_true.png\')'); $("#websiteviewer_likeButton").attr('title','حزف پسندیدن'); } else { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_false.png\')'); $("#websiteviewer_likeButton").attr('title','پسندیدن'); } $("#website_detials").html('<span dir="rtl"> <a target="_blank" href="'+dr.weburl+'">'+dr.weburl+'</a> | &nbsp;'+dr.title+' &nbsp; <a target="_blank" href="'+weburl+'/user/'+dr.the_user_name+'">'+dr.user_name+'</a></span>'); } }); } function toggleLike() { $.ajax({ url:wurl+'/websites/api/togglelike?websiteid='+current_site_id, success:function(dr) { if(dr.website_id===current_site_id) { if(dr.liked) { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_true.png\')'); $("#websiteviewer_likeButton").attr('title','حزف پسندیدن'); } else { $("#websiteviewer_likeButton").css('background-image',' url(\'/images/like_false.png\')'); $("#websiteviewer_likeButton").attr('title','پسندیدن'); } } } }); } function tabShowComments() { $("#websiteviewer_browser").css('display','none'); $("#websiteviewer_comments").css('display','block'); $("#websiteviewer_comments").html('<center>...در حال بارگزاری</center>'); loadComments(); } function tabShowWebsite() { $("#websiteviewer_browser").css('display','block'); $("#websiteviewer_comments").css('display','none'); } function loadComments() { $.ajax({ url:wurl+'/websites/api/comments/'+current_site_id, success:function(dr){ $('#websiteviewer_comments').html(''); $('#websiteviewer_comments').append(`<div id="your_comment_div"><form onsubmit="postComment()" action="`+wurl+`" method="post"><input type="text" placeholder="نظر شما" id="your_comment_content"></textarea><div id="__google_recaptcha"></div><input onclick="postComment(event)" type="submit" value="ارسال نظر"></form></div>`); comment_recapcha_id=grecaptcha.render('__google_recaptcha',{'sitekey':'6LfaYSgUAAAAAFxMhXqtX6NdYW0jxFv1wnIFS1VS'}); $('#websiteviewer_comments').append(`</div>`); for(var i=0;i<dr.comments.length;i++) { var str = '<span dir="rtl">'+dr.users[i].name + ' میگه : ' + dr.comments[i].content+'</span>'; if(dr.ownwebsite || dr.comments[i].user_id == dr.current_user_id ) { str+='<a href="javascript:void(0)"><button onclick="deleteComment('+dr.comments[i].id+')"> حزف </button></a>'; } $('#websiteviewer_comments').append('<div class="websiteviewer_thecommentblock" >'+str+'</div><br>' ); } } }); } function postComment(e) { e.preventDefault(); console.log(grecaptcha); if(grecaptcha==null) { alert('انجام نشد'); return false; } var rr = grecaptcha.getResponse(comment_recapcha_id); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: "POST", url:wurl+'/website/api/comments/add', data:{'g-recaptcha-response':rr,"website_id":current_site_id,"content":$("#your_comment_content").val()}, success:function(dr){ if(dr.done===true) { alert('نظر شما ثبت شد'); grecaptcha.reset(); loadComments(); } else { alert('متاسفانه مشکلی وجود دارد.نظر شما ثبت نشد. مطمئن شوید محتوای نظر شما خالی نیست و گزینه ی من یک ربات نیستم را تایید کرده اید'); grecaptcha.reset(); } }, error: function(data) { alert('متاسفانه مشکلی در ارتباط با سرور وجود دارد. نظر شما ثبت نشده است.'); } }); alert('... لطفا کمی صبر کنید'); return false; } function deleteComment(comment_id) { var _con = confirm('آیا برای حزف این نظر مطمئن هستید؟'); if(_con==false) return; $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ url:wurl+'/website/api/comments/delete', type:"post", data:{"cid":comment_id}, success:function(dr){ if(dr.done==true) alert('حزف شد'); else alert('مشکلی در حزف وجود دارد'); loadComments(); } }); }
amir9480/Traffic-booster
public_html/js/websites.js
JavaScript
gpl-3.0
10,083
<?php namespace Modules\Acl\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class PerimeterUpdateRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $id = $this->perimeter; return $rules = [ 'com' => 'required|max:5|unique:perimeters,com,'.$id, 'nom_com' => 'required|unique:perimeters,nom_com,'.$id, 'epci' => 'required|max:9,epci,'.$id, 'dep' => 'required|max:2,dep,'.$id ]; } }
diouck/laravel
Modules/Acl/Http/Requests/PerimeterUpdateRequest.php
PHP
gpl-3.0
763
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7-b41 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.09.01 at 06:27:35 PM MSK // package com.apple.itunes.importer.tv; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attGroup ref="{http://apple.com/itunes/importer}ReviewComponentItem"/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "review_component_item") public class ReviewComponentItem { @XmlAttribute(name = "locale") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String locale; @XmlAttribute(name = "type", required = true) @XmlSchemaType(name = "anySimpleType") protected String type; /** * Gets the value of the locale property. * * @return * possible object is * {@link String } * */ public String getLocale() { return locale; } /** * Sets the value of the locale property. * * @param value * allowed object is * {@link String } * */ public void setLocale(String value) { this.locale = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() { return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } }
DSRCorporation/imf-conversion
itunes-metadata-tv/src/main/java/com/apple/itunes/importer/tv/ReviewComponentItem.java
Java
gpl-3.0
2,525
<?php /* * Copyright (C) 2014 Aaron Sharp * Released under GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 */ namespace Controllers; class IndexController extends Controller { protected $subController = NULL; public function setSubController($subController) { $this->subController = $subController; } public function getSubController() { return $this->subController; } public function parseSession() { return; } public function parseInput() { if (isset($_REQUEST['step'])) { $this->setSubController($this->workflow->getController($_REQUEST['step'])); } else { $this->setSubController(new LoginController($this->getWorkflow())); } } public function retrievePastResults() { return ""; } public function renderInstructions() { return ""; } public function renderForm() { return ""; } public function renderHelp() { return ""; } public function getSubTitle() { return ""; } public function renderSpecificStyle() { return ""; } public function renderSpecificScript() { return ""; } public function getScriptLibraries() { return array(); } public function renderOutput() { if ($this->subController) { $this->subController->run(); } else { error_log("Attempted to render output before setting subcontroller"); } } }
chnops/QIIMEIntegration
includes/Controllers/IndexController.php
PHP
gpl-3.0
1,275
// // UnrealPaletteDataFormat.cs // // Author: // Michael Becker <alcexhim@gmail.com> // // Copyright (c) 2021 Mike Becker's Software // // 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/>. using System; using MBS.Framework.Drawing; using UniversalEditor.IO; using UniversalEditor.ObjectModels.Multimedia.Palette; namespace UniversalEditor.DataFormats.Multimedia.Palette.Unreal { public class UnrealPaletteDataFormat : DataFormat { public UnrealPaletteDataFormat() { } protected override void LoadInternal(ref ObjectModel objectModel) { PaletteObjectModel palette = (objectModel as PaletteObjectModel); if (palette == null) throw new ObjectModelNotSupportedException(); Reader reader = Accessor.Reader; ushort signature = reader.ReadUInt16(); while (!reader.EndOfStream) { byte r = reader.ReadByte(); byte g = reader.ReadByte(); byte b = reader.ReadByte(); byte a = reader.ReadByte(); palette.Entries.Add(Color.FromRGBAByte(r, g, b, a)); } } protected override void SaveInternal(ObjectModel objectModel) { PaletteObjectModel palette = (objectModel as PaletteObjectModel); if (palette == null) throw new ObjectModelNotSupportedException(); Writer writer = Accessor.Writer; writer.WriteUInt16(0x4001); for (int i = 0; i < Math.Min(palette.Entries.Count, 256); i++) { writer.WriteByte(palette.Entries[i].Color.GetRedByte()); writer.WriteByte(palette.Entries[i].Color.GetGreenByte()); writer.WriteByte(palette.Entries[i].Color.GetBlueByte()); writer.WriteByte(palette.Entries[i].Color.GetAlphaByte()); } int remaining = (256 - palette.Entries.Count); if (remaining > 0) { for (int i = 0; i < remaining; i++) { writer.WriteByte(0); writer.WriteByte(0); writer.WriteByte(0); writer.WriteByte(0); } } } } }
alcexhim/UniversalEditor
Plugins/UniversalEditor.Plugins.UnrealEngine/DataFormats/Multimedia/Palette/Unreal/UnrealPaletteDataFormat.cs
C#
gpl-3.0
2,463
require 'geomerative' # After an original sketch by fjenett # Declare the objects we are going to use, so that they are accesible # from setup and from draw attr_reader :shp, :x, :y, :xd, :yd def settings size(600, 400) smooth(4) end def setup sketch_title 'Blobby Trail' RG.init(self) @xd = rand(-5..5) @yd = rand(-5..5) @x = width / 2 @y = height / 2 @shp = RShape.new end def draw background(120) move elli = RG.getEllipse(x, y, rand(2..20)) @shp = RG.union(shp, elli) RG.shape(shp) end def move @x += xd @xd *= -1 unless (0..width).cover?(x) @y += yd @yd *= -1 unless (0..height).cover?(y) end
ruby-processing/JRubyArt-examples
external_library/gem/geomerative/blobby_trail.rb
Ruby
gpl-3.0
638
#!/usr/bin/env python if __name__ == '__main__': from anoisetools.scripts.dispatch import main main()
fhcrc/ampliconnoise
anoise.py
Python
gpl-3.0
111
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * Scoreable.java * Copyright (C) 2001 Remco Bouckaert * */ package weka.classifiers.bayes.net.search.local; /** * Interface for allowing to score a classifier * * @author Remco Bouckaert (rrb@xm.co.nz) * @version $Revision: 1.1 $ */ public interface Scoreable { /** * score types */ int BAYES = 0; int BDeu = 1; int MDL = 2; int ENTROPY = 3; int AIC = 4; /** * Returns log-score */ double logScore(int nType); } // interface Scoreable
paolopavan/cfr
src/weka/classifiers/BAYES/NET/SEARCH/LOCAL/Scoreable.java
Java
gpl-3.0
1,195
package donnees; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class ProducteurDefaut implements IProducteur { private ArrayList<String> donnees; private IMagasin Magasin; public ProducteurDefaut() { super(); donnees = new ArrayList<String>(); Magasin = null; try { BufferedReader br = new BufferedReader(new FileReader("donnees/donnees.txt")); String ligne; while((ligne = br.readLine())!=null) { donnees.add(ligne); } br.close(); } catch (Exception e) { e.printStackTrace(); } } public ArrayList<IProduit> getProduits(IMagasin oMagasin){ Class<?> produit = null; IProduit concret = null; ArrayList<IProduit> oProduit = new ArrayList<IProduit>(); for (String s : donnees) { if(s.contains("class=donnees.Produit")) {//c'est un produit, on va maintenant verifier que c'est un produit du bon magasin. if(s.split(";")[5].split("=")[1].equals(oMagasin.getNomMag())) {//bon mag try { concret = newProduit(s); concret.setNom(s.split(";")[1].split("=")[1]); concret.setType(s.split(";")[2].split("=")[1]); concret.setPrix(Float.parseFloat(s.split(";")[3].split("=")[1])); concret.setQuantites(Integer.parseInt(s.split(";")[4].split("=")[1])); oProduit.add(concret); } catch (Exception e) { e.printStackTrace(); } } } } return oProduit; } private IProduit newProduit(String s) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // Class<?> produit; IProduit concret; // produit = Class.forName(s.split(";")[0].split("=")[1]); // // concret = (IProduit) produit.newInstance(); concret = new ProduitConcret(); return concret; } public IMagasin getMagasin() { if(Magasin == null) { ArrayList<String> magPos = new ArrayList<String>(); System.out.println("liste des magasins: "); for (String s : donnees) { if(s.contains("donnees.Magasin")) { magPos.add(s.split(";")[0].split("=")[1]); System.out.println(s.split(";")[1].split("=")[1]); if(s.split(";")[2].split("=")[1].equals("now")) { System.out.println("load obligatoire, debut..."); try { Magasin = newMagasin(s); Magasin.setNomMag(s.split(";")[1].split("=")[1]); } catch (Exception e) { e.printStackTrace(); } } } } ArrayList<IProduit> stock = getProduits(Magasin); Magasin.setProduits(stock); } return Magasin; } private IMagasin newMagasin(String s) throws ClassNotFoundException, InstantiationException, IllegalAccessException { // Class<?> magasin; // magasin = Class.forName(s.split(";")[0].split("=")[1]); IMagasin magasin = new MagasinConcret(); // Magasin = (IMagasin) magasin.newInstance(); return magasin; } }
Liciax/Projet-M1ALMA-Logiciels-Extensibles
Projet_exten/src/donnees/ProducteurDefaut.java
Java
gpl-3.0
3,118
/* * Synload Development Services * September 16, 2013 * Nathaniel Davidson <nathaniel.davidson@gmail.com> * http://synload.com */ package com.synload.groupvideo; import it.sauronsoftware.base64.Base64; import java.net.InetSocketAddress; import java.util.Hashtable; import org.java_websocket.WebSocket; import org.java_websocket.drafts.Draft; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; import com.synload.groupvideo.request.RequestGenerator; import com.synload.groupvideo.request.RequestHandler; import com.synload.groupvideo.users.User; public class Server extends WebSocketServer { public Server( InetSocketAddress address, Draft d ) { super( address ); } public Group newGroup(String name){ Group newGroup = new Group(this); newGroup.groupTitle = name; activeGroups.put(name, newGroup); return newGroup; } public Group getGroup(String name){ if(!activeGroups.containsKey(name)){ return this.newGroup(name); }else{ return activeGroups.get(name); } } @Override public void onError(WebSocket conn, Exception ex) { ex.printStackTrace(); } private RequestHandler request = new RequestHandler(); public Hashtable<String, Group> activeGroups = new Hashtable<String, Group>(); public Hashtable<WebSocket, String> clientGroup = new Hashtable<WebSocket, String>(); public Hashtable<WebSocket, String> clientName = new Hashtable<WebSocket, String>(); public RequestGenerator jsonbuilder = new RequestGenerator(); @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { User user = new User(conn, this); //user.sendMessage("Welcome to GroupVideo!","System"); user.sendResponseData(this.jsonbuilder.user_nick()); System.out.println(conn+" connected"); } @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { if(clientGroup.containsKey(conn)){ Group group = getGroup(clientGroup.get(conn)); group.removeClient(conn); group.sendData(this.jsonbuilder.left(clientName.get(conn))); if(group.empty()){ group.thread.interrupt(); System.out.println(clientGroup.get(conn)+" destroyed!"); activeGroups.remove(clientGroup.get(conn)); clientGroup.remove(conn); }else{ if(group.getOwner().equals(conn)){ group.setOwner(group.clients.get(0)); System.out.println(clientName.get(group.clients.get(0))+" now owner of "+clientGroup.get(conn)); } clientGroup.remove(conn); String users = ""; for(WebSocket cl: group.clients){ if(users.equals("")){ users = clientName.get(cl); }else{ users += ","+clientName.get(cl); } } group.sendData("act=plylst&usrs="+Base64.encode(users)); } } if(clientName.containsKey(conn)){ System.out.println(clientName.get(conn)+" disconnected!"); clientName.remove(conn); } } @Override public void onMessage(WebSocket conn, String message) { request.translateRequest(conn,message, this); } }
firestar/GroupVideo
com/synload/groupvideo/Server.java
Java
gpl-3.0
3,491
FactoryBot.define do factory :status_change do status_change_to { 0 } status_change_from { 1 } entity { nil } end end
AgileVentures/MetPlus_PETS
spec/factories/status_changes.rb
Ruby
gpl-3.0
134
<?php namespace PhpOffice\Common\Adapter\Zip; use ZipArchive; class ZipArchiveAdapter implements ZipInterface { /** * @var ZipArchive */ protected $oZipArchive; /** * @var string */ protected $filename; public function open($filename) { $this->filename = $filename; $this->oZipArchive = new ZipArchive(); if ($this->oZipArchive->open($this->filename, ZipArchive::OVERWRITE) === true) { return $this; } if ($this->oZipArchive->open($this->filename, ZipArchive::CREATE) === true) { return $this; } throw new \Exception("Could not open $this->filename for writing."); } public function close() { if ($this->oZipArchive->close() === false) { throw new \Exception("Could not close zip file $this->filename."); } return $this; } public function addFromString($localname, $contents) { if ($this->oZipArchive->addFromString($localname, $contents) === false) { throw new \Exception('Error zipping files : ' . $localname); } return $this; } }
collectiveaccess/pawtucket2
vendor/phpoffice/common/src/Common/Adapter/Zip/ZipArchiveAdapter.php
PHP
gpl-3.0
1,167
/* * Copyright (c) 2017 "Neo4j, Inc." <http://neo4j.com> * * This file is part of Neo4j Graph Algorithms <http://github.com/neo4j-contrib/neo4j-graph-algorithms>. * * Neo4j Graph Algorithms is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.graphalgo.impl.degree; import org.neo4j.graphalgo.api.Graph; import org.neo4j.graphalgo.core.utils.ParallelUtil; import org.neo4j.graphalgo.core.utils.Pools; import org.neo4j.graphalgo.impl.Algorithm; import org.neo4j.graphalgo.impl.pagerank.DegreeCentralityAlgorithm; import org.neo4j.graphalgo.impl.results.CentralityResult; import org.neo4j.graphalgo.impl.results.DoubleArrayResult; import org.neo4j.graphdb.Direction; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import java.util.stream.Stream; public class WeightedDegreeCentrality extends Algorithm<WeightedDegreeCentrality> implements DegreeCentralityAlgorithm { private final int nodeCount; private Direction direction; private Graph graph; private final ExecutorService executor; private final int concurrency; private volatile AtomicInteger nodeQueue = new AtomicInteger(); private double[] degrees; private double[][] weights; public WeightedDegreeCentrality( Graph graph, ExecutorService executor, int concurrency, Direction direction ) { if (concurrency <= 0) { concurrency = Pools.DEFAULT_CONCURRENCY; } this.graph = graph; this.executor = executor; this.concurrency = concurrency; nodeCount = Math.toIntExact(graph.nodeCount()); this.direction = direction; degrees = new double[nodeCount]; weights = new double[nodeCount][]; } public WeightedDegreeCentrality compute(boolean cacheWeights) { nodeQueue.set(0); int batchSize = ParallelUtil.adjustBatchSize(nodeCount, concurrency); int taskCount = ParallelUtil.threadSize(batchSize, nodeCount); final ArrayList<Runnable> tasks = new ArrayList<>(taskCount); for (int i = 0; i < taskCount; i++) { if(cacheWeights) { tasks.add(new CacheDegreeTask()); } else { tasks.add(new DegreeTask()); } } ParallelUtil.runWithConcurrency(concurrency, tasks, executor); return this; } @Override public WeightedDegreeCentrality me() { return this; } @Override public WeightedDegreeCentrality release() { graph = null; return null; } @Override public CentralityResult result() { return new DoubleArrayResult(degrees); } @Override public void compute() { compute(false); } @Override public Algorithm<?> algorithm() { return this; } private class DegreeTask implements Runnable { @Override public void run() { for (; ; ) { final int nodeId = nodeQueue.getAndIncrement(); if (nodeId >= nodeCount || !running()) { return; } double[] weightedDegree = new double[1]; graph.forEachRelationship(nodeId, direction, (sourceNodeId, targetNodeId, relationId, weight) -> { if(weight > 0) { weightedDegree[0] += weight; } return true; }); degrees[nodeId] = weightedDegree[0]; } } } private class CacheDegreeTask implements Runnable { @Override public void run() { for (; ; ) { final int nodeId = nodeQueue.getAndIncrement(); if (nodeId >= nodeCount || !running()) { return; } weights[nodeId] = new double[graph.degree(nodeId, direction)]; int[] index = {0}; double[] weightedDegree = new double[1]; graph.forEachRelationship(nodeId, direction, (sourceNodeId, targetNodeId, relationId, weight) -> { if(weight > 0) { weightedDegree[0] += weight; } weights[nodeId][index[0]] = weight; index[0]++; return true; }); degrees[nodeId] = weightedDegree[0]; } } } public double[] degrees() { return degrees; } public double[][] weights() { return weights; } public Stream<DegreeCentrality.Result> resultStream() { return IntStream.range(0, nodeCount) .mapToObj(nodeId -> new DegreeCentrality.Result(graph.toOriginalNodeId(nodeId), degrees[nodeId])); } }
neo4j-contrib/neo4j-graph-algorithms
algo/src/main/java/org/neo4j/graphalgo/impl/degree/WeightedDegreeCentrality.java
Java
gpl-3.0
5,540
package sporemodder.extras.spuieditor.components; import sporemodder.extras.spuieditor.SPUIViewer; import sporemodder.files.formats.spui.InvalidBlockException; import sporemodder.files.formats.spui.SPUIBlock; import sporemodder.files.formats.spui.SPUIBuilder; public class cSPUIBehaviorWinBoolStateEvent extends cSPUIBehaviorWinEventBase { public static final int TYPE = 0x025611ED; public cSPUIBehaviorWinBoolStateEvent(SPUIBlock block) throws InvalidBlockException { super(block); addUnassignedInt(block, 0x03339952, 0); } public cSPUIBehaviorWinBoolStateEvent(SPUIViewer viewer) { super(viewer); unassignedProperties.put(0x03339952, (int) 0); } @Override public SPUIBlock saveComponent(SPUIBuilder builder) { SPUIBlock block = (SPUIBlock) super.saveComponent(builder); saveInt(builder, block, 0x03339952); return block; } private cSPUIBehaviorWinBoolStateEvent() { super(); } @Override public cSPUIBehaviorWinBoolStateEvent copyComponent(boolean propagateIndependent) { cSPUIBehaviorWinBoolStateEvent other = new cSPUIBehaviorWinBoolStateEvent(); copyComponent(other, propagateIndependent); return other; } }
Emd4600/SporeModder
src/sporemodder/extras/spuieditor/components/cSPUIBehaviorWinBoolStateEvent.java
Java
gpl-3.0
1,174
#!/usr/bin/env python """ Seshat Web App/API framework built on top of gevent modifying decorators for HTTP method functions For more information, see: https://github.com/JoshAshby/ http://xkcd.com/353/ Josh Ashby 2014 http://joshashby.com joshuaashby@joshashby.com """ import json import seshat_addons.utils.patch_json from ..view.template import template import seshat.actions as actions def HTML(f): def wrapper(*args, **kwargs): self = args[0] data = {"title": self._title if self._title else "Untitled"} self.view = template(self._tmpl, self.request, data) res = f(*args, **kwargs) if isinstance(res, actions.BaseAction): return res if type(res) is dict: self.view.data = res res = self.view if isinstance(res, template): string = res.render() else: string = res del res self.head.add_header("Content-Type", "text/html") return string return wrapper def JSON(f): def wrapper(*args, **kwargs): self = args[0] res = f(*args, **kwargs) if isinstance(res, actions.BaseAction): return res if type(res) is not list: res = [res] self.head.add_header("Content-Type", "application/json") return json.dumps(res) return wrapper def Guess(f): def wrapper(*args, **kwargs): self = args[0] res = f(*args, **kwargs) if isinstance(res, actions.BaseAction): return res if self.request.accepts("html") or self.request.accepts("*/*"): self.head.add_header("Content-Type", "text/html") data = {"title": self._title if self._title else "Untitled"} data.update(res) view = template(self._tmpl, self.request, data).render() del res return view if self.request.accepts("json") or self.request.accepts("*/*"): self.head.add_header("Content-Type", "application/json") t_res = type(res) if t_res is dict: final_res = json.dumps([res]) elif t_res is list: final_res = json.dumps(res) del res return final_res else: return unicode(res) return wrapper
JoshAshby/seshat_addons
seshat_addons/seshat/func_mods.py
Python
gpl-3.0
2,354
import Component from './mock/component.spec'; QUnit.module( 'File: core/common/assets/js/api/extras/hash-commands.js', ( hooks ) => { hooks.before( () => { $e.components.register( new Component() ); } ); QUnit.test( 'get(): Ensure valid return format', ( assert ) => { // Act. const actual = $e.extras.hashCommands.get( '#whatever&e:run:test-command&e:route:test-route' ); // Assert. assert.deepEqual( actual, [ { command: 'test-command', method: 'e:run', }, { command: 'test-route', method: 'e:route', } ] ); } ); QUnit.test( 'get(): Ensure valid return format - Only one hash command the start with (#)', ( assert ) => { // Act. const actual = $e.extras.hashCommands.get( '#e:run:my-component/command' ); // Assert. assert.deepEqual( actual, [ { command: 'my-component/command', method: 'e:run', } ] ); } ); QUnit.test( 'run(): Ensure run performed', ( assert ) => { // Arrange. const dispatcherOrig = $e.extras.hashCommands.dispatchersList[ 'e:run' ], dispatcherRunnerOrig = dispatcherOrig.runner; let ensureCallbackPerformed = ''; dispatcherOrig.runner = ( command ) => { ensureCallbackPerformed = command; }; // Act. $e.extras.hashCommands.run( [ { command: 'test-hash-commands/safe-command', method: 'e:run', } ] ); // Assert. assert.equal( ensureCallbackPerformed, 'test-hash-commands/safe-command' ); // Cleanup. dispatcherOrig.runner = dispatcherRunnerOrig; } ); QUnit.test( 'run(): Ensure insecure command fails', ( assert ) => { assert.throws( () => { $e.extras.hashCommands.run( [ { command: 'test-hash-commands/insecure-command', method: 'e:run', } ] ); }, new Error( 'Attempting to run unsafe or non exist command: `test-hash-commands/insecure-command`.' ) ); } ); QUnit.test( 'run(): Ensure exception when no dispatcher found', ( assert ) => { assert.throws( () => { $e.extras.hashCommands.run( [ { command: 'test-hash-commands/insecure-command', method: 'e:non-exist-method', } ] ); }, new Error( 'No dispatcher found for the command: `test-hash-commands/insecure-command`.' ) ); } ); } );
ramiy/elementor
tests/qunit/tests/core/common/assets/js/api/extras/hash-commands.spec.js
JavaScript
gpl-3.0
2,172
/******************************************************************************/ /* */ /* X r d X r o o t d L o a d L i b . c c */ /* */ /* (c) 2004 by the Board of Trustees of the Leland Stanford, Jr., University */ /* Produced by Andrew Hanushevsky for Stanford University under contract */ /* DE-AC02-76-SFO0515 with the Department of Energy */ /* */ /* This file is part of the XRootD software suite. */ /* */ /* XRootD is free software: you can redistribute it and/or modify it under */ /* the terms of the GNU Lesser General Public License as published by the */ /* Free Software Foundation, either version 3 of the License, or (at your */ /* option) any later version. */ /* */ /* XRootD 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 XRootD in a file called COPYING.LESSER (LGPL license) and file */ /* COPYING (GPL license). If not, see <http://www.gnu.org/licenses/>. */ /* */ /* The copyright holder's institutional names and contributor's names may not */ /* be used to endorse or promote products derived from this software without */ /* specific prior written permission of the institution or contributor. */ /******************************************************************************/ #include "XrdVersion.hh" #include "XrdOuc/XrdOucEnv.hh" #include "XrdSec/XrdSecInterface.hh" #include "XrdSfs/XrdSfsInterface.hh" #include "XrdSys/XrdSysError.hh" #include "XrdSys/XrdSysPlugin.hh" /******************************************************************************/ /* V e r s i o n I n f o r m a t i o n L i n k */ /******************************************************************************/ XrdVERSIONINFOREF(XrdgetProtocol); /******************************************************************************/ /* x r o o t d _ l o a d F i l e s y s t e m */ /******************************************************************************/ XrdSfsFileSystem *XrdXrootdloadFileSystem(XrdSysError *eDest, char *fslib, const char *cfn) { XrdSysPlugin ofsLib(eDest,fslib,"fslib",&XrdVERSIONINFOVAR(XrdgetProtocol)); XrdSfsFileSystem *(*ep)(XrdSfsFileSystem *, XrdSysLogger *, const char *); XrdSfsFileSystem *FS; // Record the library path in the environment // XrdOucEnv::Export("XRDOFSLIB", fslib); // Get the file system object creator // if (!(ep = (XrdSfsFileSystem *(*)(XrdSfsFileSystem *,XrdSysLogger *,const char *)) ofsLib.getPlugin("XrdSfsGetFileSystem"))) return 0; // Get the file system object // if (!(FS = (*ep)(0, eDest->logger(), cfn))) {eDest->Emsg("Config", "Unable to create file system object via",fslib); return 0; } // All done // ofsLib.Persist(); return FS; } /******************************************************************************/ /* x r o o t d _ l o a d S e c u r i t y */ /******************************************************************************/ XrdSecService *XrdXrootdloadSecurity(XrdSysError *eDest, char *seclib, char *cfn, void **secGetProt) { XrdSysPlugin secLib(eDest, seclib, "seclib", &XrdVERSIONINFOVAR(XrdgetProtocol), 1); XrdSecService *(*ep)(XrdSysLogger *, const char *cfn); XrdSecService *CIA; // Get the server object creator // if (!(ep = (XrdSecService *(*)(XrdSysLogger *, const char *cfn)) secLib.getPlugin("XrdSecgetService"))) return 0; // Get the server object // if (!(CIA = (*ep)(eDest->logger(), cfn))) {eDest->Emsg("Config", "Unable to create security service object via",seclib); return 0; } // Get the client object creator (in case we are acting as a client). We return // the function pointer as a (void *) to the caller so that it can be passed // onward via an environment object. // if (!(*secGetProt = (void *)secLib.getPlugin("XrdSecGetProtocol"))) return 0; // All done // secLib.Persist(); return CIA; }
bbockelm/xrootd_old_git
src/XrdXrootd/XrdXrootdLoadLib.cc
C++
gpl-3.0
5,139
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using System; using org.bn.attributes; using org.bn.attributes.constraints; using org.bn.coders; using org.bn.types; using org.bn; namespace MMS_ASN1_Model { [ASN1PreparedElement] [ASN1Sequence ( Name = "Unit_Control_instance", IsSet = false )] public class Unit_Control_instance : IASN1PreparedElement { private Identifier name_ ; [ASN1Element ( Name = "name", IsOptional = false , HasTag = true, Tag = 0 , HasDefaultValue = false ) ] public Identifier Name { get { return name_; } set { name_ = value; } } private DefinitionChoiceType definition_ ; [ASN1PreparedElement] [ASN1Choice ( Name = "definition" )] public class DefinitionChoiceType : IASN1PreparedElement { private ObjectIdentifier reference_ ; private bool reference_selected = false ; [ASN1ObjectIdentifier( Name = "" )] [ASN1Element ( Name = "reference", IsOptional = false , HasTag = true, Tag = 1 , HasDefaultValue = false ) ] public ObjectIdentifier Reference { get { return reference_; } set { selectReference(value); } } private DetailsSequenceType details_ ; private bool details_selected = false ; [ASN1PreparedElement] [ASN1Sequence ( Name = "details", IsSet = false )] public class DetailsSequenceType : IASN1PreparedElement { private Access_Control_List_instance accessControl_ ; [ASN1Element ( Name = "accessControl", IsOptional = false , HasTag = true, Tag = 3 , HasDefaultValue = false ) ] public Access_Control_List_instance AccessControl { get { return accessControl_; } set { accessControl_ = value; } } private System.Collections.Generic.ICollection<Domain_instance> domains_ ; [ASN1SequenceOf( Name = "domains", IsSetOf = false )] [ASN1Element ( Name = "domains", IsOptional = false , HasTag = true, Tag = 4 , HasDefaultValue = false ) ] public System.Collections.Generic.ICollection<Domain_instance> Domains { get { return domains_; } set { domains_ = value; } } private System.Collections.Generic.ICollection<Program_Invocation_instance> programInvocations_ ; [ASN1SequenceOf( Name = "programInvocations", IsSetOf = false )] [ASN1Element ( Name = "programInvocations", IsOptional = false , HasTag = true, Tag = 5 , HasDefaultValue = false ) ] public System.Collections.Generic.ICollection<Program_Invocation_instance> ProgramInvocations { get { return programInvocations_; } set { programInvocations_ = value; } } public void initWithDefaults() { } private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DetailsSequenceType)); public IASN1PreparedElementData PreparedData { get { return preparedData; } } } [ASN1Element ( Name = "details", IsOptional = false , HasTag = true, Tag = 2 , HasDefaultValue = false ) ] public DetailsSequenceType Details { get { return details_; } set { selectDetails(value); } } public bool isReferenceSelected () { return this.reference_selected ; } public void selectReference (ObjectIdentifier val) { this.reference_ = val; this.reference_selected = true; this.details_selected = false; } public bool isDetailsSelected () { return this.details_selected ; } public void selectDetails (DetailsSequenceType val) { this.details_ = val; this.details_selected = true; this.reference_selected = false; } public void initWithDefaults() { } private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DefinitionChoiceType)); public IASN1PreparedElementData PreparedData { get { return preparedData; } } } [ASN1Element ( Name = "definition", IsOptional = false , HasTag = false , HasDefaultValue = false ) ] public DefinitionChoiceType Definition { get { return definition_; } set { definition_ = value; } } public void initWithDefaults() { } private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Unit_Control_instance)); public IASN1PreparedElementData PreparedData { get { return preparedData; } } } }
rogerz/IEDExplorer
MMS_ASN1_Model/Unit_Control_instance.cs
C#
gpl-3.0
5,743
// VNR - Plugin for NewRelic which monitors `varnishstat` // Copyright (C) 2015 Luke Mallon // // 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 process import ( "github.com/nalum/vnr/structs" "log" ) func VClient(Channel chan interface{}) { var holder interface{} var data structs.VClient for { holder = <-Channel data = holder.(structs.VClient) log.Println(data) } }
Nalum/vnr
process/vclient.go
GO
gpl-3.0
990
<?php // Heading $_['heading_title'] = 'View Transaction'; // Text $_['text_pp_express'] = 'PayPal Express Checkout'; $_['text_product_lines'] = 'Product lines'; $_['text_ebay_txn_id'] = 'eBay transaction ID'; $_['text_name'] = 'Navn'; $_['text_qty'] = 'Lager'; $_['text_price'] = 'Pris'; $_['text_number'] = 'Number'; $_['text_coupon_id'] = 'Coupon ID'; $_['text_coupon_amount'] = 'Coupon amount'; $_['text_coupon_currency'] = 'Coupon currency'; $_['text_loyalty_disc_amt'] = 'Loyalty card disc amount'; $_['text_loyalty_currency'] = 'Loyalty card currency'; $_['text_options_name'] = 'Options name'; $_['text_tax_amt'] = 'Tax amount'; $_['text_currency_code'] = 'Currency code'; $_['text_amount'] = 'Beløp'; $_['text_gift_msg'] = 'Gift message'; $_['text_gift_receipt'] = 'Gift receipt'; $_['text_gift_wrap_name'] = 'Gift wrap name'; $_['text_gift_wrap_amt'] = 'Gift wrap amount'; $_['text_buyer_email_market'] = 'Buyer marketing email'; $_['text_survey_question'] = 'Survey question'; $_['text_survey_chosen'] = 'Survey choice selected'; $_['text_receiver_business'] = 'Receiver business'; $_['text_receiver_email'] = 'Receiver email'; $_['text_receiver_id'] = 'Receiver ID'; $_['text_buyer_email'] = 'Buyer email'; $_['text_payer_id'] = 'Payer ID'; $_['text_payer_status'] = 'Payer status'; $_['text_country_code'] = 'Country code'; $_['text_payer_business'] = 'Payer business'; $_['text_payer_salute'] = 'Payer salutation'; $_['text_payer_firstname'] = 'Payer first name'; $_['text_payer_middlename'] = 'Payer middle name'; $_['text_payer_lastname'] = 'Payer last name'; $_['text_payer_suffix'] = 'Payer suffix'; $_['text_address_owner'] = 'Address owner'; $_['text_address_status'] = 'Address status'; $_['text_ship_sec_name'] = 'Ship to secondary name'; $_['text_ship_name'] = 'Ship to name'; $_['text_ship_street1'] = 'Ship to address 1'; $_['text_ship_street2'] = 'Ship to address 2'; $_['text_ship_city'] = 'Ship to city'; $_['text_ship_state'] = 'Ship to state'; $_['text_ship_zip'] = 'Ship to ZIP'; $_['text_ship_country'] = 'Ship to country code'; $_['text_ship_phone'] = 'Ship to phone number'; $_['text_ship_sec_add1'] = 'Ship to secondary address 1'; $_['text_ship_sec_add2'] = 'Ship to secondary address 2'; $_['text_ship_sec_city'] = 'Ship to secondary city'; $_['text_ship_sec_state'] = 'Ship to secondary state'; $_['text_ship_sec_zip'] = 'Ship to secondary ZIP'; $_['text_ship_sec_country'] = 'Ship to secondary country code'; $_['text_ship_sec_phone'] = 'Ship to secondary phone'; $_['text_trans_id'] = 'Transaction ID'; $_['text_receipt_id'] = 'Receipt ID'; $_['text_parent_trans_id'] = 'Parent transaction ID'; $_['text_trans_type'] = 'Transaction type'; $_['text_payment_type'] = 'Payment type'; $_['text_order_time'] = 'Order time'; $_['text_fee_amount'] = 'Fee amount'; $_['text_settle_amount'] = 'Settle amount'; $_['text_tax_amount'] = 'Tax amount'; $_['text_exchange'] = 'Exchange rate'; $_['text_payment_status'] = 'Payment status'; $_['text_pending_reason'] = 'Pending reason'; $_['text_reason_code'] = 'Reason code'; $_['text_protect_elig'] = 'Protection eligibility'; $_['text_protect_elig_type'] = 'Protection eligibility type'; $_['text_store_id'] = 'Store ID'; $_['text_terminal_id'] = 'Terminal ID'; $_['text_invoice_number'] = 'Invoice number'; $_['text_custom'] = 'Custom'; $_['text_note'] = 'Note'; $_['text_sales_tax'] = 'Sales tax'; $_['text_buyer_id'] = 'Buyer ID'; $_['text_close_date'] = 'Closing date'; $_['text_multi_item'] = 'Multi item'; $_['text_sub_amt'] = 'Subscription amount'; $_['text_sub_period'] = 'Subscription period';
opencartnorge/norwegian-opencart-translation
upload/admin/language/norwegian/payment/pp_express_view.php
PHP
gpl-3.0
3,808
/*********************************************************** * Programming Assignment 6 * Arrays program * Programmers: Mark Eatough and Stephen Williams * Course: CS 1600 * Created March 5, 2013 *This program takes values from a current array and a resistance, *array, and uses them to calculate a volts array. The Program *then prints the three arrays with appropriate headings. ***********************************************************/ #include<iostream> using namespace std; //create function prototype void calc_volts(double [], double [], double [], int); //main function int main() { const int capacity = 10; int k; double current[capacity] = {10.62, 14.89, 13.21, 16.55, 18.62, 9.47, 6.58, 18.32, 12.15, 3.98}; double resistance[capacity] = {4, 8.5, 6, 7.35, 9, 15.3, 3, 5.4, 2.9, 4.8}; double volts[capacity]; calc_volts(current, resistance, volts, capacity); cout << "Current \tResistence \tVolts " << endl; for(k = 0; k < capacity; k++) { cout << current[k] << "\t\t" << resistance[k] << "\t\t" << volts[k] << endl; } } //implementation of function to calculate volts void calc_volts(double res [], double cur [], double vol [], int cap) { int i; for(i = 0; i < cap; i++) { vol[i] = (cur[i] * res[i]); } }
meatough/Marks-Programs
CS 1600/Homework assignments/programming projects/Programming project 6/Programming Project 6.cpp
C++
gpl-3.0
1,313
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004 - 2009 SugarCRM Inc. * * 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 with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU General Public License version 3. * * In accordance with Section 7(b) of the GNU General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ /********************************************************************************* * Description: base form for account * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. * All Rights Reserved. * Contributor(s): ______________________________________.. ********************************************************************************/ class AccountFormBase{ function checkForDuplicates($prefix){ require_once('include/formbase.php'); $focus = new Account(); $query = ''; $baseQuery = 'select id, name, website, billing_address_city from accounts where deleted!=1 and '; if(!empty($_POST[$prefix.'name'])){ $query = $baseQuery ." name like '".$_POST[$prefix.'name']."%'"; } if(!empty($_POST[$prefix.'billing_address_city']) || !empty($_POST[$prefix.'shipping_address_city'])){ $temp_query = ''; if(!empty($_POST[$prefix.'billing_address_city'])){ if(empty($temp_query)){ $temp_query = " billing_address_city like '".$_POST[$prefix.'billing_address_city']."%'"; }else { $temp_query .= "or billing_address_city like '".$_POST[$prefix.'billing_address_city']."%'"; } } if(!empty($_POST[$prefix.'shipping_address_city'])){ if(empty($temp_query)){ $temp_query = " shipping_address_city like '".$_POST[$prefix.'shipping_address_city']."%'"; }else { $temp_query .= "or shipping_address_city like '".$_POST[$prefix.'shipping_address_city']."%'"; } } if(empty($query)){ $query .= $baseQuery; }else{ $query .= ' AND '; } $query .= ' ('. $temp_query . ' ) '; } if(!empty($query)){ $rows = array(); global $db; $result = $db->query($query); $i=-1; while(($row=$db->fetchByAssoc($result)) != null) { $i++; $rows[$i] = $row; } if ($i==-1) return null; return $rows; } return null; } function buildTableForm($rows, $mod='Accounts'){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } global $action; if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); }else global $mod_strings; global $app_strings; $cols = sizeof($rows[0]) * 2 + 1; if ($action != 'ShowDuplicates') { $form = "<form action='index.php' method='post' id='dupAccounts' name='dupAccounts'><input type='hidden' name='selectedAccount' value=''>"; $form .= '<table width="100%"><tr><td>'.$mod_strings['MSG_DUPLICATE']. '</td></tr><tr><td height="20"></td></tr></table>'; unset($_POST['selectedAccount']); } else { $form = '<table width="100%"><tr><td>'.$mod_strings['MSG_SHOW_DUPLICATES']. '</td></tr><tr><td height="20"></td></tr></table>'; } $form .= get_form_header($mod_strings['LBL_DUPLICATE'], "", ''); $form .= "<table width='100%' cellpadding='0' cellspacing='0'> <tr> "; if ($action != 'ShowDuplicates') { $form .= "<th> &nbsp;</th>"; } require_once('include/formbase.php'); if(isset($_POST['return_action']) && $_POST['return_action'] == 'SubPanelViewer') { $_POST['return_action'] = 'DetailView'; } if(isset($_POST['return_action']) && $_POST['return_action'] == 'DetailView' && empty($_REQUEST['return_id'])) { unset($_POST['return_action']); } $form .= getPostToForm('/emailAddress(PrimaryFlag|OptOutFlag|InvalidFlag)?[0-9]*?$/', true); if(isset($rows[0])){ foreach ($rows[0] as $key=>$value){ if($key != 'id'){ $form .= "<th>". $mod_strings[$mod_strings['db_'.$key]]. "</th>"; }} $form .= "</tr>"; } $rowColor = 'oddListRowS1'; foreach($rows as $row){ $form .= "<tr class='$rowColor'>"; if ($action != 'ShowDuplicates') { $form .= "<td width='1%' nowrap><a href='#' onclick='document.dupAccounts.selectedAccount.value=\"${row['id']}\"; document.dupAccounts.submit(); '>[${app_strings['LBL_SELECT_BUTTON_LABEL']}]</a>&nbsp;&nbsp;</td>\n"; } foreach ($row as $key=>$value){ if($key != 'id'){ if(isset($_POST['popup']) && $_POST['popup']==true){ $form .= "<td scope='row'><a href='#' onclick=\"window.opener.location='index.php?module=Accounts&action=DetailView&record=${row['id']}'\">$value</a></td>\n"; } else $form .= "<td><a target='_blank' href='index.php?module=Accounts&action=DetailView&record=${row['id']}'>$value</a></td>\n"; }} if($rowColor == 'evenListRowS1'){ $rowColor = 'oddListRowS1'; }else{ $rowColor = 'evenListRowS1'; } $form .= "</tr>"; } $form .= "<tr><td colspan='$cols' class='blackline'></td></tr>"; // handle buttons if ($action == 'ShowDuplicates') { $return_action = 'ListView'; // cn: bug 6658 - hardcoded return action break popup -> create -> duplicate -> cancel $return_action = (isset($_REQUEST['return_action']) && !empty($_REQUEST['return_action'])) ? $_REQUEST['return_action'] : $return_action; $form .= "</table><br><input type='hidden' name='selectedAccount' id='selectedAccount' value=''><input title='${app_strings['LBL_SAVE_BUTTON_TITLE']}' accessKey='${app_strings['LBL_SAVE_BUTTON_KEY']}' class='button' onclick=\"this.form.action.value='Save';\" type='submit' name='button' value=' ${app_strings['LBL_SAVE_BUTTON_LABEL']} '>"; if (!empty($_REQUEST['return_module']) && !empty($_REQUEST['return_action']) && !empty($_REQUEST['return_id'])) $form .= "<input title='${app_strings['LBL_CANCEL_BUTTON_TITLE']}' accessKey='${app_strings['LBL_CANCEL_BUTTON_KEY']}' class='button' onclick=\"location.href='index.php?module=".$_REQUEST['return_module']."&action=".$_REQUEST['return_action']."&record=".$_REQUEST['return_id']."'\" type='button' name='button' value=' ${app_strings['LBL_CANCEL_BUTTON_LABEL']} '></form>"; else if (!empty($_POST['return_module']) && !empty($_POST['return_action'])) $form .= "<input title='${app_strings['LBL_CANCEL_BUTTON_TITLE']}' accessKey='${app_strings['LBL_CANCEL_BUTTON_KEY']}' class='button' onclick=\"location.href='index.php?module=".$_POST['return_module']."&action=". $_POST['return_action']."'\" type='button' name='button' value=' ${app_strings['LBL_CANCEL_BUTTON_LABEL']} '></form>"; else $form .= "<input title='${app_strings['LBL_CANCEL_BUTTON_TITLE']}' accessKey='${app_strings['LBL_CANCEL_BUTTON_KEY']}' class='button' onclick=\"location.href='index.php?module=Accounts&action=ListView'\" type='button' name='button' value=' ${app_strings['LBL_CANCEL_BUTTON_LABEL']} '></form>"; } else { $form .= "</table><BR><input type='submit' class='button' name='ContinueAccount' value='${mod_strings['LNK_NEW_ACCOUNT']}'></form>\n"; } return $form; } function getForm($prefix, $mod='', $form=''){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); }else global $mod_strings; global $app_strings; $lbl_save_button_title = $app_strings['LBL_SAVE_BUTTON_TITLE']; $lbl_save_button_key = $app_strings['LBL_SAVE_BUTTON_KEY']; $lbl_save_button_label = $app_strings['LBL_SAVE_BUTTON_LABEL']; $the_form = get_left_form_header($mod_strings['LBL_NEW_FORM_TITLE']); $the_form .= <<<EOQ <form name="${prefix}AccountSave" onSubmit="return check_form('${prefix}AccountSave');" method="POST" action="index.php"> <input type="hidden" name="${prefix}module" value="Accounts"> <input type="hidden" name="${prefix}action" value="Save"> EOQ; $the_form .= $this->getFormBody($prefix, $mod, $prefix."AccountSave"); $the_form .= <<<EOQ <p><input title="$lbl_save_button_title" accessKey="$lbl_save_button_key" class="button" type="submit" name="button" value=" $lbl_save_button_label " ></p> </form> EOQ; $the_form .= get_left_form_footer(); $the_form .= get_validate_record_js(); return $the_form; } function getFormBody($prefix,$mod='', $formname=''){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } global $mod_strings; $temp_strings = $mod_strings; if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); } global $app_strings; global $current_user; $lbl_required_symbol = $app_strings['LBL_REQUIRED_SYMBOL']; $lbl_account_name = $mod_strings['LBL_ACCOUNT_NAME']; $lbl_phone = $mod_strings['LBL_PHONE']; $lbl_website = $mod_strings['LBL_WEBSITE']; $lbl_save_button_title = $app_strings['LBL_SAVE_BUTTON_TITLE']; $lbl_save_button_key = $app_strings['LBL_SAVE_BUTTON_KEY']; $lbl_save_button_label = $app_strings['LBL_SAVE_BUTTON_LABEL']; $user_id = $current_user->id; $form = <<<EOQ <p><input type="hidden" name="record" value=""> <input type="hidden" name="email1" value=""> <input type="hidden" name="email2" value=""> <input type="hidden" name="assigned_user_id" value='${user_id}'> <input type="hidden" name="action" value="Save"> EOQ; $form .= "$lbl_account_name&nbsp;<span class='required'>$lbl_required_symbol</span><br><input name='name' type='text' value=''><br>"; $form .= "$lbl_phone<br><input name='phone_office' type='text' value=''><br>"; $form .= "$lbl_website<br><input name='website' type='text' value='http://'><br>"; $form .='</p>'; $javascript = new javascript(); $javascript->setFormName($formname); $javascript->setSugarBean(new Account()); $javascript->addRequiredFields($prefix); $form .=$javascript->getScript(); $mod_strings = $temp_strings; return $form; } function getWideFormBody($prefix, $mod='',$formname='', $contact=''){ if(!ACLController::checkAccess('Accounts', 'edit', true)){ return ''; } if(empty($contact)){ $contact = new Contact(); } global $mod_strings; $temp_strings = $mod_strings; if(!empty($mod)){ global $current_language; $mod_strings = return_module_language($current_language, $mod); } global $app_strings; global $current_user; $account = new Account(); $lbl_required_symbol = $app_strings['LBL_REQUIRED_SYMBOL']; $lbl_account_name = $mod_strings['LBL_ACCOUNT_NAME']; $lbl_phone = $mod_strings['LBL_PHONE']; $lbl_website = $mod_strings['LBL_WEBSITE']; if (isset($contact->assigned_user_id)) { $user_id=$contact->assigned_user_id; } else { $user_id = $current_user->id; } //Retrieve Email address and set email1, email2 $sugarEmailAddress = new SugarEmailAddress(); $sugarEmailAddress->handleLegacyRetrieve($contact); if(!isset($contact->email1)){ $contact->email1 = ''; } if(!isset($contact->email2)){ $contact->email2 = ''; } if(!isset($contact->email_opt_out)){ $contact->email_opt_out = ''; } $form=""; $default_desc=""; if (!empty($contact->description)) { $default_desc=$contact->description; } $form .= <<<EOQ <input type="hidden" name="${prefix}record" value=""> <input type="hidden" name="${prefix}phone_fax" value="{$contact->phone_fax}"> <input type="hidden" name="${prefix}phone_other" value="{$contact->phone_other}"> <input type="hidden" name="${prefix}email1" value="{$contact->email1}"> <input type="hidden" name="${prefix}email2" value="{$contact->email2}"> <input type='hidden' name='${prefix}billing_address_street' value='{$contact->primary_address_street}'><input type='hidden' name='${prefix}billing_address_city' value='{$contact->primary_address_city}'><input type='hidden' name='${prefix}billing_address_state' value='{$contact->primary_address_state}'><input type='hidden' name='${prefix}billing_address_postalcode' value='{$contact->primary_address_postalcode}'><input type='hidden' name='${prefix}billing_address_country' value='{$contact->primary_address_country}'> <input type='hidden' name='${prefix}shipping_address_street' value='{$contact->primary_address_street}'><input type='hidden' name='${prefix}shipping_address_city' value='{$contact->primary_address_city}'><input type='hidden' name='${prefix}shipping_address_state' value='{$contact->primary_address_state}'><input type='hidden' name='${prefix}shipping_address_postalcode' value='{$contact->primary_address_postalcode}'><input type='hidden' name='${prefix}shipping_address_country' value='{$contact->primary_address_country}'> <input type="hidden" name="${prefix}assigned_user_id" value='${user_id}'> <input type='hidden' name='${prefix}do_not_call' value='{$contact->do_not_call}'> <input type='hidden' name='${prefix}email_opt_out' value='{$contact->email_opt_out}'> <table width='100%' border="0" cellpadding="0" cellspacing="0"> <tr> <td width="20%" nowrap scope="row">$lbl_account_name&nbsp;<span class="required">$lbl_required_symbol</span></td> <TD width="80%" nowrap scope="row">{$mod_strings['LBL_DESCRIPTION']}</TD> </tr> <tr> <td nowrap ><input name='{$prefix}name' type="text" value="$contact->account_name"></td> <TD rowspan="5" ><textarea name='{$prefix}description' rows='6' cols='50' >$default_desc</textarea></TD> </tr> <tr> <td nowrap scope="row">$lbl_phone</td> </tr> <tr> <td nowrap ><input name='{$prefix}phone_office' type="text" value="$contact->phone_work"></td> </tr> <tr> <td nowrap scope="row">$lbl_website</td> </tr> <tr> <td nowrap ><input name='{$prefix}website' type="text" value="http://"></td> </tr> EOQ; //carry forward custom lead fields common to accounts during Lead Conversion $tempAccount = new Account(); if (method_exists($contact, 'convertCustomFieldsForm')) $contact->convertCustomFieldsForm($form, $tempAccount, $prefix); unset($tempAccount); $form .= <<<EOQ </TABLE> EOQ; $javascript = new javascript(); $javascript->setFormName($formname); $javascript->setSugarBean(new Account()); $javascript->addRequiredFields($prefix); $form .=$javascript->getScript(); $mod_strings = $temp_strings; return $form; } function handleSave($prefix,$redirect=true, $useRequired=false){ require_once('include/formbase.php'); $focus = new Account(); if($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))){ return null; } $focus = populateFromPost($prefix, $focus); if (isset($GLOBALS['check_notify'])) { $check_notify = $GLOBALS['check_notify']; } else { $check_notify = FALSE; } if (empty($_POST['record']) && empty($_POST['dup_checked'])) { $duplicateAccounts = $this->checkForDuplicates($prefix); if(isset($duplicateAccounts)){ $location='module=Accounts&action=ShowDuplicates'; $get = ''; //add all of the post fields to redirect get string foreach ($focus->column_fields as $field) { if (!empty($focus->$field)) { $get .= "&Accounts$field=".urlencode($focus->$field); } } foreach ($focus->additional_column_fields as $field) { if (!empty($focus->$field)) { $get .= "&Accounts$field=".urlencode($focus->$field); } } if($focus->hasCustomFields()) { foreach($focus->field_defs as $name=>$field) { if (!empty($field['source']) && $field['source'] == 'custom_fields') { $get .= "&Accounts$name=".urlencode($focus->$name); } } } $emailAddress = new SugarEmailAddress(); $get .= $emailAddress->getFormBaseURL($focus); //create list of suspected duplicate account id's in redirect get string $i=0; foreach ($duplicateAccounts as $account) { $get .= "&duplicate[$i]=".$account['id']; $i++; } //add return_module, return_action, and return_id to redirect get string $get .= '&return_module='; if(!empty($_POST['return_module'])) $get .= $_POST['return_module']; else $get .= 'Accounts'; $get .= '&return_action='; if(!empty($_POST['return_action'])) $get .= $_POST['return_action']; //else $get .= 'DetailView'; if(!empty($_POST['return_id'])) $get .= '&return_id='.$_POST['return_id']; if(!empty($_POST['popup'])) $get .= '&popup='.$_POST['popup']; if(!empty($_POST['create'])) $get .= '&create='.$_POST['create']; //echo $get; //die; //now redirect the post to modules/Accounts/ShowDuplicates.php if (!empty($_POST['is_ajax_call']) && $_POST['is_ajax_call'] == '1') { $json = getJSONobj(); echo $json->encode(array('status' => 'dupe', 'get' => $get)); } else { if(!empty($_POST['to_pdf'])) $location .= '&to_pdf='.$_POST['to_pdf']; $_SESSION['SHOW_DUPLICATES'] = $get; header("Location: index.php?$location"); } return null; } } if(!$focus->ACLAccess('Save')){ ACLController::displayNoAccess(true); sugar_cleanup(true); } $focus->save($check_notify); $return_id = $focus->id; $GLOBALS['log']->debug("Saved record with id of ".$return_id); if (!empty($_POST['is_ajax_call']) && $_POST['is_ajax_call'] == '1') { $json = getJSONobj(); echo $json->encode(array('status' => 'success', 'get' => '')); return null; } if(isset($_POST['popup']) && $_POST['popup'] == 'true') { $get = '&module='; if(!empty($_POST['return_module'])) $get .= $_POST['return_module']; else $get .= 'Accounts'; $get .= '&action='; if(!empty($_POST['return_action'])) $get .= $_POST['return_action']; else $get .= 'Popup'; if(!empty($_POST['return_id'])) $get .= '&return_id='.$_POST['return_id']; if(!empty($_POST['popup'])) $get .= '&popup='.$_POST['popup']; if(!empty($_POST['create'])) $get .= '&create='.$_POST['create']; if(!empty($_POST['to_pdf'])) $get .= '&to_pdf='.$_POST['to_pdf']; $get .= '&name=' . $focus->name; $get .= '&query=true'; header("Location: index.php?$get"); return; } if($redirect){ handleRedirect($return_id,'Accounts'); }else{ return $focus; } } } ?>
mitani/dashlet-subpanels
modules/Accounts/AccountFormBase.php
PHP
gpl-3.0
19,722
public class Solution { public int longestSubstring(String s, int k) { if(s.length() < k) return 0; int[] count = new int[26]; Arrays.fill(count, 0); for(int i = 0;i < s.length();++i) { count[(int)(s.charAt(i) - 'a')]++; } char c = '-'; for(int i = 0;i < 26;++i) { if(count[i] < k && count[i] != 0) { c = (char) (i + 'a'); break; } } if(c == '-') return s.length(); int index = -1; for(int i = 0;i < s.length();++i) { if(s.charAt(i) == c) { index = i; break; } } String left = s.substring(0, index); String right = s.substring(index + 1, s.length()); int l = 0; int r = 0; if(index >= k) { l = longestSubstring(s.substring(0, index), k); } if(s.length() - index - 1 >= k) { r = longestSubstring(s.substring(index + 1, s.length()), k); } if(l > r) return l; return r; } }
acgtun/leetcode
algorithms/java/Longest Substring with At Least K Repeating Characters.java
Java
gpl-3.0
1,120
module OLDRETS VERSION = "2.0.6" end
mccollek/ruby-rets
lib/old_rets/version.rb
Ruby
gpl-3.0
39
# -*- coding: utf-8 -*- # XMPPVOX: XMPP client for DOSVOX. # Copyright (C) 2012 Rodolfo Henrique Carvalho # # This file is part of XMPPVOX. # # XMPPVOX 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/>. u""" XMPPVOX - módulo servidor Este módulo implementa um servidor compatível com o protocolo usado pelo Papovox e Sítiovox. """ import socket import struct import textwrap import time import sys from cStringIO import StringIO from xmppvox import commands from xmppvox.strings import safe_unicode, get_string as S import logging log = logging.getLogger(__name__) # Constantes ------------------------------------------------------------------# # Todas as strings passadas para o Papovox devem ser codificadas usando a # codificação padrão do DOSVOX, ISO-8859-1, também conhecida como Latin-1. SYSTEM_ENCODING = 'ISO-8859-1' #------------------------------------------------------------------------------# class PapovoxLikeServer(object): u"""Um servidor compatível com o Papovox.""" DEFAULT_HOST = '127.0.0.1' # Escuta apenas conexões locais PORTA_PAPOVOX = 1963 #PORTA_URGENTE = 1964 #PORTA_NOMES = 1956 DADOTECLADO = 1 # texto da mensagem (sem tab, nem lf nem cr ao final) TAMANHO_DO_BUFFER = 4096 # Ver C:\winvox\Fontes\tradutor\DVINET.PAS TAMANHO_MAXIMO_MSG = 255 def __init__(self, host=None, port=None): u"""Cria servidor compatível com o Papovox.""" # Socket do servidor self.server_socket = None # Host/interface de escuta self.host = host or self.DEFAULT_HOST # Porta do servidor self.port = port or self.PORTA_PAPOVOX # Socket do cliente self.socket = None # Endereço do cliente self.addr = None # Apelido self.nickname = u"" def connect(self): u"""Conecta ao Papovox via socket. Retorna booleano indicando se a conexão foi bem-sucedida. Bloqueia aguardando Papovox conectar. Define atributos: self.server_socket self.socket self.addr self.nickname """ try: self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Reutilizar porta já aberta #self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.server_socket.bind((self.host, self.port)) self.server_socket.listen(1) log.debug(u"XMPPVOX servindo em %s:%s", self.host, self.port) # Conecta ao Papovox ----------------------------------------------# try: self._accept() except socket.error: return False #------------------------------------------------------------------# return True except socket.error, e: log.error(safe_unicode(e.message) or u" ".join(map(safe_unicode, e.args))) sys.exit(1) def _accept(self): ur"""Aceita uma conexão via socket com o Papovox. Ver 'C:\winvox\Fontes\PAPOVOX\PPLIGA.PAS' e 'C:\winvox\Fontes\SITIOVOX\SVPROC.PAS'. """ log.info(u"Aguardando Papovox conectar...") self.socket, self.addr = self.server_socket.accept() self.sendline(u"+OK - %s:%s conectado" % self.addr) self.nickname = self.recvline(self.TAMANHO_DO_BUFFER) self.sendline(u"+OK") # Espera Papovox estar pronto para receber mensagens. # # A espera é necessária pois se enviar mensagens logo em seguida o Papovox # as ignora, provavelmente relacionado a alguma temporização ou espera na # leitura de algum buffer ou estado da variável global 'conversando'. # O SítioVox aguarda 100ms (arquivo SVPROC.PAS). time.sleep(0.1) log.info(u"Conectado ao Papovox.") log.debug(u"Apelido: %s", self.nickname) def disconnect(self): u"""Desliga a conexão com o Papovox.""" log.debug(u"Encerrando conexão com o Papovox...") try: self.socket.shutdown(socket.SHUT_RDWR) self.socket.close() except socket.error, e: log.debug("Client socket: %s", safe_unicode(e)) try: self.server_socket.shutdown(socket.SHUT_RDWR) self.server_socket.close() except socket.error, e: log.debug("Server socket: %s", safe_unicode(e)) # Funções de integração com o cliente XMPP --------------------------------# def process(self, xmpp): u"""Processa mensagens do Papovox para a rede XMPP. Mensagens podem conter comandos para o XMPPVOX. Nota: esta função só termina caso ocorra algum erro ou a conexão com o Papovox seja perdida. """ try: while True: data = self.recvmessage() # Tenta executar algum comando contido na mensagem. if commands.process_command(xmpp, data, self): # Caso algum comando seja executado, sai do loop e passa # para a próxima mensagem. continue else: # Caso contrário, envia a mensagem para a rede XMPP. self.send_xmpp_message(xmpp, data) except socket.error, e: log.debug(safe_unicode(e)) finally: log.info(u"Conexão com o Papovox encerrada.") def show_online_contacts(self, xmpp): u"""Envia para o Papovox informação sobre contatos disponíveis.""" online_contacts_count = len(commands.enumerate_online_roster(xmpp)) if online_contacts_count == 0: online_contacts_count = "nenhum" contacts = u"contato disponível" elif online_contacts_count == 1: contacts = u"contato disponível" else: contacts = u"contatos disponíveis" self.sendmessage(S.ONLINE_CONTACTS_INFO.format(amount=online_contacts_count, contacts=contacts)) def send_xmpp_message(self, xmpp, mbody): u"""Envia mensagem XMPP para quem está conversando comigo.""" if xmpp.talking_to is not None: mto = xmpp.talking_to # Envia mensagem XMPP. xmpp.send_message(mto=mto, mbody=mbody, mtype='chat') # Repete a mensagem que estou enviando para ser falada pelo Papovox. self.send_chat_message(u"eu", mbody) # Avisa se o contato estiver offline. bare_jid = xmpp.get_bare_jid(mto) roster = xmpp.client_roster if bare_jid in roster and not roster[bare_jid].resources: name = xmpp.get_chatty_name(mto) self.sendmessage(S.WARN_MSG_TO_OFFLINE_USER.format(name=name)) else: mto = u"ninguém" self.sendmessage(S.WARN_MSG_TO_NOBODY) log.debug(u"-> %(mto)s: %(mbody)s", locals()) # Funções de envio de dados para o Papovox --------------------------------# def sendline(self, line): u"""Codifica e envia texto via socket pelo protocolo do Papovox. Uma quebra de linha é adicionada automaticamente ao fim da mensagem. Nota: esta função *não* deve ser usada para enviar mensagens. Use apenas para transmitir dados brutos de comunicação. """ log.debug(u"> %s", line) line = line.encode(SYSTEM_ENCODING, 'replace') self.socket.sendall("%s\r\n" % (line,)) def sendmessage(self, msg): u"""Codifica e envia uma mensagem via socket pelo protocolo do Papovox.""" log.debug(u">> %s", msg) msg = msg.encode(SYSTEM_ENCODING, 'replace') # Apesar de teoricamente o protocolo do Papovox suportar mensagens com até # 65535 (2^16 - 1) caracteres, na prática apenas os 255 primeiros são # exibidos, e os restantes acabam ignorados. # Portanto, é necessário quebrar mensagens grandes em várias menores. chunks = textwrap.wrap( text=msg, width=self.TAMANHO_MAXIMO_MSG, expand_tabs=False, replace_whitespace=False, drop_whitespace=False, ) def sendmsg(msg): self.socket.sendall("%s%s" % (struct.pack('<BH', self.DADOTECLADO, len(msg)), msg)) # Envia uma ou mais mensagens pelo socket map(sendmsg, chunks) def send_chat_message(self, sender, body, _state={}): u"""Formata e envia uma mensagem de bate-papo via socket. Use esta função para enviar uma mensagem para o Papovox sintetizar. """ # Tempo máximo entre duas mensagens para considerar que fazem parte da mesma # conversa, em segundos. TIMEOUT = 90 # Recupera estado. last_sender = _state.get('last_sender') last_timestamp = _state.get('last_timestamp', 0) # em segundos timestamp = time.time() timed_out = (time.time() - last_timestamp) > TIMEOUT if sender == last_sender and not timed_out: msg = S.MSG else: msg = S.MSG_FROM self.sendmessage(msg.format(**locals())) # Guarda estado para ser usado na próxima execução. _state['last_sender'] = sender _state['last_timestamp'] = timestamp def signal_error(self, msg): u"""Sinaliza erro para o Papovox e termina a conexão.""" # Avisa Papovox sobre o erro. self.sendmessage(msg) # Encerra conexão com o Papovox. self.disconnect() # Funções de recebimento de dados do Papovox ------------------------------# def recv(self, size): u"""Recebe dados via socket. Use esta função para receber do socket `size' bytes ou menos. Levanta uma exceção caso nenhum byte seja recebido. Nota: em geral, use esta função ao invés do método 'socket.recv'. Veja também a função 'recvall'. """ data = self.socket.recv(size) if not data and size: raise socket.error(u"Nenhum dado recebido do socket, conexão perdida.") return data def recvline(self, size): u"""Recebe uma linha via socket. A string é retornada em unicode e não contém \r nem \n. """ # Assume que apenas uma linha está disponível no socket. data = self.recv(size).rstrip('\r\n') data = data.decode(SYSTEM_ENCODING) if any(c in data for c in '\r\n'): log.warning("Mais que uma linha recebida!") return data def recvall(self, size): u"""Recebe dados exaustivamente via socket. Use esta função para receber do socket exatamente `size' bytes. Levanta uma exceção caso nenhum byte seja recebido. Nota: em geral, use esta função ou 'recv' ao invés do método 'socket.recv'. """ data = StringIO() while data.tell() < size: data.write(self.recv(size - data.tell())) data_str = data.getvalue() data.close() return data_str def recvmessage(self): u"""Recebe uma mensagem via socket pelo protocolo do Papovox. A mensagem é retornada em unicode. Se uma exceção não for levantada, esta função sempre retorna uma mensagem. """ # Tenta receber mensagem até obter sucesso. while True: datatype, datalen = struct.unpack('<BH', self.recvall(3)) # Recusa dados do Papovox que não sejam do tipo DADOTECLADO if datatype != self.DADOTECLADO: log.warning(u"Tipo de dado desconhecido: (%d).", datatype) continue # Ignora mensagens vazias if datalen == 0: log.debug(u"Mensagem vazia ignorada") continue # Recebe dados/mensagem do Papovox data = self.recvall(datalen) data = data.decode(SYSTEM_ENCODING) return data # FIXME Remover referências hard-coded para comandos e o prefixo de comando.
rhcarvalho/xmppvox
xmppvox/server.py
Python
gpl-3.0
12,781
/** -*- mode: c++ ; c-basic-offset: 2 -*- * * @file SeparatorParameter.cpp * * Copyright 2017 Sebastien Fourey * * This file is part of G'MIC-Qt, a generic plug-in for raster graphics * editors, offering hundreds of filters thanks to the underlying G'MIC * image processing framework. * * gmic_qt 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. * * gmic_qt 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 gmic_qt. If not, see <http://www.gnu.org/licenses/>. * */ #include "SeparatorParameter.h" #include "Common.h" #include <QFrame> #include <QSizePolicy> #include <QGridLayout> SeparatorParameter::SeparatorParameter(QObject *parent) : AbstractParameter(parent,false), _frame(0) { } SeparatorParameter::~SeparatorParameter() { delete _frame; } void SeparatorParameter::addTo(QWidget * widget, int row) { QGridLayout * grid = dynamic_cast<QGridLayout*>(widget->layout()); if (! grid) return; delete _frame; _frame = new QFrame(widget); QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(_frame->sizePolicy().hasHeightForWidth()); _frame->setSizePolicy(sizePolicy); _frame->setFrameShape(QFrame::HLine); _frame->setFrameShadow(QFrame::Sunken); grid->addWidget(_frame,row,0,1,3); } QString SeparatorParameter::textValue() const { return QString::null; } void SeparatorParameter::setValue(const QString &) { } void SeparatorParameter::reset() { } void SeparatorParameter::initFromText(const char * text, int & textLength) { QStringList list = parseText("separator",text,textLength); unused(list); }
boudewijnrempt/gmic-qt
src/SeparatorParameter.cpp
C++
gpl-3.0
2,143
import urllib import urllib2 import json import time import hmac,hashlib def createTimeStamp(datestr, format="%Y-%m-%d %H:%M:%S"): return time.mktime(time.strptime(datestr, format)) class poloniex: def __init__(self, APIKey, Secret): self.APIKey = APIKey self.Secret = Secret def post_process(self, before): after = before # Add timestamps if there isnt one but is a datetime if('return' in after): if(isinstance(after['return'], list)): for x in xrange(0, len(after['return'])): if(isinstance(after['return'][x], dict)): if('datetime' in after['return'][x] and 'timestamp' not in after['return'][x]): after['return'][x]['timestamp'] = float(createTimeStamp(after['return'][x]['datetime'])) return after def api_query(self, command, req={}): if(command == "returnTicker" or command == "return24Volume"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command)) return json.loads(ret.read()) elif(command == "returnChartData"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair'] + '&start=' + str((int(time.time()) - req['chartDataAge'])) + '&period=' + str(300)))) return json.loads(ret.read()) elif(command == "returnOrderBook"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + command + '&currencyPair=' + str(req['currencyPair']))) return json.loads(ret.read()) elif(command == "returnMarketTradeHistory"): ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/public?command=' + "returnTradeHistory" + '&currencyPair=' + str(req['currencyPair']))) return json.loads(ret.read()) else: req['command'] = command req['nonce'] = int(time.time()*1000) post_data = urllib.urlencode(req) sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest() headers = { 'Sign': sign, 'Key': self.APIKey } ret = urllib2.urlopen(urllib2.Request('https://poloniex.com/tradingApi', post_data, headers)) jsonRet = json.loads(ret.read()) return self.post_process(jsonRet) def returnTicker(self): return self.api_query("returnTicker") def returnChartData(self, currencyPair, chartDataAge = 300): return self.api_query("returnChartData", {'currencyPair': currencyPair, 'chartDataAge' : chartDataAge}) def return24Volume(self): return self.api_query("return24Volume") def returnOrderBook (self, currencyPair): return self.api_query("returnOrderBook", {'currencyPair': currencyPair}) def returnMarketTradeHistory (self, currencyPair): return self.api_query("returnMarketTradeHistory", {'currencyPair': currencyPair}) # Returns all of your balances. # Outputs: # {"BTC":"0.59098578","LTC":"3.31117268", ... } def returnBalances(self): return self.api_query('returnBalances') # Returns your open orders for a given market, specified by the "currencyPair" POST parameter, e.g. "BTC_XCP" # Inputs: # currencyPair The currency pair e.g. "BTC_XCP" # Outputs: # orderNumber The order number # type sell or buy # rate Price the order is selling or buying at # Amount Quantity of order # total Total value of order (price * quantity) def returnOpenOrders(self,currencyPair): return self.api_query('returnOpenOrders',{"currencyPair":currencyPair}) # Returns your trade history for a given market, specified by the "currencyPair" POST parameter # Inputs: # currencyPair The currency pair e.g. "BTC_XCP" # Outputs: # date Date in the form: "2014-02-19 03:44:59" # rate Price the order is selling or buying at # amount Quantity of order # total Total value of order (price * quantity) # type sell or buy def returnTradeHistory(self,currencyPair): return self.api_query('returnTradeHistory',{"currencyPair":currencyPair}) # Places a buy order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number. # Inputs: # currencyPair The curreny pair # rate price the order is buying at # amount Amount of coins to buy # Outputs: # orderNumber The order number def buy(self,currencyPair,rate,amount): return self.api_query('buy',{"currencyPair":currencyPair,"rate":rate,"amount":amount}) # Places a sell order in a given market. Required POST parameters are "currencyPair", "rate", and "amount". If successful, the method will return the order number. # Inputs: # currencyPair The curreny pair # rate price the order is selling at # amount Amount of coins to sell # Outputs: # orderNumber The order number def sell(self,currencyPair,rate,amount): return self.api_query('sell',{"currencyPair":currencyPair,"rate":rate,"amount":amount}) # Cancels an order you have placed in a given market. Required POST parameters are "currencyPair" and "orderNumber". # Inputs: # currencyPair The curreny pair # orderNumber The order number to cancel # Outputs: # succes 1 or 0 def cancel(self,currencyPair,orderNumber): return self.api_query('cancelOrder',{"currencyPair":currencyPair,"orderNumber":orderNumber}) # Immediately places a withdrawal for a given currency, with no email confirmation. In order to use this method, the withdrawal privilege must be enabled for your API key. Required POST parameters are "currency", "amount", and "address". Sample output: {"response":"Withdrew 2398 NXT."} # Inputs: # currency The currency to withdraw # amount The amount of this coin to withdraw # address The withdrawal address # Outputs: # response Text containing message about the withdrawal def withdraw(self, currency, amount, address): return self.api_query('withdraw',{"currency":currency, "amount":amount, "address":address})
Vadus/eldo
src/poloniex/poloniex.py
Python
gpl-3.0
6,502
<?php if(isset($_GET['id'])) { // Allocate a new XSLT processor $xh = xslt_create(); // Process the document if (xslt_process($xh, "xml/audio/$id", "xsl/audio/audio.xsl", "gen/audio/$id.xml")) { readfile("gen/audio/$id.xml"); } else { echo "Error : " . xslt_error($xh) . " and the "; echo "error code is " . xslt_errno($xh); } xslt_free($xh); } ?>
astorije/projet-nf29-a10
export_html/p_audio.php
PHP
gpl-3.0
395
package com.androidGames.lettersoup; import java.io.IOException; import java.io.InputStream; import org.json.JSONException; import org.json.JSONObject; import android.os.Build; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.drawable.ColorDrawable; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View.OnTouchListener; import android.widget.FrameLayout; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; import android.support.v4.app.NavUtils; public class PlayGameActivity extends Activity { private char[][] boardGame; PlayGameView playgameview; private String puzzle = ""; FrameLayout layout; Paint paint; private float width; private float height; private float x; private float y; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_play_game); //Get the JSON object from the data JSONObject parent = this.parseJSONData(); paint = new Paint(); paint.setAlpha(255); paint.setColor(Color.BLUE); paint.setStyle(Style.STROKE); paint.setStrokeWidth(5); /*//THis will store all the values inside "Hydrogen" in a element string try { String element = parent.getString("Nivel1"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ //THis will store "1" inside atomicNumber try { puzzle = parent.getJSONObject("Nivel1").getString("Puzzle"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d("onCreate", "oncreate"); Log.w("onCreate", "oncreate"); this.boardGame = board(4,5); this.boardGame = fillBoardGame(puzzle,this.boardGame); Log.d("onCreate", ""+this.boardGame ); final GridView gridView = (GridView) findViewById(R.id.playgamegrid); gridView.setNumColumns(4); gridView.setAdapter(new PlayGameViewAdapter(this,this.getBoard())); gridView.setOnTouchListener(new OnTouchListener() { String text=""; int pos = 0; @SuppressWarnings("unused") protected void onDraw(Canvas canvas) { canvas.drawLine(x, y, width, height, paint); } @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub float currentXPosition = event.getX(); float currentYPosition = event.getY(); int position = gridView.pointToPosition((int) currentXPosition, (int) currentYPosition); TextView tv = (TextView) gridView.getChildAt(position); width = tv.getWidth(); height = tv.getHeight(); switch(event.getAction()) { case MotionEvent.ACTION_DOWN: pos = position; text += tv.getText(); //tv.setBackgroundColor(Color.RED); return true; case MotionEvent.ACTION_MOVE: if(pos != position) { x=event.getX(); y=event.getY(); pos = position; text += tv.getText(); } gridView.invalidateViews(); //adapter.notifyDataChanged(); //grid.setAdapter(adapter); return true; case MotionEvent.ACTION_UP: getWordBoard(text); return true; } return false; } }); /*PlayGameView playgameview = new PlayGameView(this); setContentView(playgameview); playgameview.requestFocus();*/ //RelativeLayout game = (RelativeLayout)findViewById(R.id.layoutgame); //game.addView(playgameview); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Show the Up button in the action bar. setupActionBar(); } } /** * Set up the {@link android.app.ActionBar}. */ private void setupActionBar() { getActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.play_game, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } public char[][] board(int x, int y) { final char board[][] = new char [x][y]; return board; } public char[][] fillBoardGame(String string,char[][] board) { int indexString=0; int nCols = this.getColsBoard(); int nRows = this.getRowsBoard(); for (int i = 0; i < nRows; i++) { for(int k = 0; k<nCols;k++) { this.boardGame[i][k] = string.charAt(indexString); indexString++; } Log.d("fillBoard", ""+this.boardGame[i][0]); } return this.boardGame; } public String getcharBoard(int x, int y){ StringBuilder charBoard = new StringBuilder(); Log.d("getcharBoard", ""+this.boardGame[x][y]); charBoard.append(this.boardGame[x][y]); return charBoard.toString(); } public int getColsBoard() { Log.d("numCols",""+this.boardGame[0].length); return this.boardGame[0].length; } public int getRowsBoard(){ Log.d("numRows",""+this.boardGame.length); return this.boardGame.length; } public String[] getBoard() { final String[] texts = new String[puzzle.length()]; for(int i=0;i<puzzle.length();i++) { texts[i]=""+puzzle.charAt(i); } return texts; } public JSONObject parseJSONData() { String JSONString = null; JSONObject JSONObject = null; try { //open the inputStream to the file InputStream inputStream = getAssets().open("PuzzleStore.json"); int sizeOfJSONFile = inputStream.available(); //array that will store all the data byte[] bytes = new byte[sizeOfJSONFile]; //reading data into the array from the file inputStream.read(bytes); //close the input stream inputStream.close(); JSONString = new String(bytes, "UTF-8"); JSONObject = new JSONObject(JSONString); } catch (IOException ex) { ex.printStackTrace(); return null; } catch (JSONException x) { x.printStackTrace(); return null; } return JSONObject; } public void getWordBoard(String caracter) { String word = caracter; Log.d("Word",word); } }
papoon/sopa_letras
LetterSoup/src/com/androidGames/lettersoup/PlayGameActivity.java
Java
gpl-3.0
7,386
/*! * Ext JS Library * Copyright(c) 2006-2014 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ Ext.define('Ext.org.micoli.app.modules.GridWindow', { extend: 'Ext.ux.desktop.Module', requires: [ 'Ext.data.ArrayStore', 'Ext.util.Format', 'Ext.grid.Panel', 'Ext.grid.RowNumberer' ], id:'grid-win', init : function(){ this.launcher = { text: 'Grid Window', iconCls:'icon-grid' }; }, createWindow : function(){ var desktop = this.app.getDesktop(); var win = desktop.getWindow('grid-win'); if(!win){ win = desktop.createWindow({ id: 'grid-win', title:'Grid Window', width:740, height:480, iconCls: 'icon-grid', animCollapse:false, constrainHeader:true, layout: 'fit', items: [ { border: false, xtype: 'grid', store: new Ext.data.ArrayStore({ fields: [ { name: 'company' }, { name: 'price', type: 'float' }, { name: 'change', type: 'float' }, { name: 'pctChange', type: 'float' } ], data: Ext.org.micoli.app.modules.GridWindow.getDummyData() }), columns: [ new Ext.grid.RowNumberer(), { text: "Company", flex: 1, sortable: true, dataIndex: 'company' }, { text: "Price", width: 70, sortable: true, renderer: Ext.util.Format.usMoney, dataIndex: 'price' }, { text: "Change", width: 70, sortable: true, dataIndex: 'change' }, { text: "% Change", width: 70, sortable: true, dataIndex: 'pctChange' } ] } ], tbar:[{ text:'Add Something', tooltip:'Add a new row', iconCls:'add' }, '-', { text:'Options', tooltip:'Modify options', iconCls:'option' },'-',{ text:'Remove Something', tooltip:'Remove the selected item', iconCls:'remove' }] }); } return win; }, statics: { getDummyData: function () { return [ ['3m Co',71.72,0.02,0.03], ['Alcoa Inc',29.01,0.42,1.47], ['American Express Company',52.55,0.01,0.02], ['American International Group, Inc.',64.13,0.31,0.49], ['AT&T Inc.',31.61,-0.48,-1.54], ['Caterpillar Inc.',67.27,0.92,1.39], ['Citigroup, Inc.',49.37,0.02,0.04], ['Exxon Mobil Corp',68.1,-0.43,-0.64], ['General Electric Company',34.14,-0.08,-0.23], ['General Motors Corporation',30.27,1.09,3.74], ['Hewlett-Packard Co.',36.53,-0.03,-0.08], ['Honeywell Intl Inc',38.77,0.05,0.13], ['Intel Corporation',19.88,0.31,1.58], ['Johnson & Johnson',64.72,0.06,0.09], ['Merck & Co., Inc.',40.96,0.41,1.01], ['Microsoft Corporation',25.84,0.14,0.54], ['The Coca-Cola Company',45.07,0.26,0.58], ['The Procter & Gamble Company',61.91,0.01,0.02], ['Wal-Mart Stores, Inc.',45.45,0.73,1.63], ['Walt Disney Company (The) (Holding Company)',29.89,0.24,0.81] ]; } } });
micoli/reQuester
desk6/app/org/micoli/app/modules/samples/GridWindow.js
JavaScript
gpl-3.0
3,137