code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
DELETE FROM `weenie` WHERE `class_Id` = 9309; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (9309, 'undeadtinytrianglequest', 10, '2019-02-10 00:00:00') /* Creature */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (9309, 1, 16) /* ItemType - Creature */ , (9309, 2, 14) /* CreatureType - Undead */ , (9309, 6, -1) /* ItemsCapacity */ , (9309, 7, -1) /* ContainersCapacity */ , (9309, 16, 32) /* ItemUseable - Remote */ , (9309, 25, 66) /* Level */ , (9309, 93, 6292504) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity, ReportCollisionsAsEnvironment, EdgeSlide */ , (9309, 95, 8) /* RadarBlipColor - Yellow */ , (9309, 133, 4) /* ShowableOnRadar - ShowAlways */ , (9309, 134, 16) /* PlayerKillerStatus - RubberGlue */ , (9309, 8007, 0) /* PCAPRecordedAutonomousMovement */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (9309, 1, True ) /* Stuck */ , (9309, 19, False) /* Attackable */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (9309, 54, 3) /* UseRadius */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (9309, 1, 'Saelar''s Apprentice') /* Name */ , (9309, 8006, 'AAA9AAAAAAA=') /* PCAPRecordedCurrentMotionState */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (9309, 1, 0x02000197) /* Setup */ , (9309, 2, 0x09000017) /* MotionTable */ , (9309, 3, 0x20000016) /* SoundTable */ , (9309, 6, 0x04000742) /* PaletteBase */ , (9309, 8, 0x06001226) /* Icon */ , (9309, 8001, 9437238) /* PCAPRecordedWeenieHeader - ItemsCapacity, ContainersCapacity, Usable, UseRadius, RadarBlipColor, RadarBehavior */ , (9309, 8003, 4) /* PCAPRecordedObjectDesc - Stuck */ , (9309, 8005, 100355) /* PCAPRecordedPhysicsDesc - CSetup, MTable, STable, Position, Movement */; INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`) VALUES (9309, 8040, 0x029D0104, 9.33585, -8.65844, 0.0075, -0.663095, 0, 0, -0.748535) /* PCAPRecordedLocation */ /* @teleloc 0x029D0104 [9.335850 -8.658440 0.007500] -0.663095 0.000000 0.000000 -0.748535 */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (9309, 8000, 0xA5B8E385) /* PCAPRecordedObjectIID */; INSERT INTO `weenie_properties_attribute` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`) VALUES (9309, 1, 200, 0, 0) /* Strength */ , (9309, 2, 250, 0, 0) /* Endurance */ , (9309, 3, 200, 0, 0) /* Quickness */ , (9309, 4, 260, 0, 0) /* Coordination */ , (9309, 5, 240, 0, 0) /* Focus */ , (9309, 6, 30, 0, 0) /* Self */; INSERT INTO `weenie_properties_attribute_2nd` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`, `current_Level`) VALUES (9309, 1, 150, 0, 0, 275) /* MaxHealth */ , (9309, 3, 235, 0, 0, 485) /* MaxStamina */ , (9309, 5, 80, 0, 0, 110) /* MaxMana */; INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`) VALUES (9309, 67111341, 0, 0);
ACEmulator/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/Creature/Undead/09309 Saelar's Apprentice.sql
SQL
agpl-3.0
3,398
#include "action_header.h" #include "../dao/ServerBackupDao.h" #include "../server_channel.h" #include "../server_settings.h" namespace { class RemoveRestoreToken : public IObject { std::string token; public: RemoveRestoreToken(std::string token) : token(token) {} ~RemoveRestoreToken() { ServerChannelThread::remove_restore_token(token); } }; } ACTION_IMPL(restore_image) { Helper helper(tid, &POST, &PARAMS); SUser* session = helper.getSession(); if (session != NULL && session->id == SESSION_ID_INVALID) return; JSON::Object ret; if (session == NULL) { ret.set("error", 1); helper.Write(ret.stringify(false)); return; } bool all_browse_backups; std::vector<int> browse_backups_rights = helper.clientRights(RIGHT_BROWSE_BACKUPS, all_browse_backups); ServerBackupDao dao(helper.getDatabase()); int backupid = watoi(POST["backupid"]); ServerBackupDao::CondInt clientid = dao.getClientidByImageid(backupid); if (!clientid.exists) { return; } if (!all_browse_backups && std::find(browse_backups_rights.begin(), browse_backups_rights.end(), clientid.value) == browse_backups_rights.end()) { return; } db_results restore_authkey = helper.getDatabase()->Read("SELECT value FROM settings_db.settings WHERE key='restore_authkey' AND clientid=0"); if (restore_authkey.size() != 1) { return; } std::string token = ServerSettings::generateRandomAuthKey(); ServerChannelThread::add_restore_token(token, backupid); IObject* curr = helper.getSession()->getCustomPtr("rm_restore_token"); if (curr != NULL) { curr->Remove(); } helper.getSession()->mCustom["rm_restore_token"] = new RemoveRestoreToken(token); ret.set("ok", true); ret.set("token", token); ret.set("authkey", restore_authkey[0]["value"]); helper.Write(ret.stringify(false)); }
uroni/urbackup_backend
urbackupserver/serverinterface/restore_image.cpp
C++
agpl-3.0
1,893
DELETE FROM `weenie` WHERE `class_Id` = 36085; INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`) VALUES (36085, 'ace36085-lordharanueamarand', 10, '2019-02-10 00:00:00') /* Creature */; INSERT INTO `weenie_properties_int` (`object_Id`, `type`, `value`) VALUES (36085, 1, 16) /* ItemType - Creature */ , (36085, 6, -1) /* ItemsCapacity */ , (36085, 7, -1) /* ContainersCapacity */ , (36085, 16, 32) /* ItemUseable - Remote */ , (36085, 93, 6292508) /* PhysicsState - Ethereal, ReportCollisions, IgnoreCollisions, Gravity, ReportCollisionsAsEnvironment, EdgeSlide */ , (36085, 95, 8) /* RadarBlipColor - Yellow */ , (36085, 133, 4) /* ShowableOnRadar - ShowAlways */ , (36085, 8007, 0) /* PCAPRecordedAutonomousMovement */; INSERT INTO `weenie_properties_bool` (`object_Id`, `type`, `value`) VALUES (36085, 1, True ) /* Stuck */ , (36085, 19, False) /* Attackable */; INSERT INTO `weenie_properties_float` (`object_Id`, `type`, `value`) VALUES (36085, 54, 3) /* UseRadius */ , (36085, 76, 0.5) /* Translucency */; INSERT INTO `weenie_properties_string` (`object_Id`, `type`, `value`) VALUES (36085, 1, 'Lord Haranue Amarand') /* Name */ , (36085, 8006, 'AAA9AAAAAAA=') /* PCAPRecordedCurrentMotionState */; INSERT INTO `weenie_properties_d_i_d` (`object_Id`, `type`, `value`) VALUES (36085, 1, 0x02000001) /* Setup */ , (36085, 2, 0x09000025) /* MotionTable */ , (36085, 3, 0x2000001E) /* SoundTable */ , (36085, 6, 0x0400007E) /* PaletteBase */ , (36085, 8, 0x06001036) /* Icon */ , (36085, 8001, 9437238) /* PCAPRecordedWeenieHeader - ItemsCapacity, ContainersCapacity, Usable, UseRadius, RadarBlipColor, RadarBehavior */ , (36085, 8003, 4) /* PCAPRecordedObjectDesc - Stuck */ , (36085, 8005, 362563) /* PCAPRecordedPhysicsDesc - CSetup, MTable, Children, STable, Position, Movement, Translucency */; INSERT INTO `weenie_properties_position` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`) VALUES (36085, 8040, 0x00A3010C, 250.5, -186.432, -35.995, 0, 0, 0, -1) /* PCAPRecordedLocation */ /* @teleloc 0x00A3010C [250.500000 -186.432000 -35.995000] 0.000000 0.000000 0.000000 -1.000000 */; INSERT INTO `weenie_properties_i_i_d` (`object_Id`, `type`, `value`) VALUES (36085, 8000, 0xDCDBCB7A) /* PCAPRecordedObjectIID */; INSERT INTO `weenie_properties_create_list` (`object_Id`, `destination_Type`, `weenie_Class_Id`, `stack_Size`, `palette`, `shade`, `try_To_Bond`) VALUES (36085, 2, 36576, 1, 0, 0, False) /* Create Impious Staff (36576) for Wield */; INSERT INTO `weenie_properties_palette` (`object_Id`, `sub_Palette_Id`, `offset`, `length`) VALUES (36085, 67111813, 0, 0); INSERT INTO `weenie_properties_texture_map` (`object_Id`, `index`, `old_Id`, `new_Id`) VALUES (36085, 0, 83889342, 83890954) , (36085, 0, 83889072, 83890954) , (36085, 1, 83887064, 83890954) , (36085, 2, 83887066, 83890954) , (36085, 3, 83889344, 83890954) , (36085, 4, 83887068, 83890954) , (36085, 5, 83887064, 83890954) , (36085, 6, 83887066, 83890954) , (36085, 7, 83889344, 83890954) , (36085, 8, 83887068, 83890954) , (36085, 9, 83887061, 83890954) , (36085, 9, 83887060, 83890954) , (36085, 10, 83887069, 83890954) , (36085, 11, 83887067, 83890954) , (36085, 12, 83887059, 83890954) , (36085, 13, 83887069, 83890954) , (36085, 14, 83887067, 83890954) , (36085, 15, 83887059, 83890954) , (36085, 16, 83886233, 83890952) , (36085, 16, 83886232, 83890953) , (36085, 16, 83886519, 83890954); INSERT INTO `weenie_properties_anim_part` (`object_Id`, `index`, `animation_Id`) VALUES (36085, 0, 16777294) , (36085, 1, 16777295) , (36085, 2, 16777293) , (36085, 3, 16777292) , (36085, 4, 16777291) , (36085, 5, 16777299) , (36085, 6, 16777297) , (36085, 7, 16777296) , (36085, 8, 16777298) , (36085, 9, 16777300) , (36085, 10, 16777301) , (36085, 11, 16777302) , (36085, 12, 16777304) , (36085, 13, 16777303) , (36085, 14, 16777305) , (36085, 15, 16777307) , (36085, 16, 16781779);
ACEmulator/ACE-World
Database/3-Core/9 WeenieDefaults/SQL/Creature/Unsorted/36085 Lord Haranue Amarand.sql
SQL
agpl-3.0
4,355
/* * * (C) Copyright IBM Corp. 1998-2014 - All Rights Reserved * */ #include "LETypes.h" #include "LEScripts.h" #include "OpenTypeTables.h" #include "OpenTypeUtilities.h" #include "IndicReordering.h" U_NAMESPACE_BEGIN // Split matra table indices #define _x1 (1 << CF_INDEX_SHIFT) #define _x2 (2 << CF_INDEX_SHIFT) #define _x3 (3 << CF_INDEX_SHIFT) #define _x4 (4 << CF_INDEX_SHIFT) #define _x5 (5 << CF_INDEX_SHIFT) #define _x6 (6 << CF_INDEX_SHIFT) #define _x7 (7 << CF_INDEX_SHIFT) #define _x8 (8 << CF_INDEX_SHIFT) #define _x9 (9 << CF_INDEX_SHIFT) // simple classes #define _xx (CC_RESERVED) #define _ma (CC_VOWEL_MODIFIER | CF_POS_ABOVE) #define _mp (CC_VOWEL_MODIFIER | CF_POS_AFTER) #define _sa (CC_STRESS_MARK | CF_POS_ABOVE) #define _sb (CC_STRESS_MARK | CF_POS_BELOW) #define _iv (CC_INDEPENDENT_VOWEL) #define _i2 (CC_INDEPENDENT_VOWEL_2) #define _i3 (CC_INDEPENDENT_VOWEL_3) #define _ct (CC_CONSONANT | CF_CONSONANT) #define _cn (CC_CONSONANT_WITH_NUKTA | CF_CONSONANT) #define _nu (CC_NUKTA) #define _dv (CC_DEPENDENT_VOWEL) #define _dl (_dv | CF_POS_BEFORE) #define _db (_dv | CF_POS_BELOW) #define _da (_dv | CF_POS_ABOVE) #define _dr (_dv | CF_POS_AFTER) #define _lm (_dv | CF_LENGTH_MARK) #define _l1 (CC_SPLIT_VOWEL_PIECE_1 | CF_POS_BEFORE) #define _a1 (CC_SPLIT_VOWEL_PIECE_1 | CF_POS_ABOVE) #define _b2 (CC_SPLIT_VOWEL_PIECE_2 | CF_POS_BELOW) #define _r2 (CC_SPLIT_VOWEL_PIECE_2 | CF_POS_AFTER) #define _m2 (CC_SPLIT_VOWEL_PIECE_2 | CF_LENGTH_MARK) #define _m3 (CC_SPLIT_VOWEL_PIECE_3 | CF_LENGTH_MARK) #define _vr (CC_VIRAMA) #define _al (CC_AL_LAKUNA) // split matras #define _s1 (_dv | _x1) #define _s2 (_dv | _x2) #define _s3 (_dv | _x3) #define _s4 (_dv | _x4) #define _s5 (_dv | _x5) #define _s6 (_dv | _x6) #define _s7 (_dv | _x7) #define _s8 (_dv | _x8) #define _s9 (_dv | _x9) // consonants with special forms // NOTE: this assumes that no consonants with nukta have // special forms... (Bengali RA?) #define _bb (_ct | CF_BELOW_BASE) #define _pb (_ct | CF_POST_BASE) #define _fb (_ct | CF_PRE_BASE) #define _vt (_bb | CF_VATTU) #define _rv (_vt | CF_REPH) #define _rp (_pb | CF_REPH) #define _rb (_bb | CF_REPH) // // Character class tables // static const IndicClassTable::CharClass devaCharClasses[] = { _xx, _ma, _ma, _mp, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, // 0900 - 090F _iv, _iv, _iv, _iv, _iv, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, // 0910 - 091F _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _cn, _ct, _ct, _ct, _ct, _ct, _ct, // 0920 - 092F _rv, _cn, _ct, _ct, _cn, _ct, _ct, _ct, _ct, _ct, _xx, _xx, _nu, _xx, _dr, _dl, // 0930 - 093F _dr, _db, _db, _db, _db, _da, _da, _da, _da, _dr, _dr, _dr, _dr, _vr, _xx, _xx, // 0940 - 094F _xx, _sa, _sb, _sa, _sa, _xx, _xx, _xx, _cn, _cn, _cn, _cn, _cn, _cn, _cn, _cn, // 0950 - 095F _iv, _iv, _db, _db, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, // 0960 - 096F _xx // 0970 }; static const IndicClassTable::CharClass bengCharClasses[] = { _xx, _ma, _mp, _mp, _xx, _i2, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _xx, _xx, _i2, // 0980 - 098F _iv, _xx, _xx, _iv, _iv, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, // 0990 - 099F _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _xx, _ct, _ct, _bb, _ct, _ct, _pb, // 09A0 - 09AF _rv, _xx, _ct, _xx, _xx, _xx, _ct, _ct, _ct, _ct, _xx, _xx, _nu, _xx, _r2, _dl, // 09B0 - 09BF _dr, _db, _db, _db, _db, _xx, _xx, _l1, _dl, _xx, _xx, _s1, _s2, _vr, _xx, _xx, // 09C0 - 09CF _xx, _xx, _xx, _xx, _xx, _xx, _xx, _m2, _xx, _xx, _xx, _xx, _cn, _cn, _xx, _cn, // 09D0 - 09DF _iv, _iv, _dv, _dv, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, // 09E0 - 09EF _rv, _ct, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx // 09F0 - 09FA }; static const IndicClassTable::CharClass punjCharClasses[] = { _xx, _ma, _ma, _mp, _xx, _iv, _iv, _iv, _iv, _iv, _iv, _xx, _xx, _xx, _xx, _iv, // 0A00 - 0A0F _iv, _xx, _xx, _i3, _iv, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, // 0A10 - 0A1F _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _xx, _ct, _ct, _ct, _ct, _ct, _bb, // 0A20 - 0A2F _vt, _xx, _ct, _cn, _xx, _bb, _cn, _xx, _ct, _bb, _xx, _xx, _nu, _xx, _dr, _dl, // 0A30 - 0A3F _dr, _b2, _db, _xx, _xx, _xx, _xx, _da, _da, _xx, _xx, _a1, _da, _vr, _xx, _xx, // 0A40 - 0A4F _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _cn, _cn, _cn, _ct, _xx, _cn, _xx, // 0A50 - 0A5F _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, // 0A60 - 0A6F _ma, _ma, _xx, _xx, _xx // 0A70 - 0A74 }; static const IndicClassTable::CharClass gujrCharClasses[] = { _xx, _ma, _ma, _mp, _xx, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _xx, _iv, _xx, _iv, // 0A80 - 0A8F _iv, _iv, _xx, _iv, _iv, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, // 0A90 - 0A9F _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _xx, _ct, _ct, _ct, _ct, _ct, _ct, // 0AA0 - 0AAF _rv, _xx, _ct, _ct, _xx, _ct, _ct, _ct, _ct, _ct, _xx, _xx, _nu, _xx, _dr, _dl, // 0AB0 - 0ABF _dr, _db, _db, _db, _db, _da, _xx, _da, _da, _dr, _xx, _dr, _dr, _vr, _xx, _xx, // 0AC0 - 0ACF _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, // 0AD0 - 0ADF _iv, _iv, _db, _db, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx // 0AE0 - 0AEF }; #if 1 static const IndicClassTable::CharClass oryaCharClasses[] = { _xx, _ma, _mp, _mp, _xx, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _xx, _xx, _iv, /* 0B00 - 0B0F */ _iv, _xx, _xx, _iv, _iv, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _ct, _bb, /* 0B10 - 0B1F */ _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _xx, _bb, _bb, _bb, _bb, _bb, _pb, /* 0B20 - 0B2F */ _rb, _xx, _bb, _bb, _xx, _bb, _bb, _bb, _bb, _bb, _xx, _xx, _nu, _xx, _dr, _da, /* 0B30 - 0B3F */ _dr, _db, _db, _db, _xx, _xx, _xx, _dl, _s1, _xx, _xx, _s2, _s3, _vr, _xx, _xx, /* 0B40 - 0B4F */ _xx, _xx, _xx, _xx, _xx, _xx, _da, _dr, _xx, _xx, _xx, _xx, _cn, _cn, _xx, _pb, /* 0B50 - 0B5F */ _iv, _iv, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, /* 0B60 - 0B6F */ _xx, _bb /* 0B70 - 0B71 */ }; #else static const IndicClassTable::CharClass oryaCharClasses[] = { _xx, _ma, _mp, _mp, _xx, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _xx, _xx, _iv, // 0B00 - 0B0F _iv, _xx, _xx, _iv, _iv, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, // 0B10 - 0B1F _ct, _ct, _ct, _ct, _bb, _ct, _ct, _ct, _bb, _xx, _ct, _ct, _bb, _bb, _bb, _pb, // 0B20 - 0B2F _rb, _xx, _bb, _bb, _xx, _ct, _ct, _ct, _ct, _ct, _xx, _xx, _nu, _xx, _r2, _da, // 0B30 - 0B3F _dr, _db, _db, _db, _xx, _xx, _xx, _l1, _s1, _xx, _xx, _s2, _s3, _vr, _xx, _xx, // 0B40 - 0B4F _xx, _xx, _xx, _xx, _xx, _xx, _m2, _m2, _xx, _xx, _xx, _xx, _cn, _cn, _xx, _cn, // 0B50 - 0B5F _iv, _iv, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, // 0B60 - 0B6F _xx, _ct // 0B70 - 0B71 }; #endif static const IndicClassTable::CharClass tamlCharClasses[] = { _xx, _xx, _ma, _xx, _xx, _iv, _iv, _iv, _iv, _iv, _iv, _xx, _xx, _xx, _iv, _iv, // 0B80 - 0B8F _iv, _xx, _iv, _iv, _iv, _ct, _xx, _xx, _xx, _ct, _ct, _xx, _ct, _xx, _ct, _ct, // 0B90 - 0B9F _xx, _xx, _xx, _ct, _ct, _xx, _xx, _xx, _ct, _ct, _ct, _xx, _xx, _xx, _ct, _ct, // 0BA0 - 0BAF _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _xx, _xx, _xx, _xx, _r2, _dr, // 0BB0 - 0BBF _da, _dr, _dr, _xx, _xx, _xx, _l1, _l1, _dl, _xx, _s1, _s2, _s3, _vr, _xx, _xx, // 0BC0 - 0BCF _xx, _xx, _xx, _xx, _xx, _xx, _xx, _m2, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, // 0BD0 - 0BDF _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, // 0BE0 - 0BEF _xx, _xx, _xx // 0BF0 - 0BF2 }; // FIXME: Should some of the bb's be pb's? (KA, NA, MA, YA, VA, etc. (approx 13)) // U+C43 and U+C44 are _lm here not _dr. Similar to the situation with U+CC3 and // U+CC4 in Kannada below. static const IndicClassTable::CharClass teluCharClasses[] = { _xx, _mp, _mp, _mp, _xx, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _xx, _iv, _iv, // 0C00 - 0C0F _iv, _xx, _iv, _iv, _iv, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, // 0C10 - 0C1F _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _xx, _bb, _bb, _bb, _bb, _bb, _bb, // 0C20 - 0C2F _bb, _bb, _bb, _bb, _xx, _bb, _bb, _bb, _bb, _bb, _xx, _xx, _xx, _xx, _da, _da, // 0C30 - 0C3F _da, _dr, _dr, _lm, _lm, _xx, _a1, _da, _s1, _xx, _da, _da, _da, _vr, _xx, _xx, // 0C40 - 0C4F _xx, _xx, _xx, _xx, _xx, _da, _m2, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, // 0C50 - 0C5F _iv, _iv, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx // 0C60 - 0C6F }; // U+CC3 and U+CC4 are _lm here not _dr since the Kannada rendering // rules want them below and to the right of the entire cluster // // There's some information about this in: // // http://brahmi.sourceforge.net/docs/KannadaComputing.html static const IndicClassTable::CharClass kndaCharClasses[] = { _xx, _xx, _mp, _mp, _xx, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _xx, _iv, _iv, // 0C80 - 0C8F _iv, _xx, _iv, _iv, _iv, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, // 0C90 - 0C9F _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _bb, _xx, _bb, _bb, _bb, _bb, _bb, _bb, // 0CA0 - 0CAF _rb, _ct, _bb, _bb, _xx, _bb, _bb, _bb, _bb, _bb, _xx, _xx, _xx, _xx, _dr, _da, // 0CB0 - 0CBF _s1, _dr, _r2, _lm, _lm, _xx, _a1, _s2, _s3, _xx, _s4, _s5, _da, _vr, _xx, _xx, // 0CC0 - 0CCF _xx, _xx, _xx, _xx, _xx, _m3, _m2, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _ct, _xx, // 0CD0 - 0CDF _iv, _iv, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx // 0CE0 - 0CEF }; // FIXME: this is correct for old-style Malayalam (MAL) but not for reformed Malayalam (MLR) // FIXME: should there be a REPH for old-style Malayalam? static const IndicClassTable::CharClass mlymCharClasses[] = { _xx, _xx, _mp, _mp, _xx, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _xx, _iv, _iv, // 0D00 - 0D0F _iv, _xx, _iv, _iv, _iv, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, // 0D10 - 0D1F _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _xx, _ct, _ct, _ct, _ct, _ct, _pb, // 0D20 - 0D2F _fb, _fb, _bb, _ct, _ct, _pb, _ct, _ct, _ct, _ct, _xx, _xx, _xx, _xx, _r2, _dr, // 0D30 - 0D3F _dr, _dr, _dr, _dr, _xx, _xx, _l1, _l1, _dl, _xx, _s1, _s2, _s3, _vr, _xx, _xx, // 0D40 - 0D4F _xx, _xx, _xx, _xx, _xx, _xx, _xx, _m2, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, // 0D50 - 0D5F _iv, _iv, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx // 0D60 - 0D6F }; static const IndicClassTable::CharClass sinhCharClasses[] = { _xx, _xx, _mp, _mp, _xx, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, _iv, // 0D80 - 0D8F _iv, _iv, _iv, _iv, _iv, _iv, _iv, _xx, _xx, _xx, _ct, _ct, _ct, _ct, _ct, _ct, // 0D90 - 0D9F _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, // 0DA0 - 0DAF _ct, _ct, _xx, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _ct, _xx, _ct, _xx, _xx, // 0DB0 - 0DBF _ct, _ct, _ct, _ct, _ct, _ct, _ct, _xx, _xx, _xx, _al, _xx, _xx, _xx, _xx, _dr, // 0DC0 - 0DCF _dr, _dr, _da, _da, _db, _xx, _db, _xx, _dr, _dl, _s1, _dl, _s2, _s3, _s4, _dr, // 0DD0 - 0DDF _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, _xx, // 0DE0 - 0DEF _xx, _xx, _dr, _dr, _xx // 0DF0 - 0DF4 }; // // Split matra tables // static const SplitMatra bengSplitTable[] = {{0x09C7, 0x09BE}, {0x09C7, 0x09D7}}; static const SplitMatra oryaSplitTable[] = {{0x0B47, 0x0B56}, {0x0B47, 0x0B3E}, {0x0B47, 0x0B57}}; static const SplitMatra tamlSplitTable[] = {{0x0BC6, 0x0BBE}, {0x0BC7, 0x0BBE}, {0x0BC6, 0x0BD7}}; static const SplitMatra teluSplitTable[] = {{0x0C46, 0x0C56}}; static const SplitMatra kndaSplitTable[] = {{0x0CBF, 0x0CD5}, {0x0CC6, 0x0CD5}, {0x0CC6, 0x0CD6}, {0x0CC6, 0x0CC2}, {0x0CC6, 0x0CC2, 0x0CD5}}; static const SplitMatra mlymSplitTable[] = {{0x0D46, 0x0D3E}, {0x0D47, 0x0D3E}, {0x0D46, 0x0D57}}; static const SplitMatra sinhSplitTable[] = {{0x0DD9, 0x0DCA}, {0x0DD9, 0x0DCF}, {0x0DD9, 0x0DCF, 0x0DCA}, {0x0DD9, 0x0DDF}}; // // Script Flags // // FIXME: post 'GSUB' reordering of MATRA_PRE's for Malayalam and Tamil // FIXME: reformed Malayalam needs to reorder VATTU to before base glyph... // FIXME: not sure passing ZWJ/ZWNJ is best way to render Malayalam Cillu... // FIXME: eyelash RA only for Devanagari?? #define DEVA_SCRIPT_FLAGS (SF_EYELASH_RA | SF_NO_POST_BASE_LIMIT | SF_FILTER_ZERO_WIDTH) #define BENG_SCRIPT_FLAGS (SF_REPH_AFTER_BELOW | SF_NO_POST_BASE_LIMIT | SF_FILTER_ZERO_WIDTH) #define PUNJ_SCRIPT_FLAGS (SF_NO_POST_BASE_LIMIT | SF_FILTER_ZERO_WIDTH) #define GUJR_SCRIPT_FLAGS (SF_NO_POST_BASE_LIMIT | SF_FILTER_ZERO_WIDTH) #define ORYA_SCRIPT_FLAGS (SF_REPH_AFTER_BELOW | SF_NO_POST_BASE_LIMIT | SF_FILTER_ZERO_WIDTH) #define TAML_SCRIPT_FLAGS (SF_MPRE_FIXUP | SF_NO_POST_BASE_LIMIT | SF_FILTER_ZERO_WIDTH) #define TELU_SCRIPT_FLAGS (SF_MATRAS_AFTER_BASE | SF_FILTER_ZERO_WIDTH | 3) #define KNDA_SCRIPT_FLAGS (SF_MATRAS_AFTER_BASE | SF_FILTER_ZERO_WIDTH | 3) #define MLYM_SCRIPT_FLAGS (SF_MPRE_FIXUP | SF_NO_POST_BASE_LIMIT /*| SF_FILTER_ZERO_WIDTH*/) #define SINH_SCRIPT_FLAGS (SF_NO_POST_BASE_LIMIT) // // Indic Class Tables // static const IndicClassTable devaClassTable = {0x0900, 0x0970, 2, DEVA_SCRIPT_FLAGS, devaCharClasses, NULL}; static const IndicClassTable bengClassTable = {0x0980, 0x09FA, 3, BENG_SCRIPT_FLAGS, bengCharClasses, bengSplitTable}; static const IndicClassTable punjClassTable = {0x0A00, 0x0A74, 2, PUNJ_SCRIPT_FLAGS, punjCharClasses, NULL}; static const IndicClassTable gujrClassTable = {0x0A80, 0x0AEF, 2, GUJR_SCRIPT_FLAGS, gujrCharClasses, NULL}; static const IndicClassTable oryaClassTable = {0x0B00, 0x0B71, 3, ORYA_SCRIPT_FLAGS, oryaCharClasses, oryaSplitTable}; static const IndicClassTable tamlClassTable = {0x0B80, 0x0BF2, 3, TAML_SCRIPT_FLAGS, tamlCharClasses, tamlSplitTable}; static const IndicClassTable teluClassTable = {0x0C00, 0x0C6F, 3, TELU_SCRIPT_FLAGS, teluCharClasses, teluSplitTable}; static const IndicClassTable kndaClassTable = {0x0C80, 0x0CEF, 4, KNDA_SCRIPT_FLAGS, kndaCharClasses, kndaSplitTable}; static const IndicClassTable mlymClassTable = {0x0D00, 0x0D6F, 4, MLYM_SCRIPT_FLAGS, mlymCharClasses, mlymSplitTable}; static const IndicClassTable sinhClassTable = {0x0D80, 0x0DF4, 4, SINH_SCRIPT_FLAGS, sinhCharClasses, sinhSplitTable}; // // IndicClassTable addresses // static const IndicClassTable * const indicClassTables[scriptCodeCount] = { NULL, /* 'zyyy' (COMMON) */ NULL, /* 'qaai' (INHERITED) */ NULL, /* 'arab' (ARABIC) */ NULL, /* 'armn' (ARMENIAN) */ &bengClassTable, /* 'beng' (BENGALI) */ NULL, /* 'bopo' (BOPOMOFO) */ NULL, /* 'cher' (CHEROKEE) */ NULL, /* 'copt' (COPTIC) */ NULL, /* 'cyrl' (CYRILLIC) */ NULL, /* 'dsrt' (DESERET) */ &devaClassTable, /* 'deva' (DEVANAGARI) */ NULL, /* 'ethi' (ETHIOPIC) */ NULL, /* 'geor' (GEORGIAN) */ NULL, /* 'goth' (GOTHIC) */ NULL, /* 'grek' (GREEK) */ &gujrClassTable, /* 'gujr' (GUJARATI) */ &punjClassTable, /* 'guru' (GURMUKHI) */ NULL, /* 'hani' (HAN) */ NULL, /* 'hang' (HANGUL) */ NULL, /* 'hebr' (HEBREW) */ NULL, /* 'hira' (HIRAGANA) */ &kndaClassTable, /* 'knda' (KANNADA) */ NULL, /* 'kata' (KATAKANA) */ NULL, /* 'khmr' (KHMER) */ NULL, /* 'laoo' (LAO) */ NULL, /* 'latn' (LATIN) */ &mlymClassTable, /* 'mlym' (MALAYALAM) */ NULL, /* 'mong' (MONGOLIAN) */ NULL, /* 'mymr' (MYANMAR) */ NULL, /* 'ogam' (OGHAM) */ NULL, /* 'ital' (OLD-ITALIC) */ &oryaClassTable, /* 'orya' (ORIYA) */ NULL, /* 'runr' (RUNIC) */ &sinhClassTable, /* 'sinh' (SINHALA) */ NULL, /* 'syrc' (SYRIAC) */ &tamlClassTable, /* 'taml' (TAMIL) */ &teluClassTable, /* 'telu' (TELUGU) */ NULL, /* 'thaa' (THAANA) */ NULL, /* 'thai' (THAI) */ NULL, /* 'tibt' (TIBETAN) */ NULL, /* 'cans' (CANADIAN-ABORIGINAL) */ NULL, /* 'yiii' (YI) */ NULL, /* 'tglg' (TAGALOG) */ NULL, /* 'hano' (HANUNOO) */ NULL, /* 'buhd' (BUHID) */ NULL, /* 'tagb' (TAGBANWA) */ NULL, /* 'brai' (BRAILLE) */ NULL, /* 'cprt' (CYPRIOT) */ NULL, /* 'limb' (LIMBU) */ NULL, /* 'linb' (LINEAR_B) */ NULL, /* 'osma' (OSMANYA) */ NULL, /* 'shaw' (SHAVIAN) */ NULL, /* 'tale' (TAI_LE) */ NULL, /* 'ugar' (UGARITIC) */ NULL, /* 'hrkt' (KATAKANA_OR_HIRAGANA) */ NULL, /* 'bugi' (BUGINESE) */ NULL, /* 'glag' (GLAGOLITIC) */ NULL, /* 'khar' (KHAROSHTHI) */ NULL, /* 'sylo' (SYLOTI_NAGRI) */ NULL, /* 'talu' (NEW_TAI_LUE) */ NULL, /* 'tfng' (TIFINAGH) */ NULL, /* 'xpeo' (OLD_PERSIAN) */ NULL, /* 'bali' (BALINESE) */ NULL, /* 'batk' (BATK) */ NULL, /* 'blis' (BLIS) */ NULL, /* 'brah' (BRAH) */ NULL, /* 'cham' (CHAM) */ NULL, /* 'cirt' (CIRT) */ NULL, /* 'cyrs' (CYRS) */ NULL, /* 'egyd' (EGYD) */ NULL, /* 'egyh' (EGYH) */ NULL, /* 'egyp' (EGYP) */ NULL, /* 'geok' (GEOK) */ NULL, /* 'hans' (HANS) */ NULL, /* 'hant' (HANT) */ NULL, /* 'hmng' (HMNG) */ NULL, /* 'hung' (HUNG) */ NULL, /* 'inds' (INDS) */ NULL, /* 'java' (JAVA) */ NULL, /* 'kali' (KALI) */ NULL, /* 'latf' (LATF) */ NULL, /* 'latg' (LATG) */ NULL, /* 'lepc' (LEPC) */ NULL, /* 'lina' (LINA) */ NULL, /* 'mand' (MAND) */ NULL, /* 'maya' (MAYA) */ NULL, /* 'mero' (MERO) */ NULL, /* 'nko ' (NKO) */ NULL, /* 'orkh' (ORKH) */ NULL, /* 'perm' (PERM) */ NULL, /* 'phag' (PHAGS_PA) */ NULL, /* 'phnx' (PHOENICIAN) */ NULL, /* 'plrd' (PLRD) */ NULL, /* 'roro' (RORO) */ NULL, /* 'sara' (SARA) */ NULL, /* 'syre' (SYRE) */ NULL, /* 'syrj' (SYRJ) */ NULL, /* 'syrn' (SYRN) */ NULL, /* 'teng' (TENG) */ NULL, /* 'vai ' (VAII) */ NULL, /* 'visp' (VISP) */ NULL, /* 'xsux' (CUNEIFORM) */ NULL, /* 'zxxx' (ZXXX) */ NULL, /* 'zzzz' (UNKNOWN) */ NULL, /* 'cari' (CARI) */ NULL, /* 'jpan' (JPAN) */ NULL, /* 'lana' (LANA) */ NULL, /* 'lyci' (LYCI) */ NULL, /* 'lydi' (LYDI) */ NULL, /* 'olck' (OLCK) */ NULL, /* 'rjng' (RJNG) */ NULL, /* 'saur' (SAUR) */ NULL, /* 'sgnw' (SGNW) */ NULL, /* 'sund' (SUND) */ NULL, /* 'moon' (MOON) */ NULL, /* 'mtei' (MTEI) */ NULL, /* 'armi' (ARMI) */ NULL, /* 'avst' (AVST) */ NULL, /* 'cakm' (CAKM) */ NULL, /* 'kore' (KORE) */ NULL, /* 'kthi' (KTHI) */ NULL, /* 'mani' (MANI) */ NULL, /* 'phli' (PHLI) */ NULL, /* 'phlp' (PHLP) */ NULL, /* 'phlv' (PHLV) */ NULL, /* 'prti' (PRTI) */ NULL, /* 'samr' (SAMR) */ NULL, /* 'tavt' (TAVT) */ NULL, /* 'zmth' (ZMTH) */ NULL, /* 'zsym' (ZSYM) */ NULL, /* 'bamu' (BAMUM) */ NULL, /* 'lisu' (LISU) */ NULL, /* 'nkgb' (NKGB) */ NULL /* 'sarb' (OLD_SOUTH_ARABIAN) */ }; IndicClassTable::CharClass IndicClassTable::getCharClass(LEUnicode ch) const { if (ch == C_SIGN_ZWJ) { return CF_CONSONANT | CC_ZERO_WIDTH_MARK; } if (ch == C_SIGN_ZWNJ) { return CC_ZERO_WIDTH_MARK; } if (ch < firstChar || ch > lastChar) { return CC_RESERVED; } return classTable[ch - firstChar]; } const IndicClassTable *IndicClassTable::getScriptClassTable(le_int32 scriptCode) { if (scriptCode < 0 || scriptCode >= scriptCodeCount) { return NULL; } return indicClassTables[scriptCode]; } le_int32 IndicReordering::getWorstCaseExpansion(le_int32 scriptCode) { const IndicClassTable *classTable = IndicClassTable::getScriptClassTable(scriptCode); if (classTable == NULL) { return 1; } return classTable->getWorstCaseExpansion(); } le_bool IndicReordering::getFilterZeroWidth(le_int32 scriptCode) { const IndicClassTable *classTable = IndicClassTable::getScriptClassTable(scriptCode); if (classTable == NULL) { return TRUE; } return classTable->getFilterZeroWidth(); } U_NAMESPACE_END
ONLYOFFICE/core
UnicodeConverter/icubuilds-mac/icu/icu/layout/IndicClassTables.cpp
C++
agpl-3.0
22,006
/** * Copyright (C) 2001-2019 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * This program is free software: you can redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the Free Software Foundation, either version 3 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License along with this program. * If not, see http://www.gnu.org/licenses/. */ package com.rapidminer.tools.expression.internal.function.text; import java.util.concurrent.Callable; import com.rapidminer.tools.Ontology; import com.rapidminer.tools.expression.DoubleCallable; import com.rapidminer.tools.expression.ExpressionEvaluator; import com.rapidminer.tools.expression.ExpressionParsingException; import com.rapidminer.tools.expression.ExpressionType; import com.rapidminer.tools.expression.FunctionDescription; import com.rapidminer.tools.expression.FunctionInputException; import com.rapidminer.tools.expression.internal.SimpleExpressionEvaluator; import com.rapidminer.tools.expression.internal.function.AbstractFunction; /** * A {@link AbstractFunction} which allow exactly one nominal value as input and has an integer as * output. * * @author Thilo Kamradt * */ public abstract class Abstract1StringInputIntegerOutputFunction extends AbstractFunction { /** * Constructs an AbstractFunction with {@link FunctionDescription} generated from the arguments * and the function name generated from the description. * * @param i18nKey * the key for the {@link FunctionDescription}. The functionName is read from * "gui.dialog.function.i18nKey.name", the helpTextName from ".help", the groupName * from ".group", the description from ".description" and the function with * parameters from ".parameters". If ".parameters" is not present, the ".name" is * taken for the function with parameters. */ public Abstract1StringInputIntegerOutputFunction(String i18n) { super(i18n, 1, Ontology.INTEGER); } @Override public ExpressionEvaluator compute(ExpressionEvaluator... inputEvaluators) { if (inputEvaluators.length != 1) { throw new FunctionInputException("expression_parser.function_wrong_input", getFunctionName(), 1, inputEvaluators.length); } ExpressionType type = getResultType(inputEvaluators); ExpressionEvaluator eEvaluator = inputEvaluators[0]; return new SimpleExpressionEvaluator(makeStringCallable(eEvaluator), type, isResultConstant(inputEvaluators)); } /** * Builds a DoubleCallable from left and right using {@link #compute(String, String)}, where * constant child results are evaluated. * * @param left * the left input * @param right * the right input * @return the resulting DoubleCallable */ protected DoubleCallable makeStringCallable(ExpressionEvaluator evaluator) { final Callable<String> funcEvaluator = evaluator.getStringFunction(); try { final String valueLeft = evaluator.isConstant() ? funcEvaluator.call() : ""; if (evaluator.isConstant()) { final double result = compute(valueLeft); return new DoubleCallable() { @Override public double call() throws Exception { return result; } }; } else { return new DoubleCallable() { @Override public double call() throws Exception { return compute(funcEvaluator.call()); } }; } } catch (ExpressionParsingException e) { throw e; } catch (Exception e) { throw new ExpressionParsingException(e); } } /** * Computes the result for one input String value. * * @param value1 * @return the result of the computation. */ protected abstract double compute(String value1); @Override protected ExpressionType computeType(ExpressionType... inputTypes) { if (inputTypes[0] == ExpressionType.STRING) { return ExpressionType.INTEGER; } else { throw new FunctionInputException("expression_parser.function_wrong_type", getFunctionName(), "nominal"); } } }
aborg0/rapidminer-studio
src/main/java/com/rapidminer/tools/expression/internal/function/text/Abstract1StringInputIntegerOutputFunction.java
Java
agpl-3.0
4,434
using ProjectManager.Database; namespace ProjectManager.Repositories { public interface IDocumentRepository : IRepository<Document> { } }
aaretali/project-manager
ProjectManager/Repositories/IDocumentRepository.cs
C#
agpl-3.0
145
<div class="container"> <div class="row"> <div class="col-sm-6"> <form class="form-horizontal" role="form" ng-submit="submit()" name="signupform"> <fieldset> <legend>{{'Login data' | l10n}}</legend> <div class="form-group" ng-class="{'has-error': signupform.username.$dirty && isBad['username']}"> <label class="col-sm-4 control-label" for="username1">{{'Username' | l10n}}</label> <div class="col-sm-6"> <input class="form-control" maxlength="15" autocomplete="off" type="text" id="username1" name="username" ng-model="user.username" ng-change="checkUsername()"/> <span class="help-block" ng-show="signupform.username.$dirty && isBad['username']">{{errorMsg['username'] | l10n}}</span> </div> </div> <div class="form-group" ng-class="{'has-error': signupform.password.$dirty && isBad['password']}"> <label class="col-sm-4 control-label" for="password1">{{'Password' | l10n}}</label> <div class="col-sm-6"> <input class="form-control" autocomplete="off" type="password" id="password1" name="password" ng-model="user.password" ng-change="checkPassword(); matchPassword()"/> <span class="help-block" ng-show="signupform.password.$dirty && isBad['password']">{{errorMsg['password'] | l10n}}</span> </div> </div> <div class="form-group" ng-class="{'has-error': signupform.password2.$dirty && isBad['password2']}"> <label class="col-sm-4 control-label" for="password2">{{'Confirm password' | l10n}}</label> <div class="col-sm-6"> <input class="form-control" autocomplete="off" type="password" id="password2" name="password2" ng-model="user.password2" ng-change="matchPassword()"/> <span class="help-block" ng-show="signupform.password2.$dirty && isBad['password2']">{{errorMsg['password2'] | l10n}}</span> </div> </div> </fieldset> <fieldset> <legend>{{'Personal data' | l10n}}</legend> <div class="form-group"> <label class="col-sm-4 control-label" for="firstname">{{'First name' | l10n}}</label> <div class="col-sm-6"> <input class="form-control" maxlength="30" autocomplete="off" type="text" id="firstname" ng-model="user.firstname"/> </div> </div> <div class="form-group"> <label class="col-sm-4 control-label" for="lastname">{{'Last name' | l10n}}</label> <div class="col-sm-6"> <input class="form-control" maxlength="30" autocomplete="off" type="text" id="lastname" ng-model="user.lastname"/> </div> </div> <div class="form-group" ng-class="{'has-error': signupform.email.$dirty && isBad['email']}"> <label class="col-sm-4 control-label" for="email1">{{'E-mail address' | l10n}}</label> <div class="col-sm-6"> <input class="form-control" autocomplete="off" type="text" id="email1" name="email" ng-model="user.email" ng-change="checkEmail(); matchEmail()"/> <span class="help-block" ng-show="signupform.email.$dirty && isBad['email']">{{errorMsg['email'] | l10n}}</span> </div> </div> <div class="form-group" ng-class="{'has-error': signupform.email2.$dirty && isBad['email2']}"> <label class="col-sm-4 control-label" for="email2">{{'Confirm e-mail' | l10n}}</label> <div class="col-sm-6"> <input class="form-control" autocomplete="off" type="text" id="email2" name="email2" ng-model="user.email2" ng-change="matchEmail()"/> <span class="help-block" ng-show="signupform.email2.$dirty && isBad['email2']">{{errorMsg['email2'] | l10n}}</span> </div> </div> </fieldset> <div class="form-group" ng-show="cm.captcha_enabled"> <label class="col-sm-4 control-label" for="email2">{{'Anti-spam check' | l10n}}</label> <div class="col-sm-6"> <div id="recaptcha-div"></div> </div> </div> <div class="form-group"> <div class="col-sm-offset-4 col-sm-8"> <button type="submit" class="btn btn-default">{{'Sign up' | l10n}}</button> </div> </div> </form> </div> <div class="col-sm-6 hidden-xs"> <legend>{{'User profile preview' | l10n}}</legend> <div class="user-preview well well-lg col-sm-offset-1 col-sm-9 col-md-offset-2 col-md-8"> <div class="avatar-wrapper"> <img src="//gravatar.com/avatar/d41d8cd98f00b204e9800998ecf8427e?d=identicon&s=200" class="avatar img-thumbnail"/> <img src="images/loader.gif" class="avatar-loader"/> </div> <h2>{{{true: user.username, false: '(username)'}[user.username.length > 0]}}</h2> <span class="nome-cognome"> {{{true: user.firstname, false: '(nome)'}[user.firstname.length > 0] | lowercase}} {{{true: user.lastname, false: '(cognome)'}[user.lastname.length > 0] | lowercase}} </span> </div> </div> </div> </div>
algorithm-ninja/cmsocial
cmsocial-web/views/signup.html
HTML
agpl-3.0
5,187
/* This file is part of the HeavenMS MapleStory Server Copyleft (L) 2016 - 2019 RonanLana This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * @author: Ronan * @event: Vs Balrog */ importPackage(Packages.server.life); var isPq = true; var minPlayers = 3, maxPlayers = 30; var minLevel = 50, maxLevel = 255; var entryMap = 105100400; var exitMap = 105100100; var recruitMap = 105100100; var clearMap = 105100401; var minMapId = 105100400; var maxMapId = 105100401; var minMobId = 8830007; var maxMobId = 8830013; var bossMobId = 8830010; var eventTime = 60; // 60 minutes var releaseClawTime = 1; var lobbyRange = [0, 0]; function init() { setEventRequirements(); } function setLobbyRange() { return lobbyRange; } function setEventRequirements() { var reqStr = ""; reqStr += "\r\n Number of players: "; if(maxPlayers - minPlayers >= 1) reqStr += minPlayers + " ~ " + maxPlayers; else reqStr += minPlayers; reqStr += "\r\n Level range: "; if(maxLevel - minLevel >= 1) reqStr += minLevel + " ~ " + maxLevel; else reqStr += minLevel; reqStr += "\r\n Time limit: "; reqStr += eventTime + " minutes"; em.setProperty("party", reqStr); } function setEventExclusives(eim) { var itemSet = []; eim.setExclusiveItems(itemSet); } function setEventRewards(eim) { var itemSet, itemQty, evLevel, expStages; evLevel = 1; //Rewards at clear PQ itemSet = []; itemQty = []; eim.setEventRewards(evLevel, itemSet, itemQty); expStages = []; //bonus exp given on CLEAR stage signal eim.setEventClearStageExp(expStages); } function getEligibleParty(party) { //selects, from the given party, the team that is allowed to attempt this event var eligible = []; var hasLeader = false; if(party.size() > 0) { var partyList = party.toArray(); for(var i = 0; i < party.size(); i++) { var ch = partyList[i]; if(ch.getMapId() == recruitMap && ch.getLevel() >= minLevel && ch.getLevel() <= maxLevel) { if(ch.isLeader()) hasLeader = true; eligible.push(ch); } } } if(!(hasLeader && eligible.length >= minPlayers && eligible.length <= maxPlayers)) eligible = []; return eligible; } function setup(level, lobbyid) { var eim = em.newInstance("Balrog" + lobbyid); eim.setProperty("level", level); eim.setProperty("boss", "0"); eim.getInstanceMap(105100400).resetPQ(level); eim.getInstanceMap(105100401).resetPQ(level); eim.schedule("releaseLeftClaw", releaseClawTime * 60000); respawnStages(eim); eim.startEventTimer(eventTime * 60000); setEventRewards(eim); setEventExclusives(eim); return eim; } function afterSetup(eim) { spawnBalrog(eim); } function respawnStages(eim) {} function releaseLeftClaw(eim) { eim.getInstanceMap(entryMap).killMonster(8830013); } function spawnBalrog(eim) { var mapObj = eim.getInstanceMap(entryMap); mapObj.spawnFakeMonsterOnGroundBelow(MapleLifeFactory.getMonster(8830007), new Packages.java.awt.Point(412, 258)); mapObj.spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8830009), new Packages.java.awt.Point(412, 258)); mapObj.spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8830013), new Packages.java.awt.Point(412, 258)); } function spawnSealedBalrog(eim) { eim.getInstanceMap(entryMap).spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(bossMobId), new Packages.java.awt.Point(412, 258)); } function playerEntry(eim, player) { var map = eim.getMapInstance(entryMap); player.changeMap(map, map.getPortal(0)); } function scheduledTimeout(eim) { end(eim); } function playerUnregistered(eim, player) {} function playerExit(eim, player) { eim.unregisterPlayer(player); player.changeMap(exitMap, 0); } function playerLeft(eim, player) { if(!eim.isEventCleared()) { playerExit(eim, player); } } function changedMap(eim, player, mapid) { if (mapid < minMapId || mapid > maxMapId) { if (eim.isExpeditionTeamLackingNow(true, minPlayers, player)) { eim.unregisterPlayer(player); end(eim); } else eim.unregisterPlayer(player); } } function changedLeader(eim, leader) {} function playerDead(eim, player) {} function playerRevive(eim, player) { // player presses ok on the death pop up. if (eim.isExpeditionTeamLackingNow(true, minPlayers, player)) { eim.unregisterPlayer(player); end(eim); } else eim.unregisterPlayer(player); } function playerDisconnected(eim, player) { if (eim.isExpeditionTeamLackingNow(true, minPlayers, player)) { eim.unregisterPlayer(player); end(eim); } else eim.unregisterPlayer(player); } function leftParty(eim, player) {} function disbandParty(eim) {} function monsterValue(eim, mobId) { return 1; } function end(eim) { var party = eim.getPlayers(); for (var i = 0; i < party.size(); i++) { playerExit(eim, party.get(i)); } eim.dispose(); } function giveRandomEventReward(eim, player) { eim.giveEventReward(player); } function clearPQ(eim) { eim.stopEventTimer(); eim.setEventCleared(); } function isUnsealedBalrog(mob) { var balrogid = mob.getId() - 8830007; return balrogid >= 0 && balrogid <= 2; } function isBalrogBody(mob) { return mob.getId() == minMobId; } function monsterKilled(mob, eim) { if(isUnsealedBalrog(mob)) { var count = eim.getIntProperty("boss"); if(count == 2) { eim.showClearEffect(); eim.clearPQ(); eim.dispatchRaiseQuestMobCount(bossMobId, entryMap); mob.getMap().broadcastBalrogVictory(eim.getLeader().getName()); } else { if(count == 1) { var mapobj = eim.getInstanceMap(entryMap); mapobj.makeMonsterReal(mapobj.getMonsterById(8830007)); } eim.setIntProperty("boss", count + 1); } if(isBalrogBody(mob)) { eim.schedule("spawnSealedBalrog", 10 * 1000); } } } function allMonstersDead(eim) {} function cancelSchedule() {} function dispose(eim) {}
ronancpl/MapleSolaxiaV2
scripts/event/BalrogBattle_Easy.js
JavaScript
agpl-3.0
7,810
package im.actor.sdk.controllers.contacts; import android.os.Bundle; import im.actor.sdk.R; import im.actor.sdk.controllers.Intents; import im.actor.sdk.controllers.activity.BaseFragmentActivity; import im.actor.sdk.controllers.group.InviteLinkFragment; public class InviteActivity extends BaseFragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getSupportActionBar().setTitle(R.string.contacts_invite_via_link); if (savedInstanceState == null) { showFragment(new InviteFragment(), false); } } }
EaglesoftZJ/actor-platform
actor-sdk/sdk-core-android/android-sdk/src/main/java/im/actor/sdk/controllers/contacts/InviteActivity.java
Java
agpl-3.0
623
<?php namespace Plenty\Modules\Catalog\Templates; use Plenty\Modules\Catalog\Contracts\CatalogRuntimeConfigProviderContract; use Plenty\Modules\Catalog\Contracts\CatalogTemplateProviderContract; use Plenty\Modules\Catalog\Contracts\TemplateContract; /** * The BaseTemplateProvider is the abstract class that should be used to implement a template provider. */ abstract class BaseTemplateProvider implements CatalogTemplateProviderContract { abstract public function getMappings( ):array; abstract public function getPreMutators( ):array; abstract public function getPostMutators( ):array; abstract public function getFilter( ):array; abstract public function getSkuCallback( ):callable; abstract public function getSettings( ):array; abstract public function getMetaInfo( ):array; abstract public function getCustomFilters( ):array; abstract public function getAssignments( ):array; }
plentymarkets/plugin-hack-api
Modules/Catalog/Templates/BaseTemplateProvider.php
PHP
agpl-3.0
917
/* * Copyright (c) 2003-2018, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md. */ @import "../mixins/_rwd.css"; .ck.ck-media-form { padding: var(--ck-spacing-standard); &:focus { outline: none; } & > :not(:first-child) { margin-left: var(--ck-spacing-standard); } @mixin ck-media-phone { padding: 0; width: calc(.8 * var(--ck-input-text-width)); & .ck-labeled-input { margin: var(--ck-spacing-standard) var(--ck-spacing-standard) 0; & .ck-input-text { min-width: 0; width: 100%; } /* Let the long error messages wrap in the narrow form. */ & .ck-labeled-input__error { white-space: normal; } } & .ck-button { padding: var(--ck-spacing-standard); margin-top: var(--ck-spacing-standard); margin-left: 0; border-radius: 0; border: 0; border-top: 1px solid var(--ck-color-base-border); &:first-of-type { border-right: 1px solid var(--ck-color-base-border); } } } }
FriendSoftwareLabs/friendup
interfaces/web_desktop/apps/Notes/Scripts/ckeditor5/@ckeditor/ckeditor5-theme-lark/theme/ckeditor5-media-embed/mediaform.css
CSS
agpl-3.0
991
<?php // created: 2015-03-21 20:26:32 ?>
shoaib-fazal16/yourown
custom/Extension/modules/Project/Ext/Vardefs/sugarfield_jjwg_maps_geocode_status_c.php
PHP
agpl-3.0
43
<!-- | TEMPLATE show form to edit profile --> <?php $Profile = $this->getVar('Profile'); ?> <div id="$$$div__showEditProfile"> <h1><?php $this->set('{SHOWEDITPROFILE__H1}'); ?></h1> <p class="ts_suplinkbox"> <a href="<?php $this->setUrl('$$$showProfile', array('$$$id' => $Profile->getInfo('id'))); ?>"> <?php $this->set('{SHOWEDITPROFILE__TOSHOWPROFILE}'); ?></a> <a href="<?php $this->setUrl('$bp$showAddTag', array('fk_obj' => $Profile->getInfo('id'), 'backlink' => base64_encode($this->setUrl('$$$showEditProfile', array('$$$id' => $Profile->getInfo('id')), false, false)))); ?>"> <?php $this->set('{SHOWEDITPROFILE__TOADDTAG}'); ?></a> </p> <p class="ts_infotext"><?php $this->set('{SHOWEDITPROFILE__INFOTEXT}'); ?></p> <?php $this->display('$$$formProfile', array( 'Profile' => $Profile, 'preset_dateofbirth' => $this->getVar('preset_dateofbirth'), 'submit_link' => '$$$updateProfile', 'submit_text' => '{SHOWEDITPROFILE__SUBMIT}', 'reset_text' => '{SHOWEDITPROFILE__CANCEL}' )); ?> </div>
nfrickler/tsunic
data/source/modules/profile/templates/showEditProfile.tpl.php
PHP
agpl-3.0
1,037
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Internet protocol requirements</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../reference.html" title="Reference"> <link rel="prev" href="HandshakeHandler.html" title="SSL handshake handler requirements"> <link rel="next" href="IoControlCommand.html" title="I/O control command requirements"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="HandshakeHandler.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="IoControlCommand.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h3 class="title"> <a name="boost_asio.reference.InternetProtocol"></a><a class="link" href="InternetProtocol.html" title="Internet protocol requirements">Internet protocol requirements</a> </h3></div></div></div> <p> An internet protocol must meet the requirements for a <a class="link" href="Protocol.html" title="Protocol requirements">protocol</a> as well as the additional requirements listed below. </p> <p> In the table below, <code class="computeroutput"><span class="identifier">X</span></code> denotes an internet protocol class, <code class="computeroutput"><span class="identifier">a</span></code> denotes a value of type <code class="computeroutput"><span class="identifier">X</span></code>, and <code class="computeroutput"><span class="identifier">b</span></code> denotes a value of type <code class="computeroutput"><span class="identifier">X</span></code>. </p> <div class="table"> <a name="boost_asio.reference.InternetProtocol.t0"></a><p class="title"><b>Table&#160;15.&#160;InternetProtocol requirements</b></p> <div class="table-contents"><table class="table" summary="InternetProtocol requirements"> <colgroup> <col> <col> <col> </colgroup> <thead><tr> <th> <p> expression </p> </th> <th> <p> return type </p> </th> <th> <p> assertion/note<br> pre/post-conditions </p> </th> </tr></thead> <tbody> <tr> <td> <p> <code class="computeroutput"><span class="identifier">X</span><span class="special">::</span><span class="identifier">resolver</span></code> </p> </td> <td> <p> <code class="computeroutput"><span class="identifier">ip</span><span class="special">::</span><span class="identifier">basic_resolver</span><span class="special">&lt;</span><span class="identifier">X</span><span class="special">&gt;</span></code> </p> </td> <td> <p> The type of a resolver for the protocol. </p> </td> </tr> <tr> <td> <p> <code class="computeroutput"><span class="identifier">X</span><span class="special">::</span><span class="identifier">v4</span><span class="special">()</span></code> </p> </td> <td> <p> <code class="computeroutput"><span class="identifier">X</span></code> </p> </td> <td> <p> Returns an object representing the IP version 4 protocol. </p> </td> </tr> <tr> <td> <p> <code class="computeroutput"><span class="identifier">X</span><span class="special">::</span><span class="identifier">v6</span><span class="special">()</span></code> </p> </td> <td> <p> <code class="computeroutput"><span class="identifier">X</span></code> </p> </td> <td> <p> Returns an object representing the IP version 6 protocol. </p> </td> </tr> <tr> <td> <p> <code class="computeroutput"><span class="identifier">a</span> <span class="special">==</span> <span class="identifier">b</span></code> </p> </td> <td> <p> convertible to <code class="computeroutput"><span class="keyword">bool</span></code> </p> </td> <td> <p> Returns whether two protocol objects are equal. </p> </td> </tr> <tr> <td> <p> <code class="computeroutput"><span class="identifier">a</span> <span class="special">!=</span> <span class="identifier">b</span></code> </p> </td> <td> <p> convertible to <code class="computeroutput"><span class="keyword">bool</span></code> </p> </td> <td> <p> Returns <code class="computeroutput"><span class="special">!(</span><span class="identifier">a</span> <span class="special">==</span> <span class="identifier">b</span><span class="special">)</span></code>. </p> </td> </tr> </tbody> </table></div> </div> <br class="table-break"> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2017 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="HandshakeHandler.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="IoControlCommand.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
cris-iisc/mpc-primitives
crislib/libscapi/lib/boost_1_64_0/doc/html/boost_asio/reference/InternetProtocol.html
HTML
agpl-3.0
7,417
require 'csv' alls = CSV.read(ARGV[0]) aps = CSV.read(ARGV[1]) #subhead = aps[0].drop(1) column_name = aps[0][1] aps = aps.drop(1) CSV.open('complete.csv', 'w') do |info| #info << alls[0].map{|x| x[2..-1]} + ['nb_ap'] info << alls[0] + [column_name] alls = alls.drop(1) alls.each do |row| res = aps.detect do |data| row[0] == data[0] end if res.nil? info << row + [""] else info << row + [res[1]] end end end
GeoffreyHecht/paprika
paprika_csv_merge_complete.rb
Ruby
agpl-3.0
435
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ import * as React from "react"; import { defaults } from "smc-util/misc"; import { alert_message } from "../alerts"; interface WindowOpts { menubar?: "yes" | "no"; toolbar?: "yes" | "no"; resizable?: "yes" | "no"; scrollbar?: "yes" | "no"; width?: string; height?: string; } export function open_popup_window(url: string, opts: WindowOpts = {}) { return open_new_tab(url, true, opts); } // open new tab and check if user allows popups. if yes, return the tab -- otherwise show an alert and return null export function open_new_tab( url: string, popup: boolean = false, opts: WindowOpts = {} ) { // if popup=true, it opens a smaller overlay window instead of a new tab (though depends on browser) let tab; opts = defaults(opts, { menubar: "yes", toolbar: "no", resizable: "yes", scrollbars: "yes", width: "800", height: "640", }); if (popup) { const x: string[] = []; for (const k in opts) { const v = opts[k]; if (v != null) { x.push(`${k}=${v}`); } } const popup_opts = x.join(","); tab = window.open("", "_blank", popup_opts); } else { tab = window.open("", "_blank"); } if (tab == null || tab.closed == null || tab.closed) { // either tab isn't even defined (or doesn't have closed attribute) -- or already closed: then popup blocked let message; if (url) { message = ( <span> Either enable popups for this website or{" "} <a href={url} target="_blank"> click here. </a> </span> ); } else { message = "Enable popups for this website and try again."; } alert_message({ title: "Popups blocked.", message, type: "info", timeout: 15, }); return null; } // equivalent to rel=noopener, i.e. neither tabs know about each other via window.opener // credits: https://stackoverflow.com/a/49276673/54236 tab.opener = null; // only *after* the above, we set the URL! tab.location = url; return tab; }
tscholl2/smc
src/smc-webapp/misc-page/open-browser-tab.tsx
TypeScript
agpl-3.0
2,205
/* * This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later. * * This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla 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 Mozilla Public License for more details. * * You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/ */ function DonorListController($scope, sharedSpace, $location, navigateBackService, Donors) { Donors.get(function (data) { $scope.donors = data.donors; }); $scope.editDonor = function (id, donationCount) { var data = {query: $scope.query}; navigateBackService.setData(data); sharedSpace.setCountOfDonations(donationCount); $location.path('edit/' + id); }; }
vimsvarcode/elmis
modules/openlmis-web/src/main/webapp/public/js/admin/equipment/donors/controller/donors-list-controller.js
JavaScript
agpl-3.0
1,333
/* * Copyright (C) 2013 headissue GmbH (www.headissue.com) * * Source repository: https://github.com/headissue/pigeon * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This patch is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this patch. If not, see <http://www.gnu.org/licenses/agpl.txt/>. */ package com.headissue.pigeon.survey; import com.google.inject.Inject; import com.google.inject.Singleton; import com.headissue.pigeon.util.JPAUtils; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.TypedQuery; @Singleton public class SurveyHandler { @Inject private EntityManagerFactory factory; public Survey findSurveyById(int _surveyId) { EntityManager _manager = factory.createEntityManager(); try { Survey s = _manager.find(Survey.class, _surveyId); if (s == null || s.getStatus() == SurveyStatus.DISABLED) { return null; } return s; } catch (Exception e) { throw new SurveyException("survey '" + _surveyId + "' is unknown"); } finally { _manager.close(); } } public Survey findSurveyByKey(String _surveyKey) { EntityManager _manager = factory.createEntityManager(); try { TypedQuery<Survey> q = _manager.createNamedQuery("survey.findSurveyByKey", Survey.class); q.setParameter("surveyKey", _surveyKey); Survey s = JPAUtils.getSingleResult(q); if (s == null || s.getStatus() == SurveyStatus.DISABLED) { return null; } return s; } catch (Exception e) { throw new SurveyException("survey '" + _surveyKey + "' is unknown"); } finally { _manager.close(); } } }
headissue/pigeon
src/main/java/com/headissue/pigeon/survey/SurveyHandler.java
Java
agpl-3.0
2,183
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_07) on Mon Dec 27 18:35:30 CET 2010 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.fosstrak.webadapters.epcis.ws.generated.ValidationException (epcis-webadapter 0.1.0 API) </TITLE> <META NAME="date" CONTENT="2010-12-27"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.fosstrak.webadapters.epcis.ws.generated.ValidationException (epcis-webadapter 0.1.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/fosstrak/webadapters/epcis/ws/generated/\class-useValidationException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ValidationException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.fosstrak.webadapters.epcis.ws.generated.ValidationException</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.fosstrak.webadapters.epcis.ws.generated"><B>org.fosstrak.webadapters.epcis.ws.generated</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.fosstrak.webadapters.epcis.ws.generated"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A> in <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/package-summary.html">org.fosstrak.webadapters.epcis.ws.generated</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/package-summary.html">org.fosstrak.webadapters.epcis.ws.generated</A> declared as <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>protected &nbsp;<A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A></CODE></FONT></TD> <TD><CODE><B>EPCISQueryBodyType.</B><B><A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/EPCISQueryBodyType.html#validationException">validationException</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/package-summary.html">org.fosstrak.webadapters.epcis.ws.generated</A> that return <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A></CODE></FONT></TD> <TD><CODE><B>ObjectFactory.</B><B><A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ObjectFactory.html#createValidationException()">createValidationException</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Create an instance of <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated"><CODE>ValidationException</CODE></A></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A></CODE></FONT></TD> <TD><CODE><B>ValidationExceptionResponse.</B><B><A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationExceptionResponse.html#getFaultInfo()">getFaultInfo</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A></CODE></FONT></TD> <TD><CODE><B>EPCISQueryBodyType.</B><B><A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/EPCISQueryBodyType.html#getValidationException()">getValidationException</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Gets the value of the validationException property.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/package-summary.html">org.fosstrak.webadapters.epcis.ws.generated</A> that return types with arguments of type <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/javase/6/docs/api/javax/xml/bind/JAXBElement.html?is-external=true" title="class or interface in javax.xml.bind">JAXBElement</A>&lt;<A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A>&gt;</CODE></FONT></TD> <TD><CODE><B>ObjectFactory.</B><B><A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ObjectFactory.html#createValidationException(org.fosstrak.webadapters.epcis.ws.generated.ValidationException)">createValidationException</A></B>(<A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A>&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Create an instance of <A HREF="http://java.sun.com/javase/6/docs/api/javax/xml/bind/JAXBElement.html?is-external=true" title="class or interface in javax.xml.bind"><CODE>JAXBElement</CODE></A><code>&lt;</code><A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated"><CODE>ValidationException</CODE></A><code>&gt;</code>}</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/package-summary.html">org.fosstrak.webadapters.epcis.ws.generated</A> with parameters of type <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="http://java.sun.com/javase/6/docs/api/javax/xml/bind/JAXBElement.html?is-external=true" title="class or interface in javax.xml.bind">JAXBElement</A>&lt;<A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A>&gt;</CODE></FONT></TD> <TD><CODE><B>ObjectFactory.</B><B><A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ObjectFactory.html#createValidationException(org.fosstrak.webadapters.epcis.ws.generated.ValidationException)">createValidationException</A></B>(<A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A>&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Create an instance of <A HREF="http://java.sun.com/javase/6/docs/api/javax/xml/bind/JAXBElement.html?is-external=true" title="class or interface in javax.xml.bind"><CODE>JAXBElement</CODE></A><code>&lt;</code><A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated"><CODE>ValidationException</CODE></A><code>&gt;</code>}</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>EPCISQueryBodyType.</B><B><A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/EPCISQueryBodyType.html#setValidationException(org.fosstrak.webadapters.epcis.ws.generated.ValidationException)">setValidationException</A></B>(<A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A>&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Sets the value of the validationException property.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Constructors in <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/package-summary.html">org.fosstrak.webadapters.epcis.ws.generated</A> with parameters of type <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationExceptionResponse.html#ValidationExceptionResponse(java.lang.String, org.fosstrak.webadapters.epcis.ws.generated.ValidationException)">ValidationExceptionResponse</A></B>(<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;message, <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A>&nbsp;faultInfo)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><CODE><B><A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationExceptionResponse.html#ValidationExceptionResponse(java.lang.String, org.fosstrak.webadapters.epcis.ws.generated.ValidationException, java.lang.Throwable)">ValidationExceptionResponse</A></B>(<A HREF="http://java.sun.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</A>&nbsp;message, <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated">ValidationException</A>&nbsp;faultInfo, <A HREF="http://java.sun.com/javase/6/docs/api/java/lang/Throwable.html?is-external=true" title="class or interface in java.lang">Throwable</A>&nbsp;cause)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../org/fosstrak/webadapters/epcis/ws/generated/ValidationException.html" title="class in org.fosstrak.webadapters.epcis.ws.generated"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../../index.html?org/fosstrak/webadapters/epcis/ws/generated/\class-useValidationException.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ValidationException.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 2010. All Rights Reserved. </BODY> </HTML>
Fosstrak/fosstrak.github.io
webadapters/apidocs/org/fosstrak/webadapters/epcis/ws/generated/class-use/ValidationException.html
HTML
lgpl-2.1
18,685
package com.auri.ironam.Items; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import com.auri.ironam.ironam; /** * Created by 1800855 on 10/17/16. */ public class ItemBase extends Item { protected String name; public ItemBase (String name) { this.name = name; setUnlocalizedName(name); setRegistryName(name); } public void registerItemModel() { ironam.proxy.registerItemRenderer(this, 0, name); } @Override public ItemBase setCreativeTab(CreativeTabs tab) { super.setCreativeTab(tab); return this; } }
Swiftshadow/Ironam
src/main/java/com/auri/ironam/Items/ItemBase.java
Java
lgpl-2.1
635
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- customwidgetplugin.qdoc --> <title>Qt 4.8: Custom Widget Plugin Example</title> <link rel="stylesheet" type="text/css" href="style/style.css" /> <script src="scripts/jquery.js" type="text/javascript"></script> <script src="scripts/functions.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="style/superfish.css" /> <link rel="stylesheet" type="text/css" href="style/narrow.css" /> <!--[if IE]> <meta name="MSSmartTagsPreventParsing" content="true"> <meta http-equiv="imagetoolbar" content="no"> <![endif]--> <!--[if lt IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie6.css"> <![endif]--> <!--[if IE 7]> <link rel="stylesheet" type="text/css" href="style/style_ie7.css"> <![endif]--> <!--[if IE 8]> <link rel="stylesheet" type="text/css" href="style/style_ie8.css"> <![endif]--> <script src="scripts/superfish.js" type="text/javascript"></script> <script src="scripts/narrow.js" type="text/javascript"></script> </head> <body class="" onload="CheckEmptyAndLoadList();"> <div class="header" id="qtdocheader"> <div class="content"> <div id="nav-logo"> <a href="index.html">Home</a></div> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> <div id="narrowsearch"></div> <div id="nav-topright"> <ul> <li class="nav-topright-home"><a href="http://qt.digia.com/">Qt HOME</a></li> <li class="nav-topright-dev"><a href="http://qt-project.org/">DEV</a></li> <li class="nav-topright-doc nav-topright-doc-active"><a href="http://qt-project.org/doc/"> DOC</a></li> <li class="nav-topright-blog"><a href="http://blog.qt.digia.com/">BLOG</a></li> </ul> </div> <div id="shortCut"> <ul> <li class="shortCut-topleft-inactive"><span><a href="index.html">Qt 4.8</a></span></li> <li class="shortCut-topleft-active"><a href="http://qt-project.org/doc/">ALL VERSIONS </a></li> </ul> </div> <ul class="sf-menu" id="narrowmenu"> <li><a href="#">API Lookup</a> <ul> <li><a href="classes.html">Class index</a></li> <li><a href="functions.html">Function index</a></li> <li><a href="modules.html">Modules</a></li> <li><a href="namespaces.html">Namespaces</a></li> <li><a href="qtglobal.html">Global Declarations</a></li> <li><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </li> <li><a href="#">Qt Topics</a> <ul> <li><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li><a href="supported-platforms.html">Supported Platforms</a></li> <li><a href="technology-apis.html">Qt and Key Technologies</a></li> <li><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </li> <li><a href="#">Examples</a> <ul> <li><a href="all-examples.html">Examples</a></li> <li><a href="tutorials.html">Tutorials</a></li> <li><a href="demos.html">Demos</a></li> <li><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </li> </ul> </div> </div> <div class="wrapper"> <div class="hd"> <span></span> </div> <div class="bd group"> <div class="sidebar"> <div class="searchlabel"> Search index:</div> <div class="search" id="sidebarsearch"> <form id="qtdocsearch" action="" onsubmit="return false;"> <fieldset> <input type="text" name="searchstring" id="pageType" value="" /> <div id="resultdialog"> <a href="#" id="resultclose">Close</a> <p id="resultlinks" class="all"><a href="#" id="showallresults">All</a> | <a href="#" id="showapiresults">API</a> | <a href="#" id="showarticleresults">Articles</a> | <a href="#" id="showexampleresults">Examples</a></p> <p id="searchcount" class="all"><span id="resultcount"></span><span id="apicount"></span><span id="articlecount"></span><span id="examplecount"></span>&nbsp;results:</p> <ul id="resultlist" class="all"> </ul> </div> </fieldset> </form> </div> <div class="box first bottombar" id="lookup"> <h2 title="API Lookup"><span></span> API Lookup</h2> <div id="list001" class="list"> <ul id="ul001" > <li class="defaultLink"><a href="classes.html">Class index</a></li> <li class="defaultLink"><a href="functions.html">Function index</a></li> <li class="defaultLink"><a href="modules.html">Modules</a></li> <li class="defaultLink"><a href="namespaces.html">Namespaces</a></li> <li class="defaultLink"><a href="qtglobal.html">Global Declarations</a></li> <li class="defaultLink"><a href="qdeclarativeelements.html">QML elements</a></li> </ul> </div> </div> <div class="box bottombar" id="topics"> <h2 title="Qt Topics"><span></span> Qt Topics</h2> <div id="list002" class="list"> <ul id="ul002" > <li class="defaultLink"><a href="qt-basic-concepts.html">Programming with Qt</a></li> <li class="defaultLink"><a href="qtquick.html">Device UIs &amp; Qt Quick</a></li> <li class="defaultLink"><a href="qt-gui-concepts.html">UI Design with Qt</a></li> <li class="defaultLink"><a href="supported-platforms.html">Supported Platforms</a></li> <li class="defaultLink"><a href="technology-apis.html">Qt and Key Technologies</a></li> <li class="defaultLink"><a href="best-practices.html">How-To's and Best Practices</a></li> </ul> </div> </div> <div class="box" id="examples"> <h2 title="Examples"><span></span> Examples</h2> <div id="list003" class="list"> <ul id="ul003"> <li class="defaultLink"><a href="all-examples.html">Examples</a></li> <li class="defaultLink"><a href="tutorials.html">Tutorials</a></li> <li class="defaultLink"><a href="demos.html">Demos</a></li> <li class="defaultLink"><a href="qdeclarativeexamples.html">QML Examples</a></li> </ul> </div> </div> </div> <div class="wrap"> <div class="toolbar"> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> <li><a href="all-examples.html">Examples</a></li> <li>Custom Widget Plugin Example</li> </ul> </div> <div class="toolbuttons toolblock"> <ul> <li id="smallA" class="t_button">A</li> <li id="medA" class="t_button active">A</li> <li id="bigA" class="t_button">A</li> <li id="print" class="t_button"><a href="javascript:this.print();"> <span>Print</span></a></li> </ul> </div> </div> <div class="content mainContent"> <div class="toc"> <h3><a name="toc">Contents</a></h3> <ul> <li class="level1"><a href="#preparation">Preparation</a></li> <li class="level1"><a href="#analogclock-class-definition-and-implementation">AnalogClock Class Definition and Implementation</a></li> <li class="level1"><a href="#analogclockplugin-class-definition">AnalogClockPlugin Class Definition</a></li> <li class="level1"><a href="#analogclockplugin-implementation">AnalogClockPlugin Implementation</a></li> </ul> </div> <h1 class="title">Custom Widget Plugin Example</h1> <span class="subtitle"></span> <!-- $$$designer/customwidgetplugin-description --> <div class="descr"> <a name="details"></a> <p>Files:</p> <ul> <li><a href="designer-customwidgetplugin-analogclock-cpp.html">designer/customwidgetplugin/analogclock.cpp</a></li> <li><a href="designer-customwidgetplugin-analogclock-h.html">designer/customwidgetplugin/analogclock.h</a></li> <li><a href="designer-customwidgetplugin-customwidgetplugin-cpp.html">designer/customwidgetplugin/customwidgetplugin.cpp</a></li> <li><a href="designer-customwidgetplugin-customwidgetplugin-h.html">designer/customwidgetplugin/customwidgetplugin.h</a></li> <li><a href="designer-customwidgetplugin-customwidgetplugin-pro.html">designer/customwidgetplugin/customwidgetplugin.pro</a></li> </ul> <p>The Custom Widget example shows how to create a custom widget plugin for <i>Qt Designer</i>.<p class="centerAlign"><img src="images/customwidgetplugin-example.png" alt="" /></p><p>In this example, the custom widget used is based on the <a href="widgets-analogclock.html">Analog Clock example</a>, and does not provide any custom signals or slots.</p> <a name="preparation"></a> <h2>Preparation</h2> <p>To provide a custom widget that can be used with <i>Qt Designer</i>, we need to supply a self-contained implementation and provide a plugin interface. In this example, we reuse the <a href="widgets-analogclock.html">Analog Clock example</a> for convenience.</p> <p>Since custom widgets plugins rely on components supplied with <i>Qt Designer</i>, the project file that we use needs to contain information about <i>Qt Designer</i>'s library components:</p> <pre class="cpp"> TEMPLATE = lib CONFIG += designer plugin</pre> <p>The <tt>TEMPLATE</tt> variable's value makes <tt>qmake</tt> create the custom widget as a library. Later, we will ensure that the widget will be recognized as a plugin by Qt by using the <a href="qtplugin.html#Q_EXPORT_PLUGIN2">Q_EXPORT_PLUGIN2</a>() macro to export the relevant widget information.</p> <p>The <tt>CONFIG</tt> variable contains two values, <tt>designer</tt> and <tt>plugin</tt>:</p> <ul> <li><tt>designer</tt>: Since custom widgets plugins rely on components supplied with <i>Qt Designer</i>, this value ensures that our plugin links against <i>Qt Designer</i>'s library (<tt>libQtDesigner.so</tt>).</li> <li><tt>plugin</tt>: We also need to ensure that <tt>qmake</tt> considers the custom widget a plugin library.</li> </ul> <p>When Qt is configured to build in both debug and release modes, <i>Qt Designer</i> will be built in release mode. When this occurs, it is necessary to ensure that plugins are also built in release mode. For that reason we add the <tt>debug_and_release</tt> value to the <tt>CONFIG</tt> variable. Otherwise, if a plugin is built in a mode that is incompatible with <i>Qt Designer</i>, it won't be loaded and installed.</p> <p>The header and source files for the widget are declared in the usual way, and we provide an implementation of the plugin interface so that <i>Qt Designer</i> can use the custom widget:</p> <pre class="cpp"> HEADERS = analogclock.h \ customwidgetplugin.h SOURCES = analogclock.cpp \ customwidgetplugin.cpp</pre> <p>It is also important to ensure that the plugin is installed in a location that is searched by <i>Qt Designer</i>. We do this by specifying a target path for the project and adding it to the list of items to install:</p> <pre class="cpp"> target.path = $$[QT_INSTALL_PLUGINS]/designer INSTALLS += target</pre> <p>The custom widget is created as a library, and will be installed alongside the other <i>Qt Designer</i> plugins when the project is installed (using <tt>make install</tt> or an equivalent installation procedure). Later, we will ensure that it is recognized as a plugin by <i>Qt Designer</i> by using the <a href="qtplugin.html#Q_EXPORT_PLUGIN2">Q_EXPORT_PLUGIN2</a>() macro to export the relevant widget information.</p> <p>Note that if you want the plugins to appear in a Visual Studio integration, the plugins must be built in release mode and their libraries must be copied into the plugin directory in the install path of the integration (for an example, see <tt>C:/program files/trolltech as/visual studio integration/plugins</tt>).</p> <p>For more information about plugins, see the <a href="plugins-howto.html">How to Create Qt Plugins</a> documentation.</p> <a name="analogclock-class-definition-and-implementation"></a> <h2>AnalogClock Class Definition and Implementation</h2> <p>The <tt>AnalogClock</tt> class is defined and implemented in exactly the same way as described in the <a href="widgets-analogclock.html">Analog Clock example</a>. Since the class is self-contained, and does not require any external configuration, it can be used without modification as a custom widget in <i>Qt Designer</i>.</p> <a name="analogclockplugin-class-definition"></a> <h2>AnalogClockPlugin Class Definition</h2> <p>The <tt>AnalogClock</tt> class is exposed to <i>Qt Designer</i> through the <tt>AnalogClockPlugin</tt> class. This class inherits from both <a href="qobject.html">QObject</a> and the <a href="qdesignercustomwidgetinterface.html">QDesignerCustomWidgetInterface</a> class, and implements an interface defined by <a href="qdesignercustomwidgetinterface.html">QDesignerCustomWidgetInterface</a>:</p> <pre class="cpp"> <span class="keyword">class</span> AnalogClockPlugin : <span class="keyword">public</span> <span class="type"><a href="qobject.html">QObject</a></span><span class="operator">,</span> <span class="keyword">public</span> <span class="type"><a href="qdesignercustomwidgetinterface.html">QDesignerCustomWidgetInterface</a></span> { Q_OBJECT Q_INTERFACES(<span class="type"><a href="qdesignercustomwidgetinterface.html">QDesignerCustomWidgetInterface</a></span>) <span class="keyword">public</span>: AnalogClockPlugin(<span class="type"><a href="qobject.html">QObject</a></span> <span class="operator">*</span>parent <span class="operator">=</span> <span class="number">0</span>); <span class="type">bool</span> isContainer() <span class="keyword">const</span>; <span class="type">bool</span> isInitialized() <span class="keyword">const</span>; <span class="type"><a href="qicon.html">QIcon</a></span> icon() <span class="keyword">const</span>; <span class="type"><a href="qstring.html">QString</a></span> domXml() <span class="keyword">const</span>; <span class="type"><a href="qstring.html">QString</a></span> group() <span class="keyword">const</span>; <span class="type"><a href="qstring.html">QString</a></span> includeFile() <span class="keyword">const</span>; <span class="type"><a href="qstring.html">QString</a></span> name() <span class="keyword">const</span>; <span class="type"><a href="qstring.html">QString</a></span> toolTip() <span class="keyword">const</span>; <span class="type"><a href="qstring.html">QString</a></span> whatsThis() <span class="keyword">const</span>; <span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>createWidget(<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent); <span class="type">void</span> initialize(<span class="type"><a href="qdesignerformeditorinterface.html">QDesignerFormEditorInterface</a></span> <span class="operator">*</span>core); <span class="keyword">private</span>: <span class="type">bool</span> initialized; };</pre> <p>The functions provide information about the widget that <i>Qt Designer</i> can use in the <a href="designer-to-know.html#widgetbox">widget box</a>. The <tt>initialized</tt> private member variable is used to record whether the plugin has been initialized by <i>Qt Designer</i>.</p> <p>Note that the only part of the class definition that is specific to this particular custom widget is the class name.</p> <a name="analogclockplugin-implementation"></a> <h2>AnalogClockPlugin Implementation</h2> <p>The class constructor simply calls the <a href="qobject.html">QObject</a> base class constructor and sets the <tt>initialized</tt> variable to <tt>false</tt>.</p> <pre class="cpp"> AnalogClockPlugin<span class="operator">::</span>AnalogClockPlugin(<span class="type"><a href="qobject.html">QObject</a></span> <span class="operator">*</span>parent) : <span class="type"><a href="qobject.html">QObject</a></span>(parent) { initialized <span class="operator">=</span> <span class="keyword">false</span>; }</pre> <p><i>Qt Designer</i> will initialize the plugin when it is required by calling the <tt>initialize()</tt> function:</p> <pre class="cpp"> <span class="type">void</span> AnalogClockPlugin<span class="operator">::</span>initialize(<span class="type"><a href="qdesignerformeditorinterface.html">QDesignerFormEditorInterface</a></span> <span class="operator">*</span> <span class="comment">/* core */</span>) { <span class="keyword">if</span> (initialized) <span class="keyword">return</span>; initialized <span class="operator">=</span> <span class="keyword">true</span>; }</pre> <p>In this example, the <tt>initialized</tt> private variable is tested, and only set to <tt>true</tt> if the plugin is not already initialized. Although, this plugin does not require any special code to be executed when it is initialized, we could include such code after the test for initialization.</p> <p>The <tt>isInitialized()</tt> function lets <i>Qt Designer</i> know whether the plugin is ready for use:</p> <pre class="cpp"> <span class="type">bool</span> AnalogClockPlugin<span class="operator">::</span>isInitialized() <span class="keyword">const</span> { <span class="keyword">return</span> initialized; }</pre> <p>Instances of the custom widget are supplied by the <tt>createWidget()</tt> function. The implementation for the analog clock is straightforward:</p> <pre class="cpp"> <span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>AnalogClockPlugin<span class="operator">::</span>createWidget(<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent) { <span class="keyword">return</span> <span class="keyword">new</span> AnalogClock(parent); }</pre> <p>In this case, the custom widget only requires a <tt>parent</tt> to be specified. If other arguments need to be supplied to the widget, they can be introduced here.</p> <p>The following functions provide information for <i>Qt Designer</i> to use to represent the widget in the widget box. The <tt>name()</tt> function returns the name of class that provides the custom widget:</p> <pre class="cpp"> <span class="type"><a href="qstring.html">QString</a></span> AnalogClockPlugin<span class="operator">::</span>name() <span class="keyword">const</span> { <span class="keyword">return</span> <span class="string">&quot;AnalogClock&quot;</span>; }</pre> <p>The <tt>group()</tt> function is used to describe the type of widget that the custom widget belongs to:</p> <pre class="cpp"> <span class="type"><a href="qstring.html">QString</a></span> AnalogClockPlugin<span class="operator">::</span>group() <span class="keyword">const</span> { <span class="keyword">return</span> <span class="string">&quot;Display Widgets [Examples]&quot;</span>; }</pre> <p>The widget plugin will be placed in a section identified by its group name in <i>Qt Designer</i>'s widget box. The icon used to represent the widget in the widget box is returned by the <tt>icon()</tt> function:</p> <pre class="cpp"> <span class="type"><a href="qicon.html">QIcon</a></span> AnalogClockPlugin<span class="operator">::</span>icon() <span class="keyword">const</span> { <span class="keyword">return</span> <span class="type"><a href="qicon.html">QIcon</a></span>(); }</pre> <p>In this case, we return a null icon to indicate that we have no icon that can be used to represent the widget.</p> <p>A tool tip and &quot;What's This?&quot; help can be supplied for the custom widget's entry in the widget box. The <tt>toolTip()</tt> function should return a short message describing the widget:</p> <pre class="cpp"> <span class="type"><a href="qstring.html">QString</a></span> AnalogClockPlugin<span class="operator">::</span>toolTip() <span class="keyword">const</span> { <span class="keyword">return</span> <span class="string">&quot;&quot;</span>; }</pre> <p>The <tt>whatsThis()</tt> function can return a longer description:</p> <pre class="cpp"> <span class="type"><a href="qstring.html">QString</a></span> AnalogClockPlugin<span class="operator">::</span>whatsThis() <span class="keyword">const</span> { <span class="keyword">return</span> <span class="string">&quot;&quot;</span>; }</pre> <p>The <tt>isContainer()</tt> function tells <i>Qt Designer</i> whether the widget is supposed to be used as a container for other widgets. If not, <i>Qt Designer</i> will not allow the user to place widgets inside it.</p> <pre class="cpp"> <span class="type">bool</span> AnalogClockPlugin<span class="operator">::</span>isContainer() <span class="keyword">const</span> { <span class="keyword">return</span> <span class="keyword">false</span>; }</pre> <p>Most widgets in Qt can contain child widgets, but it only makes sense to use dedicated container widgets for this purpose in <i>Qt Designer</i>. By returning <tt>false</tt>, we indicate that the custom widget cannot hold other widgets; if we returned true, <i>Qt Designer</i> would allow other widgets to be placed inside the analog clock and a layout to be defined.</p> <p>The <tt>domXml()</tt> function provides a way to include default settings for the widget in the standard XML format used by <i>Qt Designer</i>. In this case, we only specify the widget's geometry:</p> <pre class="cpp"> <span class="type"><a href="qstring.html">QString</a></span> AnalogClockPlugin<span class="operator">::</span>domXml() <span class="keyword">const</span> { <span class="keyword">return</span> <span class="string">&quot;&lt;ui language=\&quot;c++\&quot;&gt;\n&quot;</span> <span class="string">&quot; &lt;widget class=\&quot;AnalogClock\&quot; name=\&quot;analogClock\&quot;&gt;\n&quot;</span> <span class="string">&quot; &lt;property name=\&quot;geometry\&quot;&gt;\n&quot;</span> <span class="string">&quot; &lt;rect&gt;\n&quot;</span> <span class="string">&quot; &lt;x&gt;0&lt;/x&gt;\n&quot;</span> <span class="string">&quot; &lt;y&gt;0&lt;/y&gt;\n&quot;</span> <span class="string">&quot; &lt;width&gt;100&lt;/width&gt;\n&quot;</span> <span class="string">&quot; &lt;height&gt;100&lt;/height&gt;\n&quot;</span> <span class="string">&quot; &lt;/rect&gt;\n&quot;</span> <span class="string">&quot; &lt;/property&gt;\n&quot;</span> <span class="string">&quot; &lt;property name=\&quot;toolTip\&quot; &gt;\n&quot;</span> <span class="string">&quot; &lt;string&gt;The current time&lt;/string&gt;\n&quot;</span> <span class="string">&quot; &lt;/property&gt;\n&quot;</span> <span class="string">&quot; &lt;property name=\&quot;whatsThis\&quot; &gt;\n&quot;</span> <span class="string">&quot; &lt;string&gt;The analog clock widget displays the current time.&lt;/string&gt;\n&quot;</span> <span class="string">&quot; &lt;/property&gt;\n&quot;</span> <span class="string">&quot; &lt;/widget&gt;\n&quot;</span> <span class="string">&quot;&lt;/ui&gt;\n&quot;</span>; }</pre> <p>If the widget provides a reasonable size hint, it is not necessary to define it here. In addition, returning an empty string instead of a <tt>&lt;widget&gt;</tt> element will tell <i>Qt Designer</i> not to install the widget in the widget box.</p> <p>To make the analog clock widget usable by applications, we implement the <tt>includeFile()</tt> function to return the name of the header file containing the custom widget class definition:</p> <pre class="cpp"> <span class="type"><a href="qstring.html">QString</a></span> AnalogClockPlugin<span class="operator">::</span>includeFile() <span class="keyword">const</span> { <span class="keyword">return</span> <span class="string">&quot;analogclock.h&quot;</span>; }</pre> <p>Finally, we use the <a href="qtplugin.html#Q_EXPORT_PLUGIN2">Q_EXPORT_PLUGIN2</a>() macro to export the <tt>AnalogClockPlugin</tt> class for use with <i>Qt Designer</i>:</p> <pre class="cpp"> <a href="qtplugin.html#Q_EXPORT_PLUGIN2">Q_EXPORT_PLUGIN2</a>(customwidgetplugin<span class="operator">,</span> AnalogClockPlugin)</pre> <p>This macro ensures that <i>Qt Designer</i> can access and construct the custom widget. Without this macro, there is no way for <i>Qt Designer</i> to use the widget.</p> <p>It is important to note that you can only use the <a href="qtplugin.html#Q_EXPORT_PLUGIN2">Q_EXPORT_PLUGIN2</a>() macro once in any implementation. If you have several custom widgets in an implementation that you wish to make available to <i>Qt Designer</i>, you will need to implement <a href="qdesignercustomwidgetcollectioninterface.html">QDesignerCustomWidgetCollectionInterface</a>.</p> </div> <!-- @@@designer/customwidgetplugin --> </div> </div> </div> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2012 Digia Plc and/or its subsidiaries. Documentation contributions included herein are the copyrights of their respective owners.</p> <br /> <p> The documentation provided herein is licensed under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> <p> Documentation sources may be obtained from <a href="http://www.qt-project.org"> www.qt-project.org</a>.</p> <br /> <p> Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide. All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://en.gitorious.org/privacy_policy/">Privacy Policy</a></p> </div> <script src="scripts/functions.js" type="text/javascript"></script> </body> </html>
sicily/qt4.8.4
doc/html/designer-customwidgetplugin.html
HTML
lgpl-2.1
26,929
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "propertymetainfo.h" #include <QSharedData> #include "invalidmetainfoexception.h" #include "metainfo.h" #include "modelnode.h" #include <private/qdeclarativevaluetype_p.h> #include <private/qdeclarativestringconverters_p.h> namespace QmlDesigner { namespace Internal { class PropertyMetaInfoData : public QSharedData { public: PropertyMetaInfoData() : QSharedData(), isValid(false), readable(false), writeable(false), resettable(false), enumType(false), flagType(false), isVisible(false) {} EnumeratorMetaInfo enumerator; QString name; QString type; bool isValid; bool readable; bool writeable; bool resettable; bool enumType; bool flagType; bool isVisible; QHash<QString, QVariant> defaultValueHash; }; } /*! \class QmlDesigner::PropertyMetaInfo \ingroup CoreModel \brief The PropertyMetaInfo class provides meta information about a qml type property. A PropertyMetaInfo object can be NodeMetaInfo, or AbstractProperty::metaInfo. The object can be invalid - you can check this by calling isValid(). The object is invalid if you ask for meta information for an non-existing qml type. Also the node meta info can become invalid if the type is deregistered from the meta type system (e.g. a sub component qml file is deleted). Trying to call any accessor methods on an invalid PropertyMetaInfo object will result in an InvalidMetaInfoException being thrown. \see QmlDesigner::MetaInfo, QmlDesigner::NodeMetaInfo, QmlDesigner::EnumeratorMetaInfo */ PropertyMetaInfo::PropertyMetaInfo() : m_data(new Internal::PropertyMetaInfoData) { } PropertyMetaInfo::~PropertyMetaInfo() { } /*! \brief Creates a copy of the handle. */ PropertyMetaInfo::PropertyMetaInfo(const PropertyMetaInfo &other) : m_data(other.m_data) { } /*! \brief Copies the handle. */ PropertyMetaInfo &PropertyMetaInfo::operator=(const PropertyMetaInfo &other) { if (this != &other) m_data = other.m_data; return *this; } /*! \brief Returns whether the meta information system knows about this property. */ bool PropertyMetaInfo::isValid() const { return m_data->isValid; } /*! \brief Returns the name of the property. */ QString PropertyMetaInfo::name() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } return m_data->name; } /*! \brief Returns the type name of the property. */ QString PropertyMetaInfo::type() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } return m_data->type; } bool PropertyMetaInfo::isVisibleToPropertyEditor() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } return m_data->isVisible; } void PropertyMetaInfo::setIsVisibleToPropertyEditor(bool isVisible) { m_data->isVisible = isVisible; } /*! \brief Returns the QVariant type of the property. */ QVariant::Type PropertyMetaInfo::variantTypeId() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } Q_ASSERT(!m_data->type.isEmpty()); if (m_data->type == "string") return QVariant::String; if (m_data->type == "color") return QVariant::Color; if (m_data->type == "int") return QVariant::Int; if (m_data->type == "url") return QVariant::Url; if (m_data->type == "real") return QVariant::Double; if (m_data->type == "bool") return QVariant::Bool; if (m_data->type == "date") return QVariant::Date; if (m_data->type == "alias") return QVariant::UserType; if (m_data->type == "var") return QVariant::UserType; return QVariant::nameToType(m_data->type.toLatin1().data()); } /*! \brief Returns whether the propery is readable. */ bool PropertyMetaInfo::isReadable() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } return m_data->readable; } /*! \brief Returns whether the propery is writeable. */ bool PropertyMetaInfo::isWriteable() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } return m_data->writeable; } /*! \brief Returns whether the propery is resettable. */ bool PropertyMetaInfo::isResettable() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } return m_data->resettable; } /*! \brief Returns whether the propery is complex value type. */ bool PropertyMetaInfo::isValueType() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } QDeclarativeValueType *valueType(QDeclarativeValueTypeFactory::valueType(variantTypeId())); return valueType; } /*! \brief Returns whether the propery is a QDeclarativeList. */ bool PropertyMetaInfo::isListProperty() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } return type().contains("QDeclarativeList"); } /*! \brief Returns whether the propery has sub properties with "." syntax e.g. font */ bool PropertyMetaInfo::hasDotSubProperties() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } return isValueType() || !isWriteable(); } /*! \brief Returns whether the propery stores an enum value. */ bool PropertyMetaInfo::isEnumType() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } return m_data->enumType; } /*! \brief Returns whether the propery stores a flag value. */ bool PropertyMetaInfo::isFlagType() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } return m_data->flagType; } /*! \brief Returns a default value if there is one specified, an invalid QVariant otherwise. */ QVariant PropertyMetaInfo::defaultValue(const NodeMetaInfo &nodeMetaInfoArg) const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } QList<NodeMetaInfo> nodeMetaInfoList(nodeMetaInfoArg.superClasses()); nodeMetaInfoList.prepend(nodeMetaInfoArg); foreach (const NodeMetaInfo &nodeMetaInfo, nodeMetaInfoList) { if (m_data->defaultValueHash.contains(nodeMetaInfo.typeName())) return m_data->defaultValueHash.value(nodeMetaInfo.typeName()); } return QVariant(); } void PropertyMetaInfo::setName(const QString &name) { m_data->name = name; } void PropertyMetaInfo::setType(const QString &type) { m_data->type = type; } void PropertyMetaInfo::setValid(bool isValid) { m_data->isValid = isValid; } void PropertyMetaInfo::setReadable(bool isReadable) { m_data->readable = isReadable; } void PropertyMetaInfo::setWritable(bool isWritable) { m_data->writeable = isWritable; } void PropertyMetaInfo::setResettable(bool isRessetable) { m_data->resettable = isRessetable; } void PropertyMetaInfo::setEnumType(bool isEnumType) { m_data->enumType = isEnumType; } void PropertyMetaInfo::setFlagType(bool isFlagType) { m_data->flagType = isFlagType; } void PropertyMetaInfo::setDefaultValue(const NodeMetaInfo &nodeMetaInfo, const QVariant &value) { m_data->defaultValueHash.insert(nodeMetaInfo.typeName(), value); } void PropertyMetaInfo::setEnumerator(const EnumeratorMetaInfo &info) { m_data->enumerator = info; } /*! \brief Returns meta information about the enumerator type, an invalid EnumeratorMetaInfo object if the property does not store enumerator values. */ const EnumeratorMetaInfo PropertyMetaInfo::enumerator() const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } return m_data->enumerator; } /*! \brief cast value type of QVariant parameter If the type of the passed variant does not correspond to type(), the method tries to convert the value according to QVariant::convert(). Returns a new QVariant with casted value type if successful, an invalid QVariant otherwise. \param variant the QVariant to take the value from \returns QVariant with aligned value type, or invalid QVariant */ QVariant PropertyMetaInfo::castedValue(const QVariant &originalVariant) const { if (!isValid()) { Q_ASSERT_X(isValid(), Q_FUNC_INFO, ""); throw InvalidMetaInfoException(__LINE__, Q_FUNC_INFO, __FILE__); } QVariant variant = originalVariant; if (m_data->enumType) { return variant; } QVariant::Type typeId = variantTypeId(); if (variant.type() == QVariant::UserType && variant.userType() == ModelNode::variantUserType()) { return variant; } else if (typeId == QVariant::UserType && m_data->type == QLatin1String("QVariant")) { return variant; } else if (typeId == QVariant::UserType && m_data->type == QLatin1String("variant")) { return variant; } else if (typeId == QVariant::UserType && m_data->type == QLatin1String("var")) { return variant; } else if (variant.type() == QVariant::List && variant.type() == QVariant::List) { // TODO: check the contents of the list return variant; } else if (type() == "var" || type() == "variant") { return variant; } else if (type() == "alias") { // TODO: The Qml compiler resolves the alias type. We probably should do the same. return variant; } else if (variant.convert(typeId)) { return variant; } return QDeclarativeStringConverters::variantFromString(variant.toString()); } }
enricoros/k-qt-creator-inspector
src/plugins/qmldesigner/core/metainfo/propertymetainfo.cpp
C++
lgpl-2.1
11,715
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** 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 Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "sourcefileswindow.h" #include "debuggeractions.h" #include "debuggercore.h" #include "debuggerengine.h" #include <utils/qtcassert.h> #include <utils/savedaction.h> #include <QDebug> #include <QContextMenuEvent> #include <QMenu> ////////////////////////////////////////////////////////////////// // // SourceFilesWindow // ////////////////////////////////////////////////////////////////// namespace Debugger { namespace Internal { SourceFilesTreeView::SourceFilesTreeView() { setSortingEnabled(true); } void SourceFilesTreeView::rowActivated(const QModelIndex &index) { DebuggerEngine *engine = currentEngine(); QTC_ASSERT(engine, return); engine->gotoLocation(index.data().toString()); } void SourceFilesTreeView::contextMenuEvent(QContextMenuEvent *ev) { DebuggerEngine *engine = currentEngine(); QTC_ASSERT(engine, return); QModelIndex index = indexAt(ev->pos()); index = index.sibling(index.row(), 0); QString name = index.data().toString(); bool engineActionsEnabled = engine->debuggerActionsEnabled(); QMenu menu; QAction *act1 = new QAction(tr("Reload Data"), &menu); act1->setEnabled(engineActionsEnabled); //act1->setCheckable(true); QAction *act2 = 0; if (name.isEmpty()) { act2 = new QAction(tr("Open File"), &menu); act2->setEnabled(false); } else { act2 = new QAction(tr("Open File \"%1\"'").arg(name), &menu); act2->setEnabled(true); } menu.addAction(act1); menu.addAction(act2); menu.addSeparator(); menu.addAction(action(SettingsDialog)); QAction *act = menu.exec(ev->globalPos()); if (act == act1) engine->reloadSourceFiles(); else if (act == act2) engine->gotoLocation(name); } } // namespace Internal } // namespace Debugger
maui-packages/qt-creator
src/plugins/debugger/sourcefileswindow.cpp
C++
lgpl-2.1
3,273
using System; namespace NCDK.FaulonSignatures { public class InvariantIntStringPair : IComparable<InvariantIntStringPair> { private readonly string stringValue; private readonly int value; private readonly int originalIndex; public InvariantIntStringPair(string stringValue, int value, int originalIndex) { this.stringValue = stringValue; this.value = value; this.originalIndex = originalIndex; } public bool Equals(string stringValue, int value) { return this.value == value && string.Equals(this.stringValue, stringValue, StringComparison.Ordinal); } public bool Equals(InvariantIntStringPair o) { if (this.stringValue == null || o.stringValue == null) return false; return this.value == o.value && string.Equals(this.stringValue, o.stringValue, StringComparison.Ordinal); } public int CompareTo(InvariantIntStringPair o) { if (this.stringValue == null || o.stringValue == null) return 0; int c = string.CompareOrdinal(this.stringValue, o.stringValue); if (c == 0) { if (this.value < o.value) { return -1; } else if (this.value > o.value) { return 1; } else { return 0; } } else { return c; } } public int GetOriginalIndex() { return originalIndex; } public override string ToString() { return this.stringValue + "|" + this.value + "|" + this.originalIndex; } } }
kazuyaujihara/NCDK
NCDK/FaulonSignatures/InvariantIntStringPair.cs
C#
lgpl-2.1
1,865
/* * Author: bwilliams * Created: Nov 16, 2015 * * Copyright (C) 2015-2016 VMware, Inc. All rights reserved. -- VMware Confidential * */ #include "stdafx.h" #include "Doc/DocXml/PersistenceXml/RemoteSecurityXml.h" #include "Doc/PersistenceDoc/CRemoteSecurityCollectionDoc.h" #include "Doc/PersistenceDoc/CRemoteSecurityDoc.h" #include "Xml/XmlUtils/CXmlElement.h" #include "Doc/DocXml/PersistenceXml/RemoteSecurityCollectionXml.h" using namespace Caf; void RemoteSecurityCollectionXml::add( const SmartPtrCRemoteSecurityCollectionDoc remoteSecurityCollectionDoc, const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RemoteSecurityCollectionXml", "add"); CAF_CM_VALIDATE_SMARTPTR(remoteSecurityCollectionDoc); CAF_CM_VALIDATE_SMARTPTR(thisXml); const std::deque<SmartPtrCRemoteSecurityDoc> remoteSecurityVal = remoteSecurityCollectionDoc->getRemoteSecurity(); if (! remoteSecurityVal.empty()) { for (TConstIterator<std::deque<SmartPtrCRemoteSecurityDoc> > remoteSecurityIter(remoteSecurityVal); remoteSecurityIter; remoteSecurityIter++) { const SmartPtrCXmlElement remoteSecurityXml = thisXml->createAndAddElement("remoteSecurity"); RemoteSecurityXml::add(*remoteSecurityIter, remoteSecurityXml); } } } SmartPtrCRemoteSecurityCollectionDoc RemoteSecurityCollectionXml::parse( const SmartPtrCXmlElement thisXml) { CAF_CM_STATIC_FUNC_VALIDATE("RemoteSecurityCollectionXml", "parse"); CAF_CM_VALIDATE_SMARTPTR(thisXml); const CXmlElement::SmartPtrCElementCollection remoteSecurityChildrenXml = thisXml->findOptionalChildren("remoteSecurity"); std::deque<SmartPtrCRemoteSecurityDoc> remoteSecurityVal; if (! remoteSecurityChildrenXml.IsNull() && ! remoteSecurityChildrenXml->empty()) { for (TConstIterator<CXmlElement::CElementCollection> remoteSecurityXmlIter(*remoteSecurityChildrenXml); remoteSecurityXmlIter; remoteSecurityXmlIter++) { const SmartPtrCXmlElement remoteSecurityXml = remoteSecurityXmlIter->second; const SmartPtrCRemoteSecurityDoc remoteSecurityDoc = RemoteSecurityXml::parse(remoteSecurityXml); remoteSecurityVal.push_back(remoteSecurityDoc); } } SmartPtrCRemoteSecurityCollectionDoc remoteSecurityCollectionDoc; remoteSecurityCollectionDoc.CreateInstance(); remoteSecurityCollectionDoc->initialize( remoteSecurityVal); return remoteSecurityCollectionDoc; }
pexip/os-open-vm-tools
open-vm-tools/common-agent/Cpp/Framework/Framework/src/Doc/DocXml/PersistenceXml/RemoteSecurityCollectionXml.cpp
C++
lgpl-2.1
2,370
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en_US" lang="en_US"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <!-- context2d.qdoc --> <title>Qt 4.8: Context2D Example</title> <link rel="stylesheet" type="text/css" href="style/offline.css" /> </head> <body> <div class="header" id="qtdocheader"> <div class="content"> <a href="index.html" class="qtref"><span>Qt Reference Documentation</span></a> </div> <div class="breadcrumb toolblock"> <ul> <li class="first"><a href="index.html">Home</a></li> <!-- Breadcrumbs go here --> <li><a href="all-examples.html">Examples</a></li> <li>Context2D Example</li> </ul> </div> </div> <div class="content mainContent"> <div class="toc"> <h3><a name="toc">Contents</a></h3> <ul> <li class="level1"><a href="#using-the-html-canvas-element-in-a-web-browser">Using The HTML Canvas Element in a Web Browser</a></li> <li class="level1"><a href="#using-qt-script-to-script-a-canvas">Using Qt Script to script a Canvas</a></li> <li class="level1"><a href="#the-context2d-class">The Context2D Class</a></li> <li class="level2"><a href="#implementation">Implementation</a></li> <li class="level1"><a href="#the-canvas-widget">The Canvas Widget</a></li> <li class="level1"><a href="#the-environment">The Environment</a></li> <li class="level1"><a href="#the-application-window">The Application Window</a></li> </ul> </div> <h1 class="title">Context2D Example</h1> <span class="subtitle"></span> <!-- $$$script/context2d-description --> <div class="descr"> <a name="details"></a> <p>Files:</p> <ul> <li><a href="script-context2d-context2d-cpp.html">script/context2d/context2d.cpp</a></li> <li><a href="script-context2d-context2d-h.html">script/context2d/context2d.h</a></li> <li><a href="script-context2d-domimage-cpp.html">script/context2d/domimage.cpp</a></li> <li><a href="script-context2d-domimage-h.html">script/context2d/domimage.h</a></li> <li><a href="script-context2d-environment-cpp.html">script/context2d/environment.cpp</a></li> <li><a href="script-context2d-environment-h.html">script/context2d/environment.h</a></li> <li><a href="script-context2d-qcontext2dcanvas-cpp.html">script/context2d/qcontext2dcanvas.cpp</a></li> <li><a href="script-context2d-qcontext2dcanvas-h.html">script/context2d/qcontext2dcanvas.h</a></li> <li><a href="script-context2d-window-cpp.html">script/context2d/window.cpp</a></li> <li><a href="script-context2d-window-h.html">script/context2d/window.h</a></li> <li><a href="script-context2d-scripts-alpha-js.html">script/context2d/scripts/alpha.js</a></li> <li><a href="script-context2d-scripts-arc-js.html">script/context2d/scripts/arc.js</a></li> <li><a href="script-context2d-scripts-bezier-js.html">script/context2d/scripts/bezier.js</a></li> <li><a href="script-context2d-scripts-clock-js.html">script/context2d/scripts/clock.js</a></li> <li><a href="script-context2d-scripts-fill1-js.html">script/context2d/scripts/fill1.js</a></li> <li><a href="script-context2d-scripts-grad-js.html">script/context2d/scripts/grad.js</a></li> <li><a href="script-context2d-scripts-linecap-js.html">script/context2d/scripts/linecap.js</a></li> <li><a href="script-context2d-scripts-linestye-js.html">script/context2d/scripts/linestye.js</a></li> <li><a href="script-context2d-scripts-moveto-js.html">script/context2d/scripts/moveto.js</a></li> <li><a href="script-context2d-scripts-moveto2-js.html">script/context2d/scripts/moveto2.js</a></li> <li><a href="script-context2d-scripts-pacman-js.html">script/context2d/scripts/pacman.js</a></li> <li><a href="script-context2d-scripts-plasma-js.html">script/context2d/scripts/plasma.js</a></li> <li><a href="script-context2d-scripts-pong-js.html">script/context2d/scripts/pong.js</a></li> <li><a href="script-context2d-scripts-quad-js.html">script/context2d/scripts/quad.js</a></li> <li><a href="script-context2d-scripts-rgba-js.html">script/context2d/scripts/rgba.js</a></li> <li><a href="script-context2d-scripts-rotate-js.html">script/context2d/scripts/rotate.js</a></li> <li><a href="script-context2d-scripts-scale-js.html">script/context2d/scripts/scale.js</a></li> <li><a href="script-context2d-scripts-stroke1-js.html">script/context2d/scripts/stroke1.js</a></li> <li><a href="script-context2d-scripts-translate-js.html">script/context2d/scripts/translate.js</a></li> <li><a href="script-context2d-main-cpp.html">script/context2d/main.cpp</a></li> <li><a href="script-context2d-context2d-pro.html">script/context2d/context2d.pro</a></li> <li><a href="script-context2d-context2d-qrc.html">script/context2d/context2d.qrc</a></li> </ul> <p class="centerAlign"><img src="images/context2d-example.png" /></p><p>Context2D is part of the specification for the HTML <tt>&lt;canvas&gt;</tt> element. It can be used to draw graphics via scripting. A good resource for learning more about the HTML <tt>&lt;canvas&gt;</tt> element is the <a href="http://developer.mozilla.org/en/docs/HTML:Canvas">Mozilla Developer Center</a>.</p> <a name="using-the-html-canvas-element-in-a-web-browser"></a> <h2>Using The HTML Canvas Element in a Web Browser</h2> <p>First, let's look at how the <tt>&lt;canvas&gt;</tt> element is typically used in a web browser. The following HTML snippet defines a canvas of size 400x400 pixels with id <tt>mycanvas</tt>:</p> <pre class="cpp"> <span class="operator">&lt;</span>canvas width<span class="operator">=</span><span class="string">&quot;400&quot;</span> height<span class="operator">=</span><span class="string">&quot;400&quot;</span> id<span class="operator">=</span><span class="string">&quot;mycanvas&quot;</span><span class="operator">&gt;</span>Fallback content goes here<span class="operator">.</span><span class="operator">&lt;</span><span class="operator">/</span>canvas<span class="operator">&gt;</span></pre> <p>To draw on the canvas, we must first obtain a reference to the DOM element corresponding to the <tt>&lt;canvas&gt;</tt> tag and then call the element's getContext() function. The resulting object implements the Context2D API that we use to draw.</p> <pre class="cpp"> <span class="operator">&lt;</span>script<span class="operator">&gt;</span> var canvas <span class="operator">=</span> document<span class="operator">.</span>getElementById(<span class="string">&quot;mycanvas&quot;</span>); var ctx <span class="operator">=</span> canvas<span class="operator">.</span>getContext(<span class="string">&quot;2d&quot;</span>); <span class="comment">// Draw a face</span> ctx<span class="operator">.</span>beginPath(); ctx<span class="operator">.</span>arc(<span class="number">75</span><span class="operator">,</span><span class="number">75</span><span class="operator">,</span><span class="number">50</span><span class="operator">,</span><span class="number">0</span><span class="operator">,</span>Math<span class="operator">.</span>PI<span class="operator">*</span><span class="number">2</span><span class="operator">,</span><span class="keyword">true</span>); <span class="comment">// Outer circle</span> ctx<span class="operator">.</span>moveTo(<span class="number">110</span><span class="operator">,</span><span class="number">75</span>); ctx<span class="operator">.</span>arc(<span class="number">75</span><span class="operator">,</span><span class="number">75</span><span class="operator">,</span><span class="number">35</span><span class="operator">,</span><span class="number">0</span><span class="operator">,</span>Math<span class="operator">.</span>PI<span class="operator">,</span><span class="keyword">false</span>); <span class="comment">// Mouth</span> ctx<span class="operator">.</span>moveTo(<span class="number">65</span><span class="operator">,</span><span class="number">65</span>); ctx<span class="operator">.</span>arc(<span class="number">60</span><span class="operator">,</span><span class="number">65</span><span class="operator">,</span><span class="number">5</span><span class="operator">,</span><span class="number">0</span><span class="operator">,</span>Math<span class="operator">.</span>PI<span class="operator">*</span><span class="number">2</span><span class="operator">,</span><span class="keyword">true</span>); <span class="comment">// Left eye</span> ctx<span class="operator">.</span>moveTo(<span class="number">95</span><span class="operator">,</span><span class="number">65</span>); ctx<span class="operator">.</span>arc(<span class="number">90</span><span class="operator">,</span><span class="number">65</span><span class="operator">,</span><span class="number">5</span><span class="operator">,</span><span class="number">0</span><span class="operator">,</span>Math<span class="operator">.</span>PI<span class="operator">*</span><span class="number">2</span><span class="operator">,</span><span class="keyword">true</span>); <span class="comment">// Right eye</span> ctx<span class="operator">.</span>stroke(); <span class="operator">&lt;</span><span class="operator">/</span>script<span class="operator">&gt;</span></pre> <p>When the page is rendered by a browser that supports the <tt>&lt;canvas&gt;</tt> tag, this would be the result:</p> <p class="centerAlign"><img src="images/context2d-example-smileysmile.png" /></p><a name="using-qt-script-to-script-a-canvas"></a> <h2>Using Qt Script to script a Canvas</h2> <p>The goal of this example is to be able to evaluate scripts that use the Context2D API, and render the results. Basic interaction (mouse, keyboard) should also be supported. In other words, we want to present scripts with an execution environment that very much resembles that of a web browser. Of course, our environment is only a small subset of what a browser provides; i.e&#x2e; we don't provide a full DOM API, only what is needed to run &quot;self-contained&quot; Context2D scripts (i.e&#x2e; scripts that don't depend on other parts of the DOM document).</p> <p>Our &quot;Context2D-browser&quot; is set up through the following steps:</p> <ul> <li>Create an Environment.</li> <li>Create a Context2D, and a QContext2DCanvas widget to render it.</li> <li>Add the canvas object to the environment; this will enable scripts to obtain a reference to it.</li> <li>Evaluate scripts in the environment.</li> </ul> <p>Once a script has been evaluated, the application handles any timer events and input events that occur subsequently (i.e&#x2e; forwards events to their associated script targets).</p> <a name="the-context2d-class"></a> <h2>The Context2D Class</h2> <p>The &quot;heart&quot; of this example is the Context2D C++ class that implements the drawing API. Its interface is defined in terms of properties and slots. Note that this class isn't tied to Qt Script in any way.</p> <pre class="cpp"> <span class="keyword">class</span> Context2D : <span class="keyword">public</span> <span class="type"><a href="qobject.html">QObject</a></span> { Q_OBJECT <span class="comment">// compositing</span> Q_PROPERTY(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> globalAlpha READ globalAlpha WRITE setGlobalAlpha) Q_PROPERTY(<span class="type"><a href="qstring.html">QString</a></span> globalCompositeOperation READ globalCompositeOperation WRITE setGlobalCompositeOperation) Q_PROPERTY(<span class="type"><a href="qvariant.html">QVariant</a></span> strokeStyle READ strokeStyle WRITE setStrokeStyle) Q_PROPERTY(<span class="type"><a href="qvariant.html">QVariant</a></span> fillStyle READ fillStyle WRITE setFillStyle) <span class="comment">// line caps/joins</span> Q_PROPERTY(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> lineWidth READ lineWidth WRITE setLineWidth) Q_PROPERTY(<span class="type"><a href="qstring.html">QString</a></span> lineCap READ lineCap WRITE setLineCap) Q_PROPERTY(<span class="type"><a href="qstring.html">QString</a></span> lineJoin READ lineJoin WRITE setLineJoin) Q_PROPERTY(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> miterLimit READ miterLimit WRITE setMiterLimit) <span class="comment">// shadows</span> Q_PROPERTY(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> shadowOffsetX READ shadowOffsetX WRITE setShadowOffsetX) Q_PROPERTY(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> shadowOffsetY READ shadowOffsetY WRITE setShadowOffsetY) Q_PROPERTY(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> shadowBlur READ shadowBlur WRITE setShadowBlur) Q_PROPERTY(<span class="type"><a href="qstring.html">QString</a></span> shadowColor READ shadowColor WRITE setShadowColor)</pre> <p>The properties define various aspects of the Context2D configuration.</p> <pre class="cpp"> <span class="keyword">public</span> <span class="keyword">slots</span>: <span class="type">void</span> save(); <span class="comment">// push state on state stack</span> <span class="type">void</span> restore(); <span class="comment">// pop state stack and restore state</span> <span class="type">void</span> scale(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y); <span class="type">void</span> rotate(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> angle); <span class="type">void</span> translate(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y); <span class="type">void</span> transform(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> m11<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> m12<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> m21<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> m22<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> dx<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> dy); <span class="type">void</span> setTransform(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> m11<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> m12<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> m21<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> m22<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> dx<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> dy); CanvasGradient createLinearGradient(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x0<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y0<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x1<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y1); CanvasGradient createRadialGradient(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x0<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y0<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> r0<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x1<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y1<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> r1); <span class="comment">// rects</span> <span class="type">void</span> clearRect(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> w<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> h); <span class="type">void</span> fillRect(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> w<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> h); <span class="type">void</span> strokeRect(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> w<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> h); <span class="comment">// path API</span> <span class="type">void</span> beginPath(); <span class="type">void</span> closePath(); <span class="type">void</span> moveTo(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y); <span class="type">void</span> lineTo(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y); <span class="type">void</span> quadraticCurveTo(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> cpx<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> cpy<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y); <span class="type">void</span> bezierCurveTo(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> cp1x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> cp1y<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> cp2x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> cp2y<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y); <span class="type">void</span> arcTo(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x1<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y1<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x2<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y2<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> radius); <span class="type">void</span> rect(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> w<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> h); <span class="type">void</span> arc(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> radius<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> startAngle<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> endAngle<span class="operator">,</span> <span class="type">bool</span> anticlockwise); <span class="type">void</span> fill(); <span class="type">void</span> stroke(); <span class="type">void</span> clip(); <span class="type">bool</span> isPointInPath(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y) <span class="keyword">const</span>;</pre> <p>The slots define the operations that can be performed.</p> <pre class="cpp"> <span class="keyword">signals</span>: <span class="type">void</span> changed(<span class="keyword">const</span> <span class="type"><a href="qimage.html">QImage</a></span> <span class="operator">&amp;</span>image);</pre> <p>The changed() signal is emitted when the contents of the drawing area has changed, so that clients associated with the Context2D object (i.e&#x2e; the canvas widget that renders it) are notified.</p> <a name="implementation"></a> <h3>Implementation</h3> <p>Conveniently enough, the concepts, data structures and operations of the Context2D API map more or less directly to Qt's painting API. Conceptually, all we have to do is initialize a <a href="qpainter.html">QPainter</a> according to the Context2D properties, and use functions like <a href="qpainter.html#strokePath">QPainter::strokePath</a>() to do the painting. Painting is done on a <a href="qimage.html">QImage</a>.</p> <pre class="cpp"> <span class="type"><a href="qstring.html">QString</a></span> Context2D<span class="operator">::</span>lineCap() <span class="keyword">const</span> { <span class="keyword">switch</span> (m_state<span class="operator">.</span>lineCap) { <span class="keyword">case</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>FlatCap: <span class="keyword">return</span> <span class="string">&quot;butt&quot;</span>; <span class="keyword">case</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>SquareCap: <span class="keyword">return</span> <span class="string">&quot;square&quot;</span>; <span class="keyword">case</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>RoundCap: <span class="keyword">return</span> <span class="string">&quot;round&quot;</span>; <span class="keyword">default</span>: ; } <span class="keyword">return</span> <span class="type"><a href="qstring.html">QString</a></span>(); } <span class="type">void</span> Context2D<span class="operator">::</span>setLineCap(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>capString) { <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>PenCapStyle style; <span class="keyword">if</span> (capString <span class="operator">=</span><span class="operator">=</span> <span class="string">&quot;round&quot;</span>) style <span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>RoundCap; <span class="keyword">else</span> <span class="keyword">if</span> (capString <span class="operator">=</span><span class="operator">=</span> <span class="string">&quot;square&quot;</span>) style <span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>SquareCap; <span class="keyword">else</span> <span class="comment">//if (capString == &quot;butt&quot;)</span> style <span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>FlatCap; m_state<span class="operator">.</span>lineCap <span class="operator">=</span> style; m_state<span class="operator">.</span>flags <span class="operator">|</span><span class="operator">=</span> DirtyLineCap; }</pre> <p>The property accessors and most of the slots manipulate the internal Context2D state in some way. For the <tt>lineCap</tt> property, Context2D uses a string representation; we therefore have to map it from/to a <a href="qt.html#PenCapStyle-enum">Qt::PenCapStyle</a>. The <tt>lineJoin</tt> property is handled in the same fashion. All the property setters also set a <i>dirty flag</i> for the property; this is used to decide which aspects of the <a href="qpainter.html">QPainter</a> that need to be updated before doing the next painting operation.</p> <pre class="cpp"> <span class="type">void</span> Context2D<span class="operator">::</span>setFillStyle(<span class="keyword">const</span> <span class="type"><a href="qvariant.html">QVariant</a></span> <span class="operator">&amp;</span>style) { <span class="keyword">if</span> (style<span class="operator">.</span>canConvert<span class="operator">&lt;</span>CanvasGradient<span class="operator">&gt;</span>()) { CanvasGradient cg <span class="operator">=</span> qvariant_cast<span class="operator">&lt;</span>CanvasGradient<span class="operator">&gt;</span>(style); m_state<span class="operator">.</span>fillStyle <span class="operator">=</span> cg<span class="operator">.</span>value; } <span class="keyword">else</span> { <span class="type"><a href="qcolor.html">QColor</a></span> color <span class="operator">=</span> colorFromString(style<span class="operator">.</span>toString()); m_state<span class="operator">.</span>fillStyle <span class="operator">=</span> color; } m_state<span class="operator">.</span>flags <span class="operator">|</span><span class="operator">=</span> DirtyFillStyle; }</pre> <p>The implementation of the <tt>fillStyle</tt> property is interesting, since the value can be either a string or a <tt>CanvasGradient</tt>. We handle this by having the property be of type <a href="qvariant.html">QVariant</a>, and check the actual type of the value to see how to handle the write.</p> <pre class="cpp"> <span class="type">void</span> Context2D<span class="operator">::</span>fillRect(<span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> x<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> y<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> w<span class="operator">,</span> <span class="type"><a href="qtglobal.html#qreal-typedef">qreal</a></span> h) { beginPainting(); m_painter<span class="operator">.</span>save(); m_painter<span class="operator">.</span>setMatrix(m_state<span class="operator">.</span>matrix<span class="operator">,</span> <span class="keyword">false</span>); m_painter<span class="operator">.</span>fillRect(<span class="type"><a href="qrectf.html">QRectF</a></span>(x<span class="operator">,</span> y<span class="operator">,</span> w<span class="operator">,</span> h)<span class="operator">,</span> m_painter<span class="operator">.</span>brush()); m_painter<span class="operator">.</span>restore(); scheduleChange(); }</pre> <p>Context2D does not have a concept of a paint event; painting operations can happen at any time. We would like to be efficient, and not have to call <a href="qpainter.html#begin">QPainter::begin</a>() and <a href="qpainter.html#end">QPainter::end</a>() for every painting operation, since typically many painting operations will follow in quick succession. The implementations of the painting operations use a helper function, beginPainting(), that activates the <a href="qpainter.html">QPainter</a> if it isn't active already, and updates the state of the <a href="qpainter.html">QPainter</a> (brush, pen, etc.) so that it reflects the current Context2D state.</p> <pre class="cpp"> <span class="type">void</span> Context2D<span class="operator">::</span>scheduleChange() { <span class="keyword">if</span> (m_changeTimerId <span class="operator">=</span><span class="operator">=</span> <span class="operator">-</span><span class="number">1</span>) m_changeTimerId <span class="operator">=</span> startTimer(<span class="number">0</span>); } <span class="type">void</span> Context2D<span class="operator">::</span>timerEvent(<span class="type"><a href="qtimerevent.html">QTimerEvent</a></span> <span class="operator">*</span>e) { <span class="keyword">if</span> (e<span class="operator">-</span><span class="operator">&gt;</span>timerId() <span class="operator">=</span><span class="operator">=</span> m_changeTimerId) { killTimer(m_changeTimerId); m_changeTimerId <span class="operator">=</span> <span class="operator">-</span><span class="number">1</span>; <span class="keyword">emit</span> changed(endPainting()); } <span class="keyword">else</span> { <span class="type"><a href="qobject.html">QObject</a></span><span class="operator">::</span>timerEvent(e); } }</pre> <p>The implementation of each painting operation ends by calling scheduleChange(), which will post a zero-timer event if one is not already pending. When the application returns to the event loop later (presumably after all the drawing operations have finished), the timer will trigger, <a href="qpainter.html#end">QPainter::end</a>() will be called, and the changed() signal is emitted with the new image as argument. The net effect is that there will typically be only a single (<a href="qpainter.html#begin">QPainter::begin</a>(), <a href="qpainter.html#end">QPainter::end</a>()) pair executed for the full sequence of painting operations.</p> <a name="the-canvas-widget"></a> <h2>The Canvas Widget</h2> <pre class="cpp"> <span class="keyword">class</span> QContext2DCanvas : <span class="keyword">public</span> <span class="type"><a href="qwidget.html">QWidget</a></span> { Q_OBJECT <span class="keyword">public</span>: QContext2DCanvas(Context2D <span class="operator">*</span>context<span class="operator">,</span> Environment <span class="operator">*</span>env<span class="operator">,</span> <span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent <span class="operator">=</span> <span class="number">0</span>); <span class="operator">~</span>QContext2DCanvas(); Context2D <span class="operator">*</span>context() <span class="keyword">const</span>; <span class="type">void</span> reset(); <span class="keyword">public</span> <span class="keyword">slots</span>: <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> getContext(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>str); <span class="type">void</span> resize(<span class="type">int</span> width<span class="operator">,</span> <span class="type">int</span> height); <span class="comment">// EventTarget</span> <span class="type">void</span> addEventListener(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>type<span class="operator">,</span> <span class="keyword">const</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> <span class="operator">&amp;</span>listener<span class="operator">,</span> <span class="type">bool</span> useCapture); <span class="keyword">protected</span>: <span class="keyword">virtual</span> <span class="type">void</span> paintEvent(<span class="type"><a href="qpaintevent.html">QPaintEvent</a></span> <span class="operator">*</span>e); <span class="keyword">virtual</span> <span class="type">void</span> mouseMoveEvent(<span class="type"><a href="qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e); <span class="keyword">virtual</span> <span class="type">void</span> mousePressEvent(<span class="type"><a href="qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e); <span class="keyword">virtual</span> <span class="type">void</span> mouseReleaseEvent(<span class="type"><a href="qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e); <span class="keyword">virtual</span> <span class="type">void</span> keyPressEvent(<span class="type"><a href="qkeyevent.html">QKeyEvent</a></span> <span class="operator">*</span>e); <span class="keyword">virtual</span> <span class="type">void</span> keyReleaseEvent(<span class="type"><a href="qkeyevent.html">QKeyEvent</a></span> <span class="operator">*</span>e); <span class="keyword">virtual</span> <span class="type">void</span> resizeEvent(<span class="type"><a href="qresizeevent.html">QResizeEvent</a></span> <span class="operator">*</span>e); <span class="keyword">private</span> <span class="keyword">slots</span>: <span class="type">void</span> contentsChanged(<span class="keyword">const</span> <span class="type"><a href="qimage.html">QImage</a></span> <span class="operator">&amp;</span>image);</pre> <p>The QContext2DCanvas class provides a widget that renders the contents of a Context2D object. It also provides a minimal scripting API, most notably the getContext() function.</p> <pre class="cpp"> QContext2DCanvas<span class="operator">::</span>QContext2DCanvas(Context2D <span class="operator">*</span>context<span class="operator">,</span> Environment <span class="operator">*</span>env<span class="operator">,</span> <span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent) : <span class="type"><a href="qwidget.html">QWidget</a></span>(parent)<span class="operator">,</span> m_context(context)<span class="operator">,</span> m_env(env) { <span class="type"><a href="qobject.html">QObject</a></span><span class="operator">::</span>connect(context<span class="operator">,</span> SIGNAL(changed(<span class="type"><a href="qimage.html">QImage</a></span>))<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(contentsChanged(<span class="type"><a href="qimage.html">QImage</a></span>))); setMouseTracking(<span class="keyword">true</span>); }</pre> <p>The constructor connects to the changed() signal of the Context2D object, so that the widget can update itself when it needs to do so. Mouse tracking is enabled so that mouse move events will be received even when no mouse buttons are depressed.</p> <pre class="cpp"> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> QContext2DCanvas<span class="operator">::</span>getContext(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>str) { <span class="keyword">if</span> (str <span class="operator">!</span><span class="operator">=</span> <span class="string">&quot;2d&quot;</span>) <span class="keyword">return</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span>(); <span class="keyword">return</span> m_env<span class="operator">-</span><span class="operator">&gt;</span>toWrapper(m_context); }</pre> <p>The getContext() function asks the environment to wrap the Context2D object; the resulting proxy object makes the Context2D API available to scripts.</p> <pre class="cpp"> <span class="type">void</span> QContext2DCanvas<span class="operator">::</span>contentsChanged(<span class="keyword">const</span> <span class="type"><a href="qimage.html">QImage</a></span> <span class="operator">&amp;</span>image) { m_image <span class="operator">=</span> image; update(); } <span class="type">void</span> QContext2DCanvas<span class="operator">::</span>paintEvent(<span class="type"><a href="qpaintevent.html">QPaintEvent</a></span> <span class="operator">*</span>e) { <span class="type"><a href="qpainter.html">QPainter</a></span> p(<span class="keyword">this</span>); <span class="preprocessor">#ifdef Q_OS_SYMBIAN</span> <span class="comment">// Draw white rect first since in with some themes the js-file content will produce black-on-black.</span> <span class="type"><a href="qbrush.html">QBrush</a></span> whiteBgBrush(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>white); p<span class="operator">.</span>fillRect(e<span class="operator">-</span><span class="operator">&gt;</span>rect()<span class="operator">,</span> whiteBgBrush); <span class="preprocessor">#endif</span> p<span class="operator">.</span>setClipRect(e<span class="operator">-</span><span class="operator">&gt;</span>rect()); p<span class="operator">.</span>drawImage(<span class="number">0</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> m_image); }</pre> <p>The paintEvent() function simply paints the contents that was last received from the Context2D object.</p> <pre class="cpp"> <span class="type">void</span> QContext2DCanvas<span class="operator">::</span>mouseMoveEvent(<span class="type"><a href="qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e) { m_env<span class="operator">-</span><span class="operator">&gt;</span>handleEvent(<span class="keyword">this</span><span class="operator">,</span> e); } <span class="type">void</span> QContext2DCanvas<span class="operator">::</span>mousePressEvent(<span class="type"><a href="qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e) { m_env<span class="operator">-</span><span class="operator">&gt;</span>handleEvent(<span class="keyword">this</span><span class="operator">,</span> e); } <span class="type">void</span> QContext2DCanvas<span class="operator">::</span>mouseReleaseEvent(<span class="type"><a href="qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e) { m_env<span class="operator">-</span><span class="operator">&gt;</span>handleEvent(<span class="keyword">this</span><span class="operator">,</span> e); } <span class="type">void</span> QContext2DCanvas<span class="operator">::</span>keyPressEvent(<span class="type"><a href="qkeyevent.html">QKeyEvent</a></span> <span class="operator">*</span>e) { m_env<span class="operator">-</span><span class="operator">&gt;</span>handleEvent(<span class="keyword">this</span><span class="operator">,</span> e); } <span class="type">void</span> QContext2DCanvas<span class="operator">::</span>keyReleaseEvent(<span class="type"><a href="qkeyevent.html">QKeyEvent</a></span> <span class="operator">*</span>e) { m_env<span class="operator">-</span><span class="operator">&gt;</span>handleEvent(<span class="keyword">this</span><span class="operator">,</span> e); }</pre> <p>The canvas widget reimplements mouse and key event handlers, and forwards these events to the scripting environment. The environment will take care of delivering the event to the proper script target, if any.</p> <a name="the-environment"></a> <h2>The Environment</h2> <pre class="cpp"> <span class="keyword">class</span> Environment : <span class="keyword">public</span> <span class="type"><a href="qobject.html">QObject</a></span> { Q_OBJECT Q_PROPERTY(<span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> document READ document) <span class="keyword">public</span>: Environment(<span class="type"><a href="qobject.html">QObject</a></span> <span class="operator">*</span>parent <span class="operator">=</span> <span class="number">0</span>); <span class="operator">~</span>Environment(); <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> document() <span class="keyword">const</span>; <span class="type">void</span> addCanvas(QContext2DCanvas <span class="operator">*</span>canvas); QContext2DCanvas <span class="operator">*</span>canvasByName(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>name) <span class="keyword">const</span>; <span class="type"><a href="qlist.html">QList</a></span><span class="operator">&lt;</span>QContext2DCanvas<span class="operator">*</span><span class="operator">&gt;</span> canvases() <span class="keyword">const</span>; <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> evaluate(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>code<span class="operator">,</span> <span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>fileName <span class="operator">=</span> <span class="type"><a href="qstring.html">QString</a></span>()); <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> toWrapper(<span class="type"><a href="qobject.html">QObject</a></span> <span class="operator">*</span>object); <span class="type">void</span> handleEvent(QContext2DCanvas <span class="operator">*</span>canvas<span class="operator">,</span> <span class="type"><a href="qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e); <span class="type">void</span> handleEvent(QContext2DCanvas <span class="operator">*</span>canvas<span class="operator">,</span> <span class="type"><a href="qkeyevent.html">QKeyEvent</a></span> <span class="operator">*</span>e); <span class="type">void</span> reset();</pre> <p>The Environment class provides a scripting environment where a Canvas C++ object can be registered, looked up by ID (name), and where scripts can be evaluated. The environment has a <tt>document</tt> property, just like the scripting environment of a web browser, so that scripts can call <tt>document.getElementById()</tt> to obtain a reference to a canvas.</p> <pre class="cpp"> <span class="keyword">public</span> <span class="keyword">slots</span>: <span class="type">int</span> setInterval(<span class="keyword">const</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> <span class="operator">&amp;</span>expression<span class="operator">,</span> <span class="type">int</span> delay); <span class="type">void</span> clearInterval(<span class="type">int</span> timerId); <span class="type">int</span> setTimeout(<span class="keyword">const</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> <span class="operator">&amp;</span>expression<span class="operator">,</span> <span class="type">int</span> delay); <span class="type">void</span> clearTimeout(<span class="type">int</span> timerId);</pre> <p>The Environment class provides the timer attributes of the DOM Window Object interface. This enables us to support scripts that do animation, for example.</p> <pre class="cpp"> <span class="keyword">signals</span>: <span class="type">void</span> scriptError(<span class="keyword">const</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> <span class="operator">&amp;</span>error);</pre> <p>The scriptError() signal is emitted when evaluation of a script causes a script exception. For example, if a mouse press handler or timeout handler causes an exception, the environment's client(s) will be notified of this and can report the error.</p> <pre class="cpp"> Environment<span class="operator">::</span>Environment(<span class="type"><a href="qobject.html">QObject</a></span> <span class="operator">*</span>parent) : <span class="type"><a href="qobject.html">QObject</a></span>(parent) { m_engine <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qscriptengine.html">QScriptEngine</a></span>(<span class="keyword">this</span>); m_document <span class="operator">=</span> m_engine<span class="operator">-</span><span class="operator">&gt;</span>newQObject( <span class="keyword">new</span> Document(<span class="keyword">this</span>)<span class="operator">,</span> <span class="type"><a href="qscriptengine.html">QScriptEngine</a></span><span class="operator">::</span><span class="type">QtOwnership</span><span class="operator">,</span> <span class="type"><a href="qscriptengine.html">QScriptEngine</a></span><span class="operator">::</span>ExcludeSuperClassContents); CanvasGradientPrototype<span class="operator">::</span>setup(m_engine); m_originalGlobalObject <span class="operator">=</span> m_engine<span class="operator">-</span><span class="operator">&gt;</span>globalObject(); reset(); }</pre> <p>The constructor initializes the environment. First it creates the <a href="qscriptengine.html">QScriptEngine</a> that will be used to evaluate scripts. It creates the Document object that provides the getElementById() function. Note that the <a href="qscriptengine.html#QObjectWrapOption-enum">QScriptEngine::ExcludeSuperClassContents</a> flag is specified to avoid the wrapper objects from exposing properties and methods inherited from <a href="qobject.html">QObject</a>. Next, the environment wraps a pointer to <i>itself</i>; this is to prepare for setting this object as the script engine's Global Object. The properties of the standard Global Object are copied, so that these will also be available in our custom Global Object. We also create two self-references to the object; again, this is to provide a minimal level of compabilitity with the scripting environment that web browsers provide.</p> <pre class="cpp"> <span class="type">void</span> Environment<span class="operator">::</span>addCanvas(QContext2DCanvas <span class="operator">*</span>canvas) { m_canvases<span class="operator">.</span>append(canvas); } QContext2DCanvas <span class="operator">*</span>Environment<span class="operator">::</span>canvasByName(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>name) <span class="keyword">const</span> { <span class="keyword">for</span> (<span class="type">int</span> i <span class="operator">=</span> <span class="number">0</span>; i <span class="operator">&lt;</span> m_canvases<span class="operator">.</span>size(); <span class="operator">+</span><span class="operator">+</span>i) { QContext2DCanvas <span class="operator">*</span>canvas <span class="operator">=</span> m_canvases<span class="operator">.</span>at(i); <span class="keyword">if</span> (canvas<span class="operator">-</span><span class="operator">&gt;</span>objectName() <span class="operator">=</span><span class="operator">=</span> name) <span class="keyword">return</span> canvas; } <span class="keyword">return</span> <span class="number">0</span>; }</pre> <p>The addCanvas() function adds the given canvas to the list of registered canvas objects. The canvasByName() function looks up a canvas by <a href="qobject.html#objectName-prop">QObject::objectName</a>(). This function is used to implement the <tt>document.getElementById()</tt> script function.</p> <pre class="cpp"> <span class="type">int</span> Environment<span class="operator">::</span>setInterval(<span class="keyword">const</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> <span class="operator">&amp;</span>expression<span class="operator">,</span> <span class="type">int</span> delay) { <span class="keyword">if</span> (expression<span class="operator">.</span>isString() <span class="operator">|</span><span class="operator">|</span> expression<span class="operator">.</span>isFunction()) { <span class="type">int</span> timerId <span class="operator">=</span> startTimer(delay); m_intervalHash<span class="operator">.</span>insert(timerId<span class="operator">,</span> expression); <span class="keyword">return</span> timerId; } <span class="keyword">return</span> <span class="operator">-</span><span class="number">1</span>; } <span class="type">void</span> Environment<span class="operator">::</span>clearInterval(<span class="type">int</span> timerId) { killTimer(timerId); m_intervalHash<span class="operator">.</span>remove(timerId); } <span class="type">void</span> Environment<span class="operator">::</span>timerEvent(<span class="type"><a href="qtimerevent.html">QTimerEvent</a></span> <span class="operator">*</span>event) { <span class="type">int</span> id <span class="operator">=</span> event<span class="operator">-</span><span class="operator">&gt;</span>timerId(); <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> expression <span class="operator">=</span> m_intervalHash<span class="operator">.</span>value(id); <span class="keyword">if</span> (<span class="operator">!</span>expression<span class="operator">.</span>isValid()) { expression <span class="operator">=</span> m_timeoutHash<span class="operator">.</span>value(id); <span class="keyword">if</span> (expression<span class="operator">.</span>isValid()) killTimer(id); } <span class="keyword">if</span> (expression<span class="operator">.</span>isString()) { evaluate(expression<span class="operator">.</span>toString()); } <span class="keyword">else</span> <span class="keyword">if</span> (expression<span class="operator">.</span>isFunction()) { expression<span class="operator">.</span>call(); } maybeEmitScriptError(); }</pre> <p>The setInterval() and clearInterval() implementations use a <a href="qhash.html">QHash</a> to map from timer ID to the <a href="qscriptvalue.html">QScriptValue</a> that holds the expression to evaluate when the timer is triggered. A helper function, maybeEmitScriptError(), is called after invoking the script handler; it will emit the scriptError() signal if the script engine has an uncaught exception.</p> <pre class="cpp"> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> Environment<span class="operator">::</span>toWrapper(<span class="type"><a href="qobject.html">QObject</a></span> <span class="operator">*</span>object) { <span class="keyword">return</span> m_engine<span class="operator">-</span><span class="operator">&gt;</span>newQObject(object<span class="operator">,</span> <span class="type"><a href="qscriptengine.html">QScriptEngine</a></span><span class="operator">::</span><span class="type">QtOwnership</span><span class="operator">,</span> <span class="type"><a href="qscriptengine.html">QScriptEngine</a></span><span class="operator">::</span>PreferExistingWrapperObject <span class="operator">|</span> <span class="type"><a href="qscriptengine.html">QScriptEngine</a></span><span class="operator">::</span>ExcludeSuperClassContents); }</pre> <p>The toWrapper() functions creates a <a href="qscriptvalue.html">QScriptValue</a> that wraps the given <a href="qobject.html">QObject</a>. Note that the <a href="qscriptengine.html#QObjectWrapOption-enum">QScriptEngine::PreferExistingWrapperObject</a> flag is specified; this guarantees that a single, unique wrapper object will be returned, even if toWrapper() is called several times with the same argument. This is important, since it is possible that a script can set new properties on the resulting wrapper object (e.g&#x2e; event handlers like <tt>onmousedown</tt>), and we want these to persist.</p> <pre class="cpp"> <span class="type">void</span> Environment<span class="operator">::</span>handleEvent(QContext2DCanvas <span class="operator">*</span>canvas<span class="operator">,</span> <span class="type"><a href="qmouseevent.html">QMouseEvent</a></span> <span class="operator">*</span>e) { <span class="type"><a href="qstring.html">QString</a></span> type; <span class="keyword">switch</span> (e<span class="operator">-</span><span class="operator">&gt;</span>type()) { <span class="keyword">case</span> <span class="type"><a href="qevent.html">QEvent</a></span><span class="operator">::</span>MouseButtonPress: type <span class="operator">=</span> <span class="string">&quot;mousedown&quot;</span>; <span class="keyword">break</span>; <span class="keyword">case</span> <span class="type"><a href="qevent.html">QEvent</a></span><span class="operator">::</span>MouseButtonRelease: type <span class="operator">=</span> <span class="string">&quot;mouseup&quot;</span>; <span class="keyword">break</span>; <span class="keyword">case</span> <span class="type"><a href="qevent.html">QEvent</a></span><span class="operator">::</span>MouseMove: type <span class="operator">=</span> <span class="string">&quot;mousemove&quot;</span>; <span class="keyword">break</span>; <span class="keyword">default</span>: <span class="keyword">break</span>; } <span class="keyword">if</span> (type<span class="operator">.</span>isEmpty()) <span class="keyword">return</span>; <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> handlerObject; <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> handler <span class="operator">=</span> eventHandler(canvas<span class="operator">,</span> type<span class="operator">,</span> <span class="operator">&amp;</span>handlerObject); <span class="keyword">if</span> (<span class="operator">!</span>handler<span class="operator">.</span>isFunction()) <span class="keyword">return</span>; <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> scriptEvent <span class="operator">=</span> newFakeDomEvent(type<span class="operator">,</span> toWrapper(canvas)); <span class="comment">// MouseEvent</span> scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;screenX&quot;</span><span class="operator">,</span> e<span class="operator">-</span><span class="operator">&gt;</span>globalX()<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;screenY&quot;</span><span class="operator">,</span> e<span class="operator">-</span><span class="operator">&gt;</span>globalY()<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;clientX&quot;</span><span class="operator">,</span> e<span class="operator">-</span><span class="operator">&gt;</span>x()<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;clientY&quot;</span><span class="operator">,</span> e<span class="operator">-</span><span class="operator">&gt;</span>y()<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;layerX&quot;</span><span class="operator">,</span> e<span class="operator">-</span><span class="operator">&gt;</span>x()<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;layerY&quot;</span><span class="operator">,</span> e<span class="operator">-</span><span class="operator">&gt;</span>y()<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;pageX&quot;</span><span class="operator">,</span> e<span class="operator">-</span><span class="operator">&gt;</span>x()<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;pageY&quot;</span><span class="operator">,</span> e<span class="operator">-</span><span class="operator">&gt;</span>y()<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;altKey&quot;</span><span class="operator">,</span> (e<span class="operator">-</span><span class="operator">&gt;</span>modifiers() <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>AltModifier) <span class="operator">!</span><span class="operator">=</span> <span class="number">0</span><span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;ctrlKey&quot;</span><span class="operator">,</span> (e<span class="operator">-</span><span class="operator">&gt;</span>modifiers() <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>ControlModifier) <span class="operator">!</span><span class="operator">=</span> <span class="number">0</span><span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;metaKey&quot;</span><span class="operator">,</span> (e<span class="operator">-</span><span class="operator">&gt;</span>modifiers() <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>MetaModifier) <span class="operator">!</span><span class="operator">=</span> <span class="number">0</span><span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;shiftKey&quot;</span><span class="operator">,</span> (e<span class="operator">-</span><span class="operator">&gt;</span>modifiers() <span class="operator">&amp;</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>ShiftModifier) <span class="operator">!</span><span class="operator">=</span> <span class="number">0</span><span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); <span class="type">int</span> button <span class="operator">=</span> <span class="number">0</span>; <span class="keyword">if</span> (e<span class="operator">-</span><span class="operator">&gt;</span>button() <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>RightButton) button <span class="operator">=</span> <span class="number">2</span>; <span class="keyword">else</span> <span class="keyword">if</span> (e<span class="operator">-</span><span class="operator">&gt;</span>button() <span class="operator">=</span><span class="operator">=</span> <span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>MidButton) button <span class="operator">=</span> <span class="number">1</span>; scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;button&quot;</span><span class="operator">,</span> button); scriptEvent<span class="operator">.</span>setProperty(<span class="string">&quot;relatedTarget&quot;</span><span class="operator">,</span> m_engine<span class="operator">-</span><span class="operator">&gt;</span>nullValue()<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); handler<span class="operator">.</span>call(handlerObject<span class="operator">,</span> <span class="type">QScriptValueList</span>() <span class="operator">&lt;</span><span class="operator">&lt;</span> scriptEvent); maybeEmitScriptError(); }</pre> <p>The handleEvent() function determines if there exists a handler for the given event in the environment, and if so, invokes that handler. Since the script expects a DOM event, the Qt C++ event must be converted to a DOM event before it is passed to the script. This mapping is relatively straightforward, but again, we only implement a subset of the full DOM API; just enough to get most scripts to work.</p> <pre class="cpp"> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> Environment<span class="operator">::</span>newFakeDomEvent(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>type<span class="operator">,</span> <span class="keyword">const</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> <span class="operator">&amp;</span>target) { <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> e <span class="operator">=</span> m_engine<span class="operator">-</span><span class="operator">&gt;</span>newObject(); <span class="comment">// Event</span> e<span class="operator">.</span>setProperty(<span class="string">&quot;type&quot;</span><span class="operator">,</span> type<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); e<span class="operator">.</span>setProperty(<span class="string">&quot;bubbles&quot;</span><span class="operator">,</span> <span class="keyword">true</span><span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); e<span class="operator">.</span>setProperty(<span class="string">&quot;cancelable&quot;</span><span class="operator">,</span> <span class="keyword">false</span><span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); e<span class="operator">.</span>setProperty(<span class="string">&quot;target&quot;</span><span class="operator">,</span> target<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); e<span class="operator">.</span>setProperty(<span class="string">&quot;currentTarget&quot;</span><span class="operator">,</span> target<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); e<span class="operator">.</span>setProperty(<span class="string">&quot;eventPhase&quot;</span><span class="operator">,</span> <span class="number">3</span>); <span class="comment">// bubbling</span> e<span class="operator">.</span>setProperty(<span class="string">&quot;timeStamp&quot;</span><span class="operator">,</span> <span class="type"><a href="qdatetime.html">QDateTime</a></span><span class="operator">::</span>currentDateTime()<span class="operator">.</span>toTime_t()); <span class="comment">// UIEvent</span> e<span class="operator">.</span>setProperty(<span class="string">&quot;detail&quot;</span><span class="operator">,</span> <span class="number">0</span><span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); e<span class="operator">.</span>setProperty(<span class="string">&quot;view&quot;</span><span class="operator">,</span> m_engine<span class="operator">-</span><span class="operator">&gt;</span>globalObject()<span class="operator">,</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span><span class="operator">::</span>ReadOnly); <span class="keyword">return</span> e; }</pre> <p>The newFakeDomEvent() function is a helper function that creates a new script object and initializes it with default values for the attributes defined in the DOM Event and DOM UIEvent interfaces.</p> <pre class="cpp"> <span class="keyword">class</span> Document : <span class="keyword">public</span> <span class="type"><a href="qobject.html">QObject</a></span> { Q_OBJECT <span class="keyword">public</span>: Document(Environment <span class="operator">*</span>env); <span class="operator">~</span>Document(); <span class="keyword">public</span> <span class="keyword">slots</span>: <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> getElementById(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>id) <span class="keyword">const</span>; <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> getElementsByTagName(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>name) <span class="keyword">const</span>; <span class="comment">// EventTarget</span> <span class="type">void</span> addEventListener(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>type<span class="operator">,</span> <span class="keyword">const</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> <span class="operator">&amp;</span>listener<span class="operator">,</span> <span class="type">bool</span> useCapture); };</pre> <p>The Document class defines two slots that become available to scripts: getElementById() and getElementsByTagName(). When the tag name is &quot;canvas&quot;, getElementsByTagName() will return a list of all canvas objects that are registered in the environment.</p> <a name="the-application-window"></a> <h2>The Application Window</h2> <pre class="cpp"> Window<span class="operator">::</span>Window(<span class="type"><a href="qwidget.html">QWidget</a></span> <span class="operator">*</span>parent) : <span class="type"><a href="qwidget.html">QWidget</a></span>(parent) <span class="preprocessor">#ifndef QT_NO_SCRIPTTOOLS</span> <span class="operator">,</span> m_debugger(<span class="number">0</span>)<span class="operator">,</span> m_debugWindow(<span class="number">0</span>) <span class="preprocessor">#endif</span> { m_env <span class="operator">=</span> <span class="keyword">new</span> Environment(<span class="keyword">this</span>); <span class="type"><a href="qobject.html">QObject</a></span><span class="operator">::</span>connect(m_env<span class="operator">,</span> SIGNAL(scriptError(<span class="type"><a href="qscriptvalue.html">QScriptValue</a></span>))<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(reportScriptError(<span class="type"><a href="qscriptvalue.html">QScriptValue</a></span>))); Context2D <span class="operator">*</span>context <span class="operator">=</span> <span class="keyword">new</span> Context2D(<span class="keyword">this</span>); context<span class="operator">-</span><span class="operator">&gt;</span>setSize(<span class="number">150</span><span class="operator">,</span> <span class="number">150</span>); m_canvas <span class="operator">=</span> <span class="keyword">new</span> QContext2DCanvas(context<span class="operator">,</span> m_env<span class="operator">,</span> <span class="keyword">this</span>); m_canvas<span class="operator">-</span><span class="operator">&gt;</span>setFixedSize(context<span class="operator">-</span><span class="operator">&gt;</span>size()); m_canvas<span class="operator">-</span><span class="operator">&gt;</span>setObjectName(<span class="string">&quot;tutorial&quot;</span>); m_env<span class="operator">-</span><span class="operator">&gt;</span>addCanvas(m_canvas);</pre> <p>The Window constructor creates an Environment object and connects to its scriptError() signal. It then creates a Context2D object, and a QContext2DCanvas widget to hold it. The canvas widget is given the name <tt>tutorial</tt>, and added to the environment; scripts can access the canvas by e.g&#x2e; <tt>document.getElementById('tutorial')</tt>.</p> <pre class="cpp"> <span class="type"><a href="qdir.html">QDir</a></span> dir(scriptsDir()); <span class="type"><a href="qfileinfo.html#QFileInfoList-typedef">QFileInfoList</a></span> entries <span class="operator">=</span> dir<span class="operator">.</span>entryInfoList(<span class="type"><a href="qstringlist.html">QStringList</a></span>() <span class="operator">&lt;</span><span class="operator">&lt;</span> <span class="string">&quot;*.js&quot;</span>); <span class="keyword">for</span> (<span class="type">int</span> i <span class="operator">=</span> <span class="number">0</span>; i <span class="operator">&lt;</span> entries<span class="operator">.</span>size(); <span class="operator">+</span><span class="operator">+</span>i) m_view<span class="operator">-</span><span class="operator">&gt;</span>addItem(entries<span class="operator">.</span>at(i)<span class="operator">.</span>fileName()); connect(m_view<span class="operator">,</span> SIGNAL(currentItemChanged(<span class="type"><a href="qlistwidgetitem.html">QListWidgetItem</a></span><span class="operator">*</span><span class="operator">,</span><span class="type"><a href="qlistwidgetitem.html">QListWidgetItem</a></span><span class="operator">*</span>))<span class="operator">,</span> <span class="keyword">this</span><span class="operator">,</span> SLOT(selectScript(<span class="type"><a href="qlistwidgetitem.html">QListWidgetItem</a></span><span class="operator">*</span>)));</pre> <p>The window contains a list widget that is populated with available scripts (read from a <tt>scripts/</tt> folder).</p> <pre class="cpp"> <span class="type">void</span> Window<span class="operator">::</span>selectScript(<span class="type"><a href="qlistwidgetitem.html">QListWidgetItem</a></span> <span class="operator">*</span>item) { <span class="type"><a href="qstring.html">QString</a></span> fileName <span class="operator">=</span> item<span class="operator">-</span><span class="operator">&gt;</span>text(); runScript(fileName<span class="operator">,</span> <span class="comment">/*debug=*/</span><span class="keyword">false</span>); }</pre> <p>When an item is selected, the corresponding script is evaluated in the environment.</p> <pre class="cpp"> <span class="type">void</span> Window<span class="operator">::</span>runInDebugger() { <span class="type"><a href="qlistwidgetitem.html">QListWidgetItem</a></span> <span class="operator">*</span>item <span class="operator">=</span> m_view<span class="operator">-</span><span class="operator">&gt;</span>currentItem(); <span class="keyword">if</span> (item) { <span class="type"><a href="qstring.html">QString</a></span> fileName <span class="operator">=</span> item<span class="operator">-</span><span class="operator">&gt;</span>text(); runScript(fileName<span class="operator">,</span> <span class="comment">/*debug=*/</span><span class="keyword">true</span>); } }</pre> <p>When the &quot;Run in Debugger&quot; button is clicked, the Qt Script debugger will automatically be invoked when the first statement of the script is reached. This enables the user to inspect the scripting environment and control further execution of the script; e.g&#x2e; he can single-step through the script and/or set breakpoints. It is also possible to enter script statements in the debugger's console widget, e.g&#x2e; to perform custom Context2D drawing operations, interactively.</p> <pre class="cpp"> <span class="type">void</span> Window<span class="operator">::</span>runScript(<span class="keyword">const</span> <span class="type"><a href="qstring.html">QString</a></span> <span class="operator">&amp;</span>fileName<span class="operator">,</span> <span class="type">bool</span> debug) { <span class="type"><a href="qfile.html">QFile</a></span> file(scriptsDir() <span class="operator">+</span> <span class="string">&quot;/&quot;</span> <span class="operator">+</span> fileName); file<span class="operator">.</span>open(<span class="type"><a href="qiodevice.html">QIODevice</a></span><span class="operator">::</span>ReadOnly); <span class="type"><a href="qstring.html">QString</a></span> contents <span class="operator">=</span> file<span class="operator">.</span>readAll(); file<span class="operator">.</span>close(); m_env<span class="operator">-</span><span class="operator">&gt;</span>reset(); <span class="preprocessor">#ifndef QT_NO_SCRIPTTOOLS</span> <span class="keyword">if</span> (debug) { <span class="keyword">if</span> (<span class="operator">!</span>m_debugger) { m_debugger <span class="operator">=</span> <span class="keyword">new</span> <span class="type"><a href="qscriptenginedebugger.html">QScriptEngineDebugger</a></span>(<span class="keyword">this</span>); m_debugWindow <span class="operator">=</span> m_debugger<span class="operator">-</span><span class="operator">&gt;</span>standardWindow(); m_debugWindow<span class="operator">-</span><span class="operator">&gt;</span>setWindowModality(<span class="type"><a href="qt.html">Qt</a></span><span class="operator">::</span>ApplicationModal); m_debugWindow<span class="operator">-</span><span class="operator">&gt;</span>resize(<span class="number">1280</span><span class="operator">,</span> <span class="number">704</span>); } m_debugger<span class="operator">-</span><span class="operator">&gt;</span>attachTo(m_env<span class="operator">-</span><span class="operator">&gt;</span>engine()); m_debugger<span class="operator">-</span><span class="operator">&gt;</span>action(<span class="type"><a href="qscriptenginedebugger.html">QScriptEngineDebugger</a></span><span class="operator">::</span>InterruptAction)<span class="operator">-</span><span class="operator">&gt;</span>trigger(); } <span class="keyword">else</span> { <span class="keyword">if</span> (m_debugger) m_debugger<span class="operator">-</span><span class="operator">&gt;</span>detach(); } <span class="preprocessor">#else</span> Q_UNUSED(debug); <span class="preprocessor">#endif</span> <span class="type"><a href="qscriptvalue.html">QScriptValue</a></span> ret <span class="operator">=</span> m_env<span class="operator">-</span><span class="operator">&gt;</span>evaluate(contents<span class="operator">,</span> fileName); <span class="preprocessor">#ifndef QT_NO_SCRIPTTOOLS</span> <span class="keyword">if</span> (m_debugWindow) m_debugWindow<span class="operator">-</span><span class="operator">&gt;</span>hide(); <span class="preprocessor">#endif</span> <span class="keyword">if</span> (ret<span class="operator">.</span>isError()) reportScriptError(ret); }</pre> <p>If the evaluation of a script causes an uncaught exception, the Qt Script debugger will automatically be invoked; this enables the user to get an idea of what went wrong.</p> </div> <!-- @@@script/context2d --> <div class="ft"> <span></span> </div> </div> <div class="footer"> <p> <acronym title="Copyright">&copy;</acronym> 2008-2011 Nokia Corporation and/or its subsidiaries. Nokia, Qt and their respective logos are trademarks of Nokia Corporation in Finland and/or other countries worldwide.</p> <p> All other trademarks are property of their respective owners. <a title="Privacy Policy" href="http://qt.nokia.com/about/privacy-policy">Privacy Policy</a></p> <br /> <p> Licensees holding valid Qt Commercial licenses may use this document in accordance with the Qt Commercial License Agreement provided with the Software or, alternatively, in accordance with the terms contained in a written agreement between you and Nokia.</p> <p> Alternatively, this document may be used under the terms of the <a href="http://www.gnu.org/licenses/fdl.html">GNU Free Documentation License version 1.3</a> as published by the Free Software Foundation.</p> </div> </body> </html>
kobolabs/qt-everywhere-4.8.0
doc/html/script-context2d.html
HTML
lgpl-2.1
78,111
<?php // $Header: /cvsroot/tikiwiki/tiki/tiki-admin_include_metatags.php,v 1.1.10.5 2007/03/02 12:23:22 luciash Exp $ // Copyright (c) 2002-2007, Luis Argerich, Garland Foster, Eduardo Polidor, et. al. // All Rights Reserved. See copyright.txt for details and a complete list of authors. // Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See license.txt for details. //this script may only be included - so its better to die if called directly. if(strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) { header("location: index.php"); exit; } if(isset($_REQUEST["metatags"])) { $tikilib->set_preference('metatag_keywords', $_REQUEST["metatag_keywords"]); $smarty->assign("metatag_keywords", $_REQUEST["metatag_keywords"]); $tikilib->set_preference('metatag_description', $_REQUEST["metatag_description"]); $smarty->assign("metatag_description", $_REQUEST["metatag_description"]); $tikilib->set_preference('metatag_author', $_REQUEST["metatag_author"]); $smarty->assign("metatag_author", $_REQUEST["metatag_author"]); $tikilib->set_preference('metatag_geoposition', $_REQUEST["metatag_geoposition"]); $smarty->assign("metatag_geoposition", $_REQUEST["metatag_geoposition"]); $tikilib->set_preference('metatag_georegion', $_REQUEST["metatag_georegion"]); $smarty->assign("metatag_georegion", $_REQUEST["metatag_georegion"]); $tikilib->set_preference('metatag_geoplacename', $_REQUEST["metatag_geoplacename"]); $smarty->assign("metatag_geoplacename", $_REQUEST["metatag_geoplacename"]); $tikilib->set_preference('metatag_robots', $_REQUEST["adm_metatag_robots"]); $smarty->assign("adm_metatag_robots", $_REQUEST["adm_metatag_robots"]); $tikilib->set_preference('metatag_revisitafter', $_REQUEST["metatag_revisitafter"]); $smarty->assign("metatag_revisitafter", $_REQUEST["metatag_revisitafter"]); } else { $smarty->assign("metatag_keywords", $tikilib->get_preference("metatag_keywords", '')); $smarty->assign("metatag_description", $tikilib->get_preference("metatag_description", '')); $smarty->assign("metatag_author", $tikilib->get_preference("metatag_author", '')); $smarty->assign("metatag_geoposition", $tikilib->get_preference("metatag_geoposition", '')); $smarty->assign("metatag_georegion", $tikilib->get_preference("metatag_georegion", '')); $smarty->assign("metatag_geoplacename", $tikilib->get_preference("metatag_geoplacename", '')); $smarty->assign("adm_metatag_robots", $tikilib->get_preference("metatag_robots", '')); $smarty->assign("metatag_revisitafter", $tikilib->get_preference("metatag_revisitafter", '')); } ?>
marcelosoaressouza/estudiolivre
tiki-admin_include_metatags.php
PHP
lgpl-2.1
2,605
/****************************************************************************** * This file is part of the Gluon Development Platform * Copyright (c) 2009 Dan Leinir Turthra Jensen <admin@leinir.dk> * Copyright (c) 2009 Kim Jung Nissen <jungnissen@gmail.com> * * This library 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 library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "btcharacter.h" #include <QtCore/QDebug> #include <QtCore/QXmlStreamWriter> #include <QtCore/QFileInfo> #include <sys/stat.h> using namespace GluonSmarts; btCharacter::btCharacter(QObject* parent) : QObject(parent) , m_thinksBeforeSaving(10) , m_thinksDone(0) , m_behaviortree(0) , m_position(Eigen::Vector3f(0,0,0)) , m_orientation(Eigen::Quaternionf::Identity()) , m_perception(new btPerception(this)) { m_nodesStatusQueue.enqueue(btNode::None); } btCharacter::~btCharacter() { clearExecution(); } void btCharacter::setBehaviorTree(btNode* behaviorTree) { clearExecution(); m_behaviortree = behaviorTree; QStack<btNode*>* currentNodeStack = new QStack<btNode*>(); currentNodeStack->push(m_behaviortree); QStack<int> currentChildStack = QStack<int>(); currentChildStack.push(0); m_currentChildStackQueue.enqueue(currentChildStack); QPair<QStack<btNode*>*, QStack<btNode*>*> pair; pair.first = currentNodeStack; pair.second = NULL; m_currentNodeStackQueue.enqueue(pair); m_nodesProbabilities.clear(); initProbabilityHash(m_behaviortree); btBrain * brain = qobject_cast<btBrain*>(m_behaviortree->parent()); setFile(brain->getFile()); } void btCharacter::think() { //local variables used in think btProbSelectorNode * probSelector = NULL; btParallelNode * parallel = NULL; btNode* currentParent = NULL; QStack<QList<ProbNode*> > visitedProbChildrenStack; QStack<btNode*>* currentNodeStack = NULL; QStack<int> currentChildStack; btNode::status nodeStatus; int currentChildIndex = 0; QPair<QStack<btNode*>*, QStack<btNode*>*> currentChildParentStackPair; //retrieve a execution stack currentChildParentStackPair = m_currentNodeStackQueue.dequeue(); currentNodeStack = currentChildParentStackPair.first; currentChildStack = m_currentChildStackQueue.dequeue(); nodeStatus = m_nodesStatusQueue.dequeue(); //retrieve the executing node btNode* currentNode = currentNodeStack->top(); //check if it s possible to set parent, and set it if possible if(currentNodeStack->count() > 1) { currentParent = currentNodeStack->at(currentNodeStack->count() - 2); } //check if it s possible to set current child, and set it if possible if(currentChildStack.count() > 0) { currentChildIndex = currentChildStack.pop(); } if (QString(currentNode->metaObject()->className()) == "btProbSelectorNode") { //if the current node is a probselector, cast it probSelector = qobject_cast<btProbSelectorNode*>(currentNode); //and set the probnodes if we have run it before if(m_visitedProbChildrenHash.contains(currentNodeStack)) { probSelector->setVisitedProbNodes(m_visitedProbChildrenHash[currentNodeStack].pop()); } } else if (QString(currentNode->metaObject()->className()) == "btParallelNode") { //if the current node is a parallel, cast it parallel = qobject_cast<btParallelNode*>(currentNode); //if it is the first time, create execution stacks, child stacks etc. for each child and add them to the queue if(nodeStatus == btNode::None) { QList<btNode::status>* childStatus = new QList<btNode::status>(); for(int i = 0; i < parallel->childCount(); i++) { QStack<btNode*>* newStack = new QStack<btNode*>(); newStack->push(parallel); newStack->push(parallel->child(i)); QPair<QStack<btNode*>*, QStack<btNode*>*> pair; pair.first = newStack; pair.second = currentNodeStack; m_currentNodeStackQueue.enqueue(pair); childStatus->append(btNode::Running); m_nodesStatusQueue.enqueue(btNode::None); m_parallelNodeStatusHash.insert(newStack, childStatus); QStack<int> childStack = QStack<int>(); childStack.push(0); m_currentChildStackQueue.append(childStack); } m_parallelNodeStatusHash.insert(currentNodeStack, childStatus); nodeStatus = btNode::Running; } //check if termination conditions is fulfilled, return btNode::Running if not parallel->setRunningNodesStatus(m_parallelNodeStatusHash.value(currentNodeStack)); nodeStatus = parallel->conditionsFulfilled(); } //restore the execution state of the current executing node currentNode->setCurrentChildIndex(currentChildIndex); currentNode->setCurrentChildStatus(nodeStatus); currentNode->setParentNode(currentParent); //qDebug() << currentNode->name(); //run the node nodeStatus = currentNode->run(this); //handle the status messsage switch (nodeStatus) { case btNode::RunningChild: qDebug() << currentNode->name() << ": running child"; //when running child, push the child and child index onto the stacks currentNodeStack->push(currentNode->currentChild()); currentChildStack.push(currentNode->currentChildIndex()); currentChildStack.push(0); //enqueue the stacks and status m_currentNodeStackQueue.enqueue(currentChildParentStackPair); m_currentChildStackQueue.enqueue(currentChildStack); m_nodesStatusQueue.enqueue(btNode::None); //if current node is a probselector, then save the probnodes if(probSelector) { m_visitedProbChildrenHash[currentNodeStack].push(probSelector->visitedProbNodes()); } //add to runs m_nodesProbabilities[currentNode->currentChild()].runs++; break; case btNode::Failed: case btNode::Succeeded: if(nodeStatus == btNode::Failed) { qDebug() << currentNode->name() << ": failed"; } else { qDebug() << currentNode->name() << ": succeeded"; } //calculate probs if(nodeStatus == btNode::Succeeded) { probability * p = & m_nodesProbabilities[currentNode]; p->succeeds++; if(p->runs == 0) p->runs++; p->prob = (double)(p->succeeds / p->runs); } //when the node fails or succeeds if(currentNodeStack->count() > 1) { //if there is more than one node in the stack, pop it currentNodeStack->pop(); } else { //else if count == 0 then push a 0 on it if(currentChildStack.count() == 0) { currentChildStack.push(0); } //if the node is the root, reset status if(currentNode == m_behaviortree) nodeStatus = btNode::None; } if(QString(currentNode->metaObject()->className()) == "btProbSelectorNode") { //if probselector then remove the probnodes for this stack if(m_visitedProbChildrenHash[currentNodeStack].count() == 0) m_visitedProbChildrenHash.remove(currentNodeStack); } if(currentParent != NULL && QString(currentParent->metaObject()->className()) == "btParallelNode") { //if the parent is a parallel, set the status for that parallel. parallel = qobject_cast<btParallelNode*>(currentParent); QList<btNode::status>* m_parallelNodeStatus = m_parallelNodeStatusHash.value(currentNodeStack); m_parallelNodeStatus->replace(parallel->childNodeIndex(currentNode), nodeStatus); m_parallelNodeStatusHash.remove(currentNodeStack, m_parallelNodeStatus); if(m_parallelNodeStatusHash.count(currentNodeStack) == 0) { //remove the stack if there is no other node status in the hash delete currentNodeStack; currentNodeStack = NULL; } } if(QString(currentNode->metaObject()->className()) == "btParallelNode") { //if parallel stop the children and remove the node status list from the hash stopParallelExecution(currentNode, currentNodeStack); if(currentNodeStack) { QList<btNode::status>* status = m_parallelNodeStatusHash.value(currentNodeStack); m_parallelNodeStatusHash.remove(currentNodeStack, m_parallelNodeStatusHash.value(currentNodeStack)); delete status; } } if(currentNodeStack) { //if node stack is not deleted, enqueue it again m_currentNodeStackQueue.enqueue(currentChildParentStackPair); m_currentChildStackQueue.enqueue(currentChildStack); m_nodesStatusQueue.enqueue(nodeStatus); } break; case btNode::Running: qDebug() << currentNode->name() << ": still running"; //enqueue stack and stuff currentChildIndex = currentNode->currentChildIndex(); m_currentNodeStackQueue.enqueue(currentChildParentStackPair); currentChildStack.push(currentChildIndex); m_currentChildStackQueue.enqueue(currentChildStack); m_nodesStatusQueue.enqueue(nodeStatus); break; } if(m_thinksBeforeSaving == m_thinksDone) { saveProbabilities(); m_thinksDone = 0; } else { m_thinksDone++; } } void btCharacter::stopParallelExecution(btNode * currentNode, QStack<btNode*>* parentStack) { qDebug() <<"stopping parallel"; QStack<QPair<QStack<btNode*>*, QStack<btNode*>*> > * nodeStacksForTermination = new QStack<QPair<QStack<btNode*>*, QStack<btNode*>*> >(); findParallelsForTermination(currentNode, parentStack, nodeStacksForTermination); while(!nodeStacksForTermination->empty()) { int counter = m_currentNodeStackQueue.count(); Q_UNUSED(counter) QPair<QStack<btNode*>*, QStack<btNode*>*> terminationPair = nodeStacksForTermination->pop(); int index = m_currentNodeStackQueue.indexOf(terminationPair); m_currentNodeStackQueue.removeOne(terminationPair); qDebug() <<"stopping stack"; QList<btNode::status>* status = m_parallelNodeStatusHash.value(terminationPair.first); QStack<btNode*>* tmp = terminationPair.first; while (m_parallelNodeStatusHash.contains(tmp)) { m_parallelNodeStatusHash.remove(tmp, m_parallelNodeStatusHash.value(tmp)); } m_visitedProbChildrenHash.remove(tmp); if(QString(tmp->last()->metaObject()->className()) == QString("btParallelNode")) { delete status; } delete tmp; m_nodesStatusQueue.removeAt(index); m_currentChildStackQueue.removeAt(index); } qDebug() << "stopped parallel"; } void btCharacter::findParallelsForTermination(btNode * currentNode, QStack<btNode*>* parentStack, QStack<QPair<QStack<btNode*>*, QStack<btNode*>*> > * stack) { for(int i = 0; i < m_currentNodeStackQueue.count(); i++) { QPair<QStack<btNode*>*, QStack<btNode*>*> pair = m_currentNodeStackQueue.value(i); if(pair.first->front() == currentNode && pair.second == parentStack) { qDebug() << "found " << pair.first->last()->name(); stack->push(pair); if(QString(pair.first->top()->metaObject()->className()) == QString("btParallelNode")) { findParallelsForTermination(pair.first->last(), pair.first, stack); } } } } void btCharacter::clearExecution() { for (int i = 0; i < m_currentNodeStackQueue.count(); i++) { delete m_currentNodeStackQueue.at(i).first; } m_currentNodeStackQueue.clear(); m_currentChildStackQueue.clear(); qDeleteAll(m_visitedProbChildrenHash.keys()); m_visitedProbChildrenHash.clear(); qDeleteAll(m_parallelNodeStatusHash.values()); qDeleteAll(m_parallelNodeStatusHash.keys()); m_parallelNodeStatusHash.clear(); } Eigen::Vector3f btCharacter::position() const { return m_position; } void btCharacter::setPosition(const Eigen::Vector3f& newPosition) { m_position = newPosition; } Eigen::Quaternionf btCharacter::orientation() const { return m_orientation; } void btCharacter::setOrientation(const Eigen::Quaternionf& newOrientation) { m_orientation = newOrientation; } btPerception* btCharacter::perception() { return m_perception; } void btCharacter::saveProbabilities() { QString m_xmlData = ""; QFile file(m_filename); QXmlStreamWriter* xmlWriter = new QXmlStreamWriter(&m_xmlData); xmlWriter->setAutoFormatting(true); if(!file.exists()) xmlWriter->writeStartDocument("1.0"); saveNodeProbabilities(m_behaviortree, xmlWriter); file.open(QIODevice::Append | QIODevice::Text); QByteArray byteFileContents(m_xmlData.toUtf8()); file.write(byteFileContents); file.close(); } void btCharacter::initProbabilityHash(btNode * node) { m_nodesProbabilities[node] = probability(); for(int i = 0; i < node->childCount(); i++) { initProbabilityHash(node->child(i)); } } void btCharacter::saveNodeProbabilities(btNode * node, QXmlStreamWriter * xmlWriter) { xmlWriter->writeStartElement("behaviornode"); xmlWriter->writeAttribute("name", node->name()); xmlWriter->writeAttribute("description", node->description()); xmlWriter->writeAttribute("probability", QString("%1").arg(m_nodesProbabilities[node].prob)); int count = node->childCount(); for (int i = 0; i < count; i++) { saveNodeProbabilities(node->child(i), xmlWriter); } xmlWriter->writeEndElement(); } void btCharacter::setFile(QString file) { QFileInfo info(file); QString path = info.path(); QString name = info.fileName(); int insert = name.lastIndexOf(".") - 1; m_filename = name.insert(insert, "-probabilities"); }
KDE/gluon
smarts/lib/btcharacter.cpp
C++
lgpl-2.1
14,036
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library 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 library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.asic.cades.timestamp.asice; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Test; import eu.europa.esig.dss.asic.cades.ASiCWithCAdESSignatureParameters; import eu.europa.esig.dss.asic.cades.ASiCWithCAdESTimestampParameters; import eu.europa.esig.dss.asic.cades.signature.ASiCWithCAdESService; import eu.europa.esig.dss.diagnostic.DiagnosticData; import eu.europa.esig.dss.diagnostic.TimestampWrapper; import eu.europa.esig.dss.diagnostic.jaxb.XmlDigestMatcher; import eu.europa.esig.dss.enumerations.ASiCContainerType; import eu.europa.esig.dss.enumerations.DigestMatcherType; import eu.europa.esig.dss.enumerations.SignatureLevel; import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.DSSException; import eu.europa.esig.dss.model.InMemoryDocument; import eu.europa.esig.dss.model.MimeType; import eu.europa.esig.dss.test.signature.PKIFactoryAccess; import eu.europa.esig.dss.utils.Utils; import eu.europa.esig.dss.validation.SignedDocumentValidator; import eu.europa.esig.dss.validation.reports.Reports; import eu.europa.esig.validationreport.enums.ObjectType; import eu.europa.esig.validationreport.jaxb.POEProvisioningType; import eu.europa.esig.validationreport.jaxb.SignatureValidationReportType; import eu.europa.esig.validationreport.jaxb.SignerInformationType; import eu.europa.esig.validationreport.jaxb.ValidationConstraintsEvaluationReportType; import eu.europa.esig.validationreport.jaxb.ValidationObjectType; import eu.europa.esig.validationreport.jaxb.ValidationReportType; import eu.europa.esig.validationreport.jaxb.ValidationStatusType; public class ASiCETimestampMultiFilesTest extends PKIFactoryAccess { @Test public void test() throws IOException { ASiCWithCAdESService service = new ASiCWithCAdESService(getCompleteCertificateVerifier()); service.setTspSource(getAlternateGoodTsa()); DSSDocument documentToSign = new InMemoryDocument("Hello World !".getBytes(), "test.text", MimeType.TEXT); DSSDocument documentToSign2 = new InMemoryDocument("Bye World !".getBytes(), "test2.text", MimeType.TEXT); List<DSSDocument> docs = Arrays.asList(documentToSign, documentToSign2); ASiCWithCAdESTimestampParameters timestampParameters = new ASiCWithCAdESTimestampParameters(); timestampParameters.aSiC().setContainerType(ASiCContainerType.ASiC_E); DSSDocument archiveWithTimestamp = service.timestamp(docs, timestampParameters); assertNotNull(archiveWithTimestamp); // archiveWithTimestamp.save("target/test-multi-files.asice"); SignedDocumentValidator validator = SignedDocumentValidator.fromDocument(archiveWithTimestamp); validator.setCertificateVerifier(getOfflineCertificateVerifier()); Reports reports = validator.validateDocument(); // reports.print(); assertNotNull(reports); DiagnosticData diagnosticData = reports.getDiagnosticData(); assertNotNull(diagnosticData.getContainerInfo()); assertEquals(ASiCContainerType.ASiC_E.getReadable(), diagnosticData.getContainerInfo().getContainerType()); assertEquals(0, diagnosticData.getSignatureIdList().size()); assertEquals(1, diagnosticData.getTimestampIdList().size()); assertEquals(0, diagnosticData.getAllRevocationData().size()); // offline TimestampWrapper timestampWrapper = diagnosticData.getTimestampList().get(0); assertTrue(timestampWrapper.isMessageImprintDataFound()); assertTrue(timestampWrapper.isMessageImprintDataIntact()); assertTrue(timestampWrapper.isSignatureIntact()); assertTrue(timestampWrapper.isSignatureValid()); List<XmlDigestMatcher> digestMatchers = timestampWrapper.getDigestMatchers(); assertEquals(3, digestMatchers.size()); int messageImprintCounter = 0; int filesCounter = 0; for (XmlDigestMatcher xmlDigestMatcher : digestMatchers) { assertNotNull(xmlDigestMatcher.getName()); if (DigestMatcherType.MESSAGE_IMPRINT == xmlDigestMatcher.getType()) { messageImprintCounter++; } else if (DigestMatcherType.MANIFEST_ENTRY == xmlDigestMatcher.getType()) { filesCounter++; } else { fail("Not supported " + xmlDigestMatcher); } } assertEquals(1, messageImprintCounter); assertEquals(docs.size(), filesCounter); timestampParameters = new ASiCWithCAdESTimestampParameters(); timestampParameters.aSiC().setContainerType(ASiCContainerType.ASiC_E); archiveWithTimestamp = service.timestamp(archiveWithTimestamp, timestampParameters); // archiveWithTimestamp.save("target/test-multi-files-2-times.asice"); validator = SignedDocumentValidator.fromDocument(archiveWithTimestamp); validator.setCertificateVerifier(getOfflineCertificateVerifier()); reports = validator.validateDocument(); assertNotNull(reports); // reports.print(); diagnosticData = reports.getDiagnosticData(); assertEquals(0, diagnosticData.getSignatureIdList().size()); assertEquals(2, diagnosticData.getTimestampIdList().size()); for (TimestampWrapper timestamp : diagnosticData.getTimestampList()) { assertTrue(timestamp.isMessageImprintDataFound()); assertTrue(timestamp.isMessageImprintDataIntact()); assertTrue(timestamp.isSignatureIntact()); assertTrue(timestamp.isSignatureValid()); } ValidationReportType etsiValidationReportJaxb = reports.getEtsiValidationReportJaxb(); assertNotNull(etsiValidationReportJaxb); boolean noTimestamp = true; for (ValidationObjectType validationObject : etsiValidationReportJaxb.getSignatureValidationObjects().getValidationObject()) { if (ObjectType.TIMESTAMP == validationObject.getObjectType()) { noTimestamp = false; POEProvisioningType poeProvisioning = validationObject.getPOEProvisioning(); assertNotNull(poeProvisioning); assertNotNull(poeProvisioning.getPOETime()); assertTrue(Utils.isCollectionNotEmpty(poeProvisioning.getValidationObject())); SignatureValidationReportType validationReport = validationObject.getValidationReport(); assertNotNull(validationReport); assertNotNull(validationReport.getSignatureQuality()); assertTrue(Utils.isCollectionNotEmpty(validationReport.getSignatureQuality().getSignatureQualityInformation())); SignerInformationType signerInformation = validationReport.getSignerInformation(); assertNotNull(signerInformation); assertNotNull(signerInformation.getSigner()); assertNotNull(signerInformation.getSignerCertificate()); ValidationStatusType timestampValidationStatus = validationReport.getSignatureValidationStatus(); assertNotNull(timestampValidationStatus); assertNotNull(timestampValidationStatus.getMainIndication()); assertNotNull(timestampValidationStatus.getAssociatedValidationReportData()); assertNotNull(timestampValidationStatus.getAssociatedValidationReportData().get(0).getCryptoInformation()); ValidationConstraintsEvaluationReportType validationConstraintsEvaluationReport = validationReport.getValidationConstraintsEvaluationReport(); assertNotNull(validationConstraintsEvaluationReport); assertTrue(Utils.isCollectionNotEmpty(validationConstraintsEvaluationReport.getValidationConstraint())); } } assertFalse(noTimestamp); final DSSDocument docToExtend = archiveWithTimestamp; ASiCWithCAdESSignatureParameters extendParameters = new ASiCWithCAdESSignatureParameters(); extendParameters.aSiC().setContainerType(ASiCContainerType.ASiC_E); extendParameters.setSignatureLevel(SignatureLevel.CAdES_BASELINE_T); DSSException exception = assertThrows(DSSException.class, () -> service.extendDocument(docToExtend, extendParameters)); assertEquals("Unsupported file type", exception.getMessage()); extendParameters.setSignatureLevel(SignatureLevel.CAdES_BASELINE_LT); assertThrows(DSSException.class, () -> service.extendDocument(docToExtend, extendParameters)); extendParameters.setSignatureLevel(SignatureLevel.CAdES_BASELINE_LTA); assertThrows(DSSException.class, () -> service.extendDocument(docToExtend, extendParameters)); } @Override protected String getSigningAlias() { return null; } }
openlimit-signcubes/dss
dss-asic-cades/src/test/java/eu/europa/esig/dss/asic/cades/timestamp/asice/ASiCETimestampMultiFilesTest.java
Java
lgpl-2.1
9,340
/* * * This file is part of XForms. * * XForms 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, or * (at your option) any later version. * * XForms 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 XForms. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SP_POSITIONER_H_ #define SP_POSITIONER_H_ #include "include/forms.h" #include <stdio.h> FL_FORM * positioner_create_spec_form( void ); void positioner_fill_in_spec_form( FL_OBJECT * obj ); void positioner_reread_spec_form( FL_OBJECT * obj ); void positioner_emit_spec_fd_code( FILE * fp, FL_OBJECT * obj ); void positioner_emit_spec_c_code( FILE * fp, FL_OBJECT * obj ); #endif /* * Local variables: * tab-width: 4 * indent-tabs-mode: nil * End: */
OrangeTide/xforms
fdesign/sp_positioner.h
C
lgpl-2.1
1,205
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Qt 4.6: worldtimeclockbuilder.qrc Example File (designer/worldtimeclockbuilder/worldtimeclockbuilder.qrc)</title> <link href="classic.css" rel="stylesheet" type="text/css" /> </head> <body> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td align="left" valign="top" width="32"><a href="http://qt.nokia.com/"><img src="images/qt-logo.png" align="left" border="0" /></a></td> <td width="1">&nbsp;&nbsp;</td><td class="postheader" valign="center"><a href="index.html"><font color="#004faf">Home</font></a>&nbsp;&middot; <a href="classes.html"><font color="#004faf">All&nbsp;Classes</font></a>&nbsp;&middot; <a href="functions.html"><font color="#004faf">All&nbsp;Functions</font></a>&nbsp;&middot; <a href="overviews.html"><font color="#004faf">Overviews</font></a></td></tr></table><h1 class="title">worldtimeclockbuilder.qrc Example File<br /><span class="small-subtitle">designer/worldtimeclockbuilder/worldtimeclockbuilder.qrc</span> </h1> <pre> &lt;!DOCTYPE RCC&gt;&lt;RCC version=&quot;1.0&quot;&gt; &lt;qresource prefix=&quot;/forms&quot;&gt; &lt;file&gt;form.ui&lt;/file&gt; &lt;/qresource&gt; &lt;/RCC&gt;</pre> <p /><address><hr /><div align="center"> <table width="100%" cellspacing="0" border="0"><tr class="address"> <td width="40%" align="left">Copyright &copy; 2010 Nokia Corporation and/or its subsidiary(-ies)</td> <td width="20%" align="center"><a href="trademarks.html">Trademarks</a></td> <td width="40%" align="right"><div align="right">Qt 4.6.2</div></td> </tr></table></div></address></body> </html>
kobolabs/qt-everywhere-opensource-src-4.6.2
doc/html/designer-worldtimeclockbuilder-worldtimeclockbuilder-qrc.html
HTML
lgpl-2.1
1,766
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** 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 Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #ifndef CUSTOMEXECUTABLECONFIGURATIONWIDGET_H #define CUSTOMEXECUTABLECONFIGURATIONWIDGET_H #include <QWidget> QT_BEGIN_NAMESPACE class QCheckBox; class QLineEdit; class QComboBox; class QLabel; class QAbstractButton; QT_END_NAMESPACE namespace Utils { class DetailsWidget; class PathChooser; } namespace QtSupport { class CustomExecutableRunConfiguration; namespace Internal { class CustomExecutableConfigurationWidget : public QWidget { Q_OBJECT public: enum ApplyMode { InstantApply, DelayedApply}; CustomExecutableConfigurationWidget(CustomExecutableRunConfiguration *rc, ApplyMode mode); void apply(); // only used for DelayedApply bool isValid() const; signals: void validChanged(); private slots: void changed(); void executableEdited(); void argumentsEdited(const QString &arguments); void workingDirectoryEdited(); void termToggled(bool); void environmentWasChanged(); private: bool m_ignoreChange; CustomExecutableRunConfiguration *m_runConfiguration; Utils::PathChooser *m_executableChooser; QLineEdit *m_commandLineArgumentsLineEdit; Utils::PathChooser *m_workingDirectory; QCheckBox *m_useTerminalCheck; Utils::DetailsWidget *m_detailsContainer; }; } // namespace Internal } // namespace QtSupport #endif // CUSTOMEXECUTABLECONFIGURATIONWIDGET_H
maui-packages/qt-creator
src/plugins/qtsupport/customexecutableconfigurationwidget.h
C
lgpl-2.1
2,802
/** * \file * * \brief AVR XMEGA Real Time Counter driver definitions * * Copyright (C) 2010 Atmel Corporation. All rights reserved. * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel AVR product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #ifndef DRIVERS_RTC_RTC_H #define DRIVERS_RTC_RTC_H #include <compiler.h> #include <conf_rtc.h> /** * \defgroup rtc_group Real Time Counter (RTC) * * This is a driver implementation for the XMEGA RTC. * * \section rtc_min_alarm_time Minimum allowed alarm time * * If current time is close to a time unit roll over, there is a risk to miss * this when using a value of 0. * * A safe use of this can be in an alarm callback. * * @{ */ /** * \def CONFIG_RTC_COMPARE_INT_LEVEL * \brief Configuration symbol for interrupt level to use on alarm * * Possible values: * - RTC_COMPINTLVL_LO_gc * - RTC_COMPINTLVL_MED_gc * - RTC_COMPINTLVL_HI_gc */ #ifdef __DOXYGEN__ # define CONFIG_RTC_COMPARE_INT_LEVEL #endif /** * \def CONFIG_RTC_OVERFLOW_INT_LEVEL * \brief Configuration symbol for interrupt level to use on overflow * * Possible values: * - RTC_OVFINTLVL_LO_gc * - RTC_OVFINTLVL_MED_gc * - RTC_OVFINTLVL_HI_gc */ #ifdef __DOXYGEN__ # define CONFIG_RTC_OVERFLOW_INT_LEVEL #endif /** * \def CONFIG_RTC_PRESCALER * \brief Configuration symbol for prescaler to use * * Possible values: * - RTC_PRESCALER_DIV1_gc * - RTC_PRESCALER_DIV2_gc * - RTC_PRESCALER_DIV8_gc * - RTC_PRESCALER_DIV16_gc * - RTC_PRESCALER_DIV64_gc * - RTC_PRESCALER_DIV256_gc * - RTC_PRESCALER_DIV1024_gc */ #ifdef __DOXYGEN__ # define CONFIG_RTC_PRESCALER #endif /** * \def CONFIG_RTC_CLOCK_SOURCE * \brief Configuration symbol for which clock source to use * * Possible values: * - CLK_RTCSRC_ULP_gc * - CLK_RTCSRC_TOSC_gc * - CLK_RTCSRC_RCOSC_gc * - CLK_RTCSRC_TOSC32_gc */ #ifdef __DOXYGEN__ # define CONFIG_RTC_CLOCK_SOURCE #endif /** * \brief Callback definition for alarm callback * * \param time The time of the alarm */ typedef void (*rtc_callback_t)(uint32_t time); void rtc_set_callback(rtc_callback_t callback); void rtc_set_time(uint32_t time); uint32_t rtc_get_time(void); void rtc_set_alarm(uint32_t time); bool rtc_alarm_has_triggered(void); /** * \brief Set alarm relative to current time * * \param offset Offset to current time. This is minimum value, so the alarm * might happen at up to one time unit later. See also \ref * rtc_min_alarm_time * * \note Due to errata, this can be unsafe to do shortly after waking up from * sleep. */ static inline void rtc_set_alarm_relative(uint32_t offset) { rtc_set_alarm(rtc_get_time() + offset); } extern void rtc_init(void); //! @} #endif /* RTC_H */
osuar/iarc
Software/Testing/outeradc/code/asf/xmega/drivers/rtc/rtc.h
C
lgpl-2.1
4,297
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_21) on Wed Apr 16 20:33:22 EDT 2014 --> <title>DecorateBiomeEvent.Post (Forge API)</title> <meta name="date" content="2014-04-16"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="DecorateBiomeEvent.Post (Forge API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.Decorate.EventType.html" title="enum in net.minecraftforge.event.terraingen"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.Pre.html" title="class in net.minecraftforge.event.terraingen"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/minecraftforge/event/terraingen/DecorateBiomeEvent.Post.html" target="_top">Frames</a></li> <li><a href="DecorateBiomeEvent.Post.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_classes_inherited_from_class_net.minecraftforge.event.terraingen.DecorateBiomeEvent">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_net.minecraftforge.event.terraingen.DecorateBiomeEvent">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_cpw.mods.fml.common.eventhandler.Event">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">net.minecraftforge.event.terraingen</div> <h2 title="Class DecorateBiomeEvent.Post" class="title">Class DecorateBiomeEvent.Post</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../cpw/mods/fml/common/eventhandler/Event.html" title="class in cpw.mods.fml.common.eventhandler">cpw.mods.fml.common.eventhandler.Event</a></li> <li> <ul class="inheritance"> <li><a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.html" title="class in net.minecraftforge.event.terraingen">net.minecraftforge.event.terraingen.DecorateBiomeEvent</a></li> <li> <ul class="inheritance"> <li>net.minecraftforge.event.terraingen.DecorateBiomeEvent.Post</li> </ul> </li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.html" title="class in net.minecraftforge.event.terraingen">DecorateBiomeEvent</a></dd> </dl> <hr> <br> <pre>public static class <span class="strong">DecorateBiomeEvent.Post</span> extends <a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.html" title="class in net.minecraftforge.event.terraingen">DecorateBiomeEvent</a></pre> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== NESTED CLASS SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="nested_class_summary"> <!-- --> </a> <h3>Nested Class Summary</h3> <ul class="blockList"> <li class="blockList"><a name="nested_classes_inherited_from_class_net.minecraftforge.event.terraingen.DecorateBiomeEvent"> <!-- --> </a> <h3>Nested classes/interfaces inherited from class&nbsp;net.minecraftforge.event.terraingen.<a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.html" title="class in net.minecraftforge.event.terraingen">DecorateBiomeEvent</a></h3> <code><a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.Decorate.html" title="class in net.minecraftforge.event.terraingen">DecorateBiomeEvent.Decorate</a>, <a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.Post.html" title="class in net.minecraftforge.event.terraingen">DecorateBiomeEvent.Post</a>, <a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.Pre.html" title="class in net.minecraftforge.event.terraingen">DecorateBiomeEvent.Pre</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="nested_classes_inherited_from_class_cpw.mods.fml.common.eventhandler.Event"> <!-- --> </a> <h3>Nested classes/interfaces inherited from class&nbsp;cpw.mods.fml.common.eventhandler.<a href="../../../../cpw/mods/fml/common/eventhandler/Event.html" title="class in cpw.mods.fml.common.eventhandler">Event</a></h3> <code><a href="../../../../cpw/mods/fml/common/eventhandler/Event.HasResult.html" title="annotation in cpw.mods.fml.common.eventhandler">Event.HasResult</a>, <a href="../../../../cpw/mods/fml/common/eventhandler/Event.Result.html" title="enum in cpw.mods.fml.common.eventhandler">Event.Result</a></code></li> </ul> </li> </ul> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field_summary"> <!-- --> </a> <h3>Field Summary</h3> <ul class="blockList"> <li class="blockList"><a name="fields_inherited_from_class_net.minecraftforge.event.terraingen.DecorateBiomeEvent"> <!-- --> </a> <h3>Fields inherited from class&nbsp;net.minecraftforge.event.terraingen.<a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.html" title="class in net.minecraftforge.event.terraingen">DecorateBiomeEvent</a></h3> <code><a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.html#chunkX">chunkX</a>, <a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.html#chunkZ">chunkZ</a>, <a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.html#rand">rand</a>, <a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.html#world">world</a></code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.Post.html#DecorateBiomeEvent.Post(net.minecraft.world.World, java.util.Random, int, int)">DecorateBiomeEvent.Post</a></strong>(<a href="../../../../net/minecraft/world/World.html" title="class in net.minecraft.world">World</a>&nbsp;world, java.util.Random&nbsp;rand, int&nbsp;worldX, int&nbsp;worldZ)</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_cpw.mods.fml.common.eventhandler.Event"> <!-- --> </a> <h3>Methods inherited from class&nbsp;cpw.mods.fml.common.eventhandler.<a href="../../../../cpw/mods/fml/common/eventhandler/Event.html" title="class in cpw.mods.fml.common.eventhandler">Event</a></h3> <code><a href="../../../../cpw/mods/fml/common/eventhandler/Event.html#getListenerList()">getListenerList</a>, <a href="../../../../cpw/mods/fml/common/eventhandler/Event.html#getResult()">getResult</a>, <a href="../../../../cpw/mods/fml/common/eventhandler/Event.html#hasResult()">hasResult</a>, <a href="../../../../cpw/mods/fml/common/eventhandler/Event.html#isCancelable()">isCancelable</a>, <a href="../../../../cpw/mods/fml/common/eventhandler/Event.html#isCanceled()">isCanceled</a>, <a href="../../../../cpw/mods/fml/common/eventhandler/Event.html#setCanceled(boolean)">setCanceled</a>, <a href="../../../../cpw/mods/fml/common/eventhandler/Event.html#setResult(cpw.mods.fml.common.eventhandler.Event.Result)">setResult</a>, <a href="../../../../cpw/mods/fml/common/eventhandler/Event.html#setup()">setup</a></code></li> </ul> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="DecorateBiomeEvent.Post(net.minecraft.world.World, java.util.Random, int, int)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>DecorateBiomeEvent.Post</h4> <pre>public&nbsp;DecorateBiomeEvent.Post(<a href="../../../../net/minecraft/world/World.html" title="class in net.minecraft.world">World</a>&nbsp;world, java.util.Random&nbsp;rand, int&nbsp;worldX, int&nbsp;worldZ)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.Decorate.EventType.html" title="enum in net.minecraftforge.event.terraingen"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/minecraftforge/event/terraingen/DecorateBiomeEvent.Pre.html" title="class in net.minecraftforge.event.terraingen"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/minecraftforge/event/terraingen/DecorateBiomeEvent.Post.html" target="_top">Frames</a></li> <li><a href="DecorateBiomeEvent.Post.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li><a href="#nested_classes_inherited_from_class_net.minecraftforge.event.terraingen.DecorateBiomeEvent">Nested</a>&nbsp;|&nbsp;</li> <li><a href="#fields_inherited_from_class_net.minecraftforge.event.terraingen.DecorateBiomeEvent">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#methods_inherited_from_class_cpw.mods.fml.common.eventhandler.Event">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li>Method</li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
tera911/itc_minecraft
javadoc/net/minecraftforge/event/terraingen/DecorateBiomeEvent.Post.html
HTML
lgpl-2.1
13,421
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>Affymetrix Power Tools: affxstat Namespace Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.7.1 --> <div class="navigation" id="top"> <div class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="pages.html"><span>Related&nbsp;Pages</span></a></li> <li class="current"><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="dirs.html"><span>Directories</span></a></li> </ul> </div> <div class="tabs2"> <ul class="tablist"> <li><a href="namespaces.html"><span>Namespace&nbsp;List</span></a></li> <li><a href="namespacemembers.html"><span>Namespace&nbsp;Members</span></a></li> </ul> </div> </div> <div class="header"> <div class="summary"> <a href="#typedef-members">Typedefs</a> &#124; <a href="#enum-members">Enumerations</a> &#124; <a href="#func-members">Functions</a> </div> <div class="headertitle"> <h1>affxstat Namespace Reference</h1> </div> </div> <div class="contents"> <p>We want the output to be the same as the perl code, so //! we have converted the code to C. Refer to the perldocs //! for more info. <a href="#_details">More...</a></p> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="typedef-members"></a> Typedefs</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">typedef enum <a class="el" href="namespaceaffxstat.html#a18951321970ee51c7bc587a5c07bcc1b">affxstat::_TAIL_TYPE</a>&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a4e1e9f8cdafa90ce3b2e29581794ab30">TAIL_TYPE</a></td></tr> <tr><td colspan="2"><h2><a name="enum-members"></a> Enumerations</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">enum &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a18951321970ee51c7bc587a5c07bcc1b">_TAIL_TYPE</a> { <a class="el" href="namespaceaffxstat.html#a18951321970ee51c7bc587a5c07bcc1ba325d4fd896710899c2424d8fee7695c0">ONE_SIDED_LOWER</a>, <a class="el" href="namespaceaffxstat.html#a18951321970ee51c7bc587a5c07bcc1ba56ac6b81fdfa440c7f75b8e80e4d89e2">ONE_SIDED_UPPER</a>, <a class="el" href="namespaceaffxstat.html#a18951321970ee51c7bc587a5c07bcc1ba47868946cab15f9186ea219331ed1d18">TWO_SIDED</a> }</td></tr> <tr><td colspan="2"><h2><a name="func-members"></a> Functions</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a7e7c48eb162ea5db7ed39fca9a61cf06">gammln</a> (double xx)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#aa249ac8f23f1e31bd4a38cc6290f7fbd">log_gamma</a> (double aa)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a78075c6e3a9f8e484f02f360ae2d7150">log_beta</a> (double a, double b)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a1040e2cfda39816b7701d408af2290c1">Incomplete_Beta</a> (double a, double b, double x)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a0c206cda13a0c56c16bf08e7c56c7620">Incomplete_Gamma</a> (double a, double z, bool doLog)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a27e662ca2fcb522b98bc39feaf19d568">CalcHWEqPValue</a> (int nAA, int nAB, int nBB)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#ad9a14cc099a09d560a1bf57038543fa3">Ftest</a> (double F, double vone, double vtwo)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a01c7688a08b5c80031c8425ac33b8150">erf</a> (double x)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a6181f65e899907308e7868a3ea6396b3">pnorm</a> (double x, double mu, double sigma, bool lower_tail, bool log_p)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a4584c6f7207f84266273a45992669274">pwilcox</a> (unsigned int w, unsigned int nx, unsigned int ny, bool lower_tail, bool log_p)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#aab92d14425944b3e67b65d5604624a55">psignrank</a> (unsigned int t, unsigned int n, bool lower_tail, bool log_p)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a633827fd13f7edbe64fad0e99fc146f3">nChooseK</a> (unsigned int n, unsigned int k)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a61f579eff7a1bfab9beb5b72914fcdf3">ranksumTest</a> (double *x1, int n1, double *x2, int n2, int tail_type, bool log_p)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a4bc932b2b3fc0d657d791ee7dfbf3092">ranksumTest</a> (double *x1, int n1, double *x2, int n2, bool *tied, double *pval, int tail_type, bool log_p)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#ac202bf413dd25f139747bb5c47f34db5">ranksumTest</a> (double *x1, int n1, double *x2, int n2, int *nTied, double *pval, double *signal, int tail_type)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a95acadb00bf9bf63198efa871c498437">signedRankTest</a> (double *x, int n, int tail_type, bool log_p)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a44c21d88386fa23c75e6df7436895e44">signedRankTest</a> (double *x, int n, bool *tied, bool *nZero, bool *tiedAndZero, double *pval, int tail_type, bool log_p)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">void&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a52da5697524a8a984d0b2192e9dd4655">signedRankTest</a> (double *x, int n, int *tied, int *nZero, int *tiedAndZero, double *pval, double *signal)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#ad8834f81d1b85f540ffe7f934fa76b16">pseudoMedian</a> (double *x, int n)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a6d4a02cec18ebd50dea6023564a9dd6e">medianDifference</a> (double *x, int nX, double *y, int nY)</td></tr> <tr><td class="memItemLeft" align="right" valign="top">double&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#acc1707915ae94213453c560745858c3f">PearsonCorrelation</a> (float *x1, float *x2, int nPoints, float(*transform)(float x)=NULL)</td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T1 &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">T1&nbsp;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a74172d87fe6461d47b2abc381a75656d">chisqrprob</a> (int n, T1 x)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">The chi-squared probability ///. <a href="#a74172d87fe6461d47b2abc381a75656d"></a><br/></td></tr> <tr><td class="memTemplParams" colspan="2">template&lt;typename T1 &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">T1&nbsp;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="namespaceaffxstat.html#a4e27f62d77c9d54ed10eaebfcf9b981d">uprob</a> (T1 x)</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">upper probability of the u distribution (u=-0.85) /// <a href="#a4e27f62d77c9d54ed10eaebfcf9b981d"></a><br/></td></tr> <tr><td class="memTemplParams" colspan="2"><a class="anchor" id="ac1e4410140b70867a782794e4f2748bf"></a><!-- doxytag: member="affxstat::tDistribution" ref="ac1e4410140b70867a782794e4f2748bf" args="(T1 x, T1 degFreedom)" --> template&lt;typename T1 &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">T1&nbsp;</td><td class="memTemplItemRight" valign="bottom"><b>tDistribution</b> (T1 x, T1 degFreedom)</td></tr> <tr><td class="memTemplParams" colspan="2"><a class="anchor" id="a4e0cdbd1062c9c1037d4f8cad522e8d8"></a><!-- doxytag: member="affxstat::normalDistribution" ref="a4e0cdbd1062c9c1037d4f8cad522e8d8" args="(T1 ecks, T1 mu, T1 sigma)" --> template&lt;typename T1 &gt; </td></tr> <tr><td class="memTemplItemLeft" align="right" valign="top">T1&nbsp;</td><td class="memTemplItemRight" valign="bottom"><b>normalDistribution</b> (T1 ecks, T1 mu, T1 sigma)</td></tr> </table> <hr/><a name="_details"></a><h2>Detailed Description</h2> <p>We want the output to be the same as the perl code, so //! we have converted the code to C. Refer to the perldocs //! for more info. </p> <p>These used to live in stats-distributions.cpp, but are now templates //! so we get the float and double versions. </p> <hr/><h2>Typedef Documentation</h2> <a class="anchor" id="a4e1e9f8cdafa90ce3b2e29581794ab30"></a><!-- doxytag: member="affxstat::TAIL_TYPE" ref="a4e1e9f8cdafa90ce3b2e29581794ab30" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">typedef enum <a class="el" href="namespaceaffxstat.html#a18951321970ee51c7bc587a5c07bcc1b">affxstat::_TAIL_TYPE</a> <a class="el" href="namespaceaffxstat.html#a4e1e9f8cdafa90ce3b2e29581794ab30">affxstat::TAIL_TYPE</a></td> </tr> </table> </div> <div class="memdoc"> <p>Tail types for statistical tests. </p> </div> </div> <hr/><h2>Enumeration Type Documentation</h2> <a class="anchor" id="a18951321970ee51c7bc587a5c07bcc1b"></a><!-- doxytag: member="affxstat::_TAIL_TYPE" ref="a18951321970ee51c7bc587a5c07bcc1b" args="" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">enum <a class="el" href="namespaceaffxstat.html#a18951321970ee51c7bc587a5c07bcc1b">affxstat::_TAIL_TYPE</a></td> </tr> </table> </div> <div class="memdoc"> <p>Tail types for statistical tests. </p> <dl><dt><b>Enumerator: </b></dt><dd><table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"><em><a class="anchor" id="a18951321970ee51c7bc587a5c07bcc1ba325d4fd896710899c2424d8fee7695c0"></a><!-- doxytag: member="ONE_SIDED_LOWER" ref="a18951321970ee51c7bc587a5c07bcc1ba325d4fd896710899c2424d8fee7695c0" args="" -->ONE_SIDED_LOWER</em>&nbsp;</td><td> <p>One sided lower tail </p> </td></tr> <tr><td valign="top"><em><a class="anchor" id="a18951321970ee51c7bc587a5c07bcc1ba56ac6b81fdfa440c7f75b8e80e4d89e2"></a><!-- doxytag: member="ONE_SIDED_UPPER" ref="a18951321970ee51c7bc587a5c07bcc1ba56ac6b81fdfa440c7f75b8e80e4d89e2" args="" -->ONE_SIDED_UPPER</em>&nbsp;</td><td> <p>Once sided upper tail </p> </td></tr> <tr><td valign="top"><em><a class="anchor" id="a18951321970ee51c7bc587a5c07bcc1ba47868946cab15f9186ea219331ed1d18"></a><!-- doxytag: member="TWO_SIDED" ref="a18951321970ee51c7bc587a5c07bcc1ba47868946cab15f9186ea219331ed1d18" args="" -->TWO_SIDED</em>&nbsp;</td><td> <p>Two sided tail </p> </td></tr> </table> </dd> </dl> <p>Definition at line <a class="el" href="statfun_8h_source.html#l00081">81</a> of file <a class="el" href="statfun_8h_source.html">statfun.h</a>.</p> </div> </div> <hr/><h2>Function Documentation</h2> <a class="anchor" id="a27e662ca2fcb522b98bc39feaf19d568"></a><!-- doxytag: member="affxstat::CalcHWEqPValue" ref="a27e662ca2fcb522b98bc39feaf19d568" args="(int nAA, int nAB, int nBB)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::CalcHWEqPValue </td> <td>(</td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>nAA</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>nAB</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>nBB</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Calculate the hardy weinburg equilibrium </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>nAA</em>&nbsp;</td><td>The number of AA calls </td></tr> <tr><td valign="top"></td><td valign="top"><em>nAB</em>&nbsp;</td><td>The number of AB calls </td></tr> <tr><td valign="top"></td><td valign="top"><em>nBB</em>&nbsp;</td><td>The number of BB calls </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The HW equilibrium </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l01470">1470</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> </div> </div> <a class="anchor" id="a74172d87fe6461d47b2abc381a75656d"></a><!-- doxytag: member="affxstat::chisqrprob" ref="a74172d87fe6461d47b2abc381a75656d" args="(int n, T1 x)" --> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename T1 &gt; </div> <table class="memname"> <tr> <td class="memname">T1 affxstat::chisqrprob </td> <td>(</td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>n</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">T1&nbsp;</td> <td class="paramname"> <em>x</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>The chi-squared probability ///. </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>n</em>&nbsp;</td><td>degrees of freedom /// </td></tr> <tr><td valign="top"></td><td valign="top"><em>x</em>&nbsp;</td><td>chi-square value /// </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>upper probability of the chi-square </dd></dl> <p>Definition at line <a class="el" href="stats-distributions_8h_source.html#l00061">61</a> of file <a class="el" href="stats-distributions_8h_source.html">stats-distributions.h</a>.</p> <p>References <a class="el" href="stats-distributions_8h_source.html#l00099">uprob()</a>.</p> <p>Referenced by <a class="el" href="Dabg_8cpp_source.html#l00262">affx::Dabg::compute_target_fisher()</a>, and <a class="el" href="test-dabg_8cpp_source.html#l00229">test_target()</a>.</p> </div> </div> <a class="anchor" id="a01c7688a08b5c80031c8425ac33b8150"></a><!-- doxytag: member="affxstat::erf" ref="a01c7688a08b5c80031c8425ac33b8150" args="(double x)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::erf </td> <td>(</td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>x</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>This function ...</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x</em>&nbsp;</td><td>The ... </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The ... </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00387">387</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>Referenced by <a class="el" href="statfun_8cpp_source.html#l00462">pnorm()</a>.</p> </div> </div> <a class="anchor" id="ad9a14cc099a09d560a1bf57038543fa3"></a><!-- doxytag: member="affxstat::Ftest" ref="ad9a14cc099a09d560a1bf57038543fa3" args="(double F, double vone, double vtwo)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::Ftest </td> <td>(</td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>F</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>vone</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>vtwo</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>This function ...</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>F</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>vone</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>vtwo</em>&nbsp;</td><td>The ... </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The ... </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00375">375</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>References <a class="el" href="statfun_8cpp_source.html#l00362">Incomplete_Beta()</a>.</p> <p>Referenced by <a class="el" href="MidasSpliceDetector_8cpp_source.html#l00113">midasSpliceDetector::runMidasSingle()</a>.</p> </div> </div> <a class="anchor" id="a7e7c48eb162ea5db7ed39fca9a61cf06"></a><!-- doxytag: member="affxstat::gammln" ref="a7e7c48eb162ea5db7ed39fca9a61cf06" args="(double xx)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::gammln </td> <td>(</td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>xx</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>This function ...</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>xx</em>&nbsp;</td><td>The ... </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The ... </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00156">156</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>Referenced by <a class="el" href="statfun_8cpp_source.html#l00222">log_beta()</a>.</p> </div> </div> <a class="anchor" id="a1040e2cfda39816b7701d408af2290c1"></a><!-- doxytag: member="affxstat::Incomplete_Beta" ref="a1040e2cfda39816b7701d408af2290c1" args="(double a, double b, double x)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::Incomplete_Beta </td> <td>(</td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>a</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>b</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>x</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>This function ...</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>a</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>b</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>x</em>&nbsp;</td><td>The ... </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The ... </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00362">362</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>Referenced by <a class="el" href="statfun_8cpp_source.html#l00375">Ftest()</a>.</p> </div> </div> <a class="anchor" id="a0c206cda13a0c56c16bf08e7c56c7620"></a><!-- doxytag: member="affxstat::Incomplete_Gamma" ref="a0c206cda13a0c56c16bf08e7c56c7620" args="(double a, double z, bool doLog)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::Incomplete_Gamma </td> <td>(</td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>a</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>z</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&nbsp;</td> <td class="paramname"> <em>doLog</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>This function ...</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>a</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>z</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>doLog</em>&nbsp;</td><td>The ... </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The ... </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00295">295</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> </div> </div> <a class="anchor" id="a78075c6e3a9f8e484f02f360ae2d7150"></a><!-- doxytag: member="affxstat::log_beta" ref="a78075c6e3a9f8e484f02f360ae2d7150" args="(double a, double b)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::log_beta </td> <td>(</td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>a</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>b</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>This function ...</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>a</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>b</em>&nbsp;</td><td>The ... </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The ... </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00222">222</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>References <a class="el" href="statfun_8cpp_source.html#l00156">gammln()</a>, and <a class="el" href="statfun_8cpp_source.html#l00172">log_gamma()</a>.</p> </div> </div> <a class="anchor" id="aa249ac8f23f1e31bd4a38cc6290f7fbd"></a><!-- doxytag: member="affxstat::log_gamma" ref="aa249ac8f23f1e31bd4a38cc6290f7fbd" args="(double aa)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::log_gamma </td> <td>(</td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>aa</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>This function ...</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>aa</em>&nbsp;</td><td>The ... </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The ... </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00172">172</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>Referenced by <a class="el" href="statfun_8cpp_source.html#l00222">log_beta()</a>.</p> </div> </div> <a class="anchor" id="a6d4a02cec18ebd50dea6023564a9dd6e"></a><!-- doxytag: member="affxstat::medianDifference" ref="a6d4a02cec18ebd50dea6023564a9dd6e" args="(double *x, int nX, double *y, int nY)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::medianDifference </td> <td>(</td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>x</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>nX</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>y</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>nY</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Computes the median over all pairwise differences in two arrays of values.</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x</em>&nbsp;</td><td>The first array of values. </td></tr> <tr><td valign="top"></td><td valign="top"><em>nX</em>&nbsp;</td><td>The number of points in the x1 array. </td></tr> <tr><td valign="top"></td><td valign="top"><em>y</em>&nbsp;</td><td>The second array of values. </td></tr> <tr><td valign="top"></td><td valign="top"><em>nY</em>&nbsp;</td><td>The number of points in the x2 array. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The median of all n1*n2 pairwise differences. </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l01225">1225</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>Referenced by <a class="el" href="statfun_8cpp_source.html#l00981">ranksumTest()</a>.</p> </div> </div> <a class="anchor" id="a633827fd13f7edbe64fad0e99fc146f3"></a><!-- doxytag: member="affxstat::nChooseK" ref="a633827fd13f7edbe64fad0e99fc146f3" args="(unsigned int n, unsigned int k)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::nChooseK </td> <td>(</td> <td class="paramtype">unsigned int&nbsp;</td> <td class="paramname"> <em>n</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">unsigned int&nbsp;</td> <td class="paramname"> <em>k</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>This function compute the N choose K value.</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>n</em>&nbsp;</td><td>The N value </td></tr> <tr><td valign="top"></td><td valign="top"><em>k</em>&nbsp;</td><td>The K value </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>N choose K </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00674">674</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> </div> </div> <a class="anchor" id="acc1707915ae94213453c560745858c3f"></a><!-- doxytag: member="affxstat::PearsonCorrelation" ref="acc1707915ae94213453c560745858c3f" args="(float *x1, float *x2, int nPoints, float(*transform)(float x)=NULL)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::PearsonCorrelation </td> <td>(</td> <td class="paramtype">float *&nbsp;</td> <td class="paramname"> <em>x1</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">float *&nbsp;</td> <td class="paramname"> <em>x2</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>nPoints</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">float(*)(float x)&nbsp;</td> <td class="paramname"> <em>transform</em> = <code>NULL</code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>This function calculates Pearson's correlation coefficient between 2 arrays of floats</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x1</em>&nbsp;</td><td>The first array of floats </td></tr> <tr><td valign="top"></td><td valign="top"><em>x2</em>&nbsp;</td><td>The second array of floats </td></tr> <tr><td valign="top"></td><td valign="top"><em>nPoints</em>&nbsp;</td><td>The size of each array. assumed the same </td></tr> <tr><td valign="top"></td><td valign="top"><em>transform</em>&nbsp;</td><td>A function to transform the data </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>Pearson's correlation </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l01249">1249</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> </div> </div> <a class="anchor" id="a6181f65e899907308e7868a3ea6396b3"></a><!-- doxytag: member="affxstat::pnorm" ref="a6181f65e899907308e7868a3ea6396b3" args="(double x, double mu, double sigma, bool lower_tail, bool log_p)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::pnorm </td> <td>(</td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>x</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>mu</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double&nbsp;</td> <td class="paramname"> <em>sigma</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&nbsp;</td> <td class="paramname"> <em>lower_tail</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&nbsp;</td> <td class="paramname"> <em>log_p</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>This function ...</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>mu</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>sigma</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>lower_tail</em>&nbsp;</td><td>Flag indicating if lower tail should be computed. </td></tr> <tr><td valign="top"></td><td valign="top"><em>log_p</em>&nbsp;</td><td>Flag indicating if the p-value should be logged. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The ... </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00462">462</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>References <a class="el" href="statfun_8cpp_source.html#l00387">erf()</a>, and <a class="el" href="statfun_8h_source.html#l00054">SQRT_TWO</a>.</p> </div> </div> <a class="anchor" id="ad8834f81d1b85f540ffe7f934fa76b16"></a><!-- doxytag: member="affxstat::pseudoMedian" ref="ad8834f81d1b85f540ffe7f934fa76b16" args="(double *x, int n)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::pseudoMedian </td> <td>(</td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>x</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>n</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Computes the pseudo median.</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x</em>&nbsp;</td><td>The array of values for which to compute the pseudomedian. </td></tr> <tr><td valign="top"></td><td valign="top"><em>n</em>&nbsp;</td><td>The number of points in the x array. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The pseudo median. </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00929">929</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>Referenced by <a class="el" href="statfun_8cpp_source.html#l00698">signedRankTest()</a>.</p> </div> </div> <a class="anchor" id="aab92d14425944b3e67b65d5604624a55"></a><!-- doxytag: member="affxstat::psignrank" ref="aab92d14425944b3e67b65d5604624a55" args="(unsigned int t, unsigned int n, bool lower_tail, bool log_p)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::psignrank </td> <td>(</td> <td class="paramtype">unsigned int&nbsp;</td> <td class="paramname"> <em>t</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">unsigned int&nbsp;</td> <td class="paramname"> <em>n</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&nbsp;</td> <td class="paramname"> <em>lower_tail</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&nbsp;</td> <td class="paramname"> <em>log_p</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>The implementation of wilcoxon signed rank statistic.</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>w</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>n</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>lower_tail</em>&nbsp;</td><td>Flag indicating if lower tail should be computed. </td></tr> <tr><td valign="top"></td><td valign="top"><em>log_p</em>&nbsp;</td><td>Flag indicating if the p-value should be logged. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The signed rank statistic. </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00634">634</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>References <a class="el" href="statfun_8h_source.html#l00057">LOG_TWO</a>, and <a class="el" href="statfun_8h_source.html#l00069">PSIGNRANK_MAX_N</a>.</p> <p>Referenced by <a class="el" href="statfun_8cpp_source.html#l00735">signedRankTest()</a>.</p> </div> </div> <a class="anchor" id="a4584c6f7207f84266273a45992669274"></a><!-- doxytag: member="affxstat::pwilcox" ref="a4584c6f7207f84266273a45992669274" args="(unsigned int w, unsigned int nx, unsigned int ny, bool lower_tail, bool log_p)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::pwilcox </td> <td>(</td> <td class="paramtype">unsigned int&nbsp;</td> <td class="paramname"> <em>w</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">unsigned int&nbsp;</td> <td class="paramname"> <em>nx</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">unsigned int&nbsp;</td> <td class="paramname"> <em>ny</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&nbsp;</td> <td class="paramname"> <em>lower_tail</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&nbsp;</td> <td class="paramname"> <em>log_p</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>This function ...</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>w</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>nx</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>xy</em>&nbsp;</td><td>The ... </td></tr> <tr><td valign="top"></td><td valign="top"><em>lower_tail</em>&nbsp;</td><td>Flag indicating if lower tail should be computed. </td></tr> <tr><td valign="top"></td><td valign="top"><em>log_p</em>&nbsp;</td><td>Flag indicating if the p-value should be logged. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The ... </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00575">575</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>References <a class="el" href="GenoCallCoder_8cpp_source.html#l00094">choose()</a>.</p> <p>Referenced by <a class="el" href="statfun_8cpp_source.html#l01015">ranksumTest()</a>.</p> </div> </div> <a class="anchor" id="a61f579eff7a1bfab9beb5b72914fcdf3"></a><!-- doxytag: member="affxstat::ranksumTest" ref="a61f579eff7a1bfab9beb5b72914fcdf3" args="(double *x1, int n1, double *x2, int n2, int tail_type, bool log_p)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::ranksumTest </td> <td>(</td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>x1</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>n1</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>x2</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>n2</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>tail_type</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&nbsp;</td> <td class="paramname"> <em>log_p</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Performs a Wilcoxon rank sum test. This is the simplest interface.</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x1</em>&nbsp;</td><td>The array of values for the first sample. </td></tr> <tr><td valign="top"></td><td valign="top"><em>n1</em>&nbsp;</td><td>The number of points in the x1 array. </td></tr> <tr><td valign="top"></td><td valign="top"><em>x2</em>&nbsp;</td><td>The array of values for the second sample. </td></tr> <tr><td valign="top"></td><td valign="top"><em>n2</em>&nbsp;</td><td>The number of points in the x2 array. </td></tr> <tr><td valign="top"></td><td valign="top"><em>tail_type</em>&nbsp;</td><td>The tail type for the test (one of ONE_SIDED_UPPER, ONE_SIDED_LOWER, TWO_SIDED) </td></tr> <tr><td valign="top"></td><td valign="top"><em>log_p</em>&nbsp;</td><td>Boolean flag indicating if the p-value should be logged. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The computed p-value. </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l01002">1002</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>Referenced by <a class="el" href="statfun_8cpp_source.html#l00981">ranksumTest()</a>.</p> </div> </div> <a class="anchor" id="ac202bf413dd25f139747bb5c47f34db5"></a><!-- doxytag: member="affxstat::ranksumTest" ref="ac202bf413dd25f139747bb5c47f34db5" args="(double *x1, int n1, double *x2, int n2, int *nTied, double *pval, double *signal, int tail_type)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void affxstat::ranksumTest </td> <td>(</td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>x1</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>n1</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>x2</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>n2</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int *&nbsp;</td> <td class="paramname"> <em>nTied</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>pval</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>signal</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>tail_type</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Performs a Wilcoxon rank sum test. This is the legacy interface.</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x1</em>&nbsp;</td><td>The array of values for the first sample. </td></tr> <tr><td valign="top"></td><td valign="top"><em>n1</em>&nbsp;</td><td>The number of points in the x1 array. </td></tr> <tr><td valign="top"></td><td valign="top"><em>x2</em>&nbsp;</td><td>The array of values for the second sample. </td></tr> <tr><td valign="top"></td><td valign="top"><em>n2</em>&nbsp;</td><td>The number of points in the x2 array. </td></tr> <tr><td valign="top"></td><td valign="top"><em>nTied</em>&nbsp;</td><td>Value will be incremented by one if there were ties in the input data. </td></tr> <tr><td valign="top"></td><td valign="top"><em>pval</em>&nbsp;</td><td>The computed p-value. </td></tr> <tr><td valign="top"></td><td valign="top"><em>signal</em>&nbsp;</td><td>The median of all pairwise differences in x1 and x2 (Hodges-Lehmann estimator) </td></tr> <tr><td valign="top"></td><td valign="top"><em>tail_type</em>&nbsp;</td><td>The tail type for the test (one of ONE_SIDED_UPPER, ONE_SIDED_LOWER, TWO_SIDED) </td></tr> </table> </dd> </dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00981">981</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>References <a class="el" href="statfun_8cpp_source.html#l01225">medianDifference()</a>, and <a class="el" href="statfun_8cpp_source.html#l01002">ranksumTest()</a>.</p> </div> </div> <a class="anchor" id="a4bc932b2b3fc0d657d791ee7dfbf3092"></a><!-- doxytag: member="affxstat::ranksumTest" ref="a4bc932b2b3fc0d657d791ee7dfbf3092" args="(double *x1, int n1, double *x2, int n2, bool *tied, double *pval, int tail_type, bool log_p)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void affxstat::ranksumTest </td> <td>(</td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>x1</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>n1</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>x2</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>n2</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool *&nbsp;</td> <td class="paramname"> <em>tied</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>pval</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>tail_type</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&nbsp;</td> <td class="paramname"> <em>log_p</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Performs a Wilcoxon rank sum test. This is the full interface.</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x1</em>&nbsp;</td><td>The array of values for the first sample. </td></tr> <tr><td valign="top"></td><td valign="top"><em>n1</em>&nbsp;</td><td>The number of points in the x1 array. </td></tr> <tr><td valign="top"></td><td valign="top"><em>x2</em>&nbsp;</td><td>The array of values for the second sample. </td></tr> <tr><td valign="top"></td><td valign="top"><em>n2</em>&nbsp;</td><td>The number of points in the x2 array. </td></tr> <tr><td valign="top"></td><td valign="top"><em>tied</em>&nbsp;</td><td>Boolean flag, value will reflect whether or not there were ties in the input data. </td></tr> <tr><td valign="top"></td><td valign="top"><em>pval</em>&nbsp;</td><td>The computed p-value. </td></tr> <tr><td valign="top"></td><td valign="top"><em>tail_type</em>&nbsp;</td><td>The tail type for the test (one of ONE_SIDED_UPPER, ONE_SIDED_LOWER, TWO_SIDED) </td></tr> <tr><td valign="top"></td><td valign="top"><em>log_p</em>&nbsp;</td><td>Boolean flag indicating if the p-value should be logged. </td></tr> </table> </dd> </dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l01015">1015</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>References <a class="el" href="statfun_8h_source.html#l00078">APPROX_RANKSUM_CUTOFF</a>, <a class="el" href="statfun_8h_source.html#l00057">LOG_TWO</a>, <a class="el" href="statfun_8h_source.html#l00083">ONE_SIDED_LOWER</a>, <a class="el" href="statfun_8h_source.html#l00086">ONE_SIDED_UPPER</a>, <a class="el" href="statfun_8cpp_source.html#l00575">pwilcox()</a>, and <a class="el" href="statfun_8h_source.html#l00089">TWO_SIDED</a>.</p> </div> </div> <a class="anchor" id="a52da5697524a8a984d0b2192e9dd4655"></a><!-- doxytag: member="affxstat::signedRankTest" ref="a52da5697524a8a984d0b2192e9dd4655" args="(double *x, int n, int *tied, int *nZero, int *tiedAndZero, double *pval, double *signal)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void affxstat::signedRankTest </td> <td>(</td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>x</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>n</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int *&nbsp;</td> <td class="paramname"> <em>tied</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int *&nbsp;</td> <td class="paramname"> <em>nZero</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int *&nbsp;</td> <td class="paramname"> <em>tiedAndZero</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>pval</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>signal</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Performs a signed rank test, returns logged lower-tail p-value and computes pseudoMedian. This is the legacy interface.</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x</em>&nbsp;</td><td>The array of values to analyze. </td></tr> <tr><td valign="top"></td><td valign="top"><em>n</em>&nbsp;</td><td>The number of points in the x array. </td></tr> <tr><td valign="top"></td><td valign="top"><em>tied</em>&nbsp;</td><td>The number of observations that were tied. </td></tr> <tr><td valign="top"></td><td valign="top"><em>nZero</em>&nbsp;</td><td>The number of observations that were zero. </td></tr> <tr><td valign="top"></td><td valign="top"><em>tiedAndZero</em>&nbsp;</td><td>The number of observations that were tied and zero. </td></tr> <tr><td valign="top"></td><td valign="top"><em>pval</em>&nbsp;</td><td>The p-value. </td></tr> <tr><td valign="top"></td><td valign="top"><em>signal</em>&nbsp;</td><td>The pseudo median. </td></tr> </table> </dd> </dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00698">698</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>References <a class="el" href="statfun_8h_source.html#l00083">ONE_SIDED_LOWER</a>, <a class="el" href="statfun_8cpp_source.html#l00929">pseudoMedian()</a>, and <a class="el" href="statfun_8cpp_source.html#l00714">signedRankTest()</a>.</p> </div> </div> <a class="anchor" id="a95acadb00bf9bf63198efa871c498437"></a><!-- doxytag: member="affxstat::signedRankTest" ref="a95acadb00bf9bf63198efa871c498437" args="(double *x, int n, int tail_type, bool log_p)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">double affxstat::signedRankTest </td> <td>(</td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>x</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>n</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>tail_type</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&nbsp;</td> <td class="paramname"> <em>log_p</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Performs a Wilcoxon signed rank test. This is the simplest interface.</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x</em>&nbsp;</td><td>The array of values to analyze. </td></tr> <tr><td valign="top"></td><td valign="top"><em>n</em>&nbsp;</td><td>The number of points in the x array. </td></tr> <tr><td valign="top"></td><td valign="top"><em>tail_type</em>&nbsp;</td><td>The tail type for the test (one of ONE_SIDED_UPPER, ONE_SIDED_LOWER, TWO_SIDED) </td></tr> <tr><td valign="top"></td><td valign="top"><em>log_p</em>&nbsp;</td><td>Flag indicating if the p-value should be logged. </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>The computed p-value. </dd></dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00714">714</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>Referenced by <a class="el" href="statfun_8cpp_source.html#l00698">signedRankTest()</a>.</p> </div> </div> <a class="anchor" id="a44c21d88386fa23c75e6df7436895e44"></a><!-- doxytag: member="affxstat::signedRankTest" ref="a44c21d88386fa23c75e6df7436895e44" args="(double *x, int n, bool *tied, bool *nZero, bool *tiedAndZero, double *pval, int tail_type, bool log_p)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void affxstat::signedRankTest </td> <td>(</td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>x</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>n</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool *&nbsp;</td> <td class="paramname"> <em>tied</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool *&nbsp;</td> <td class="paramname"> <em>nZero</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool *&nbsp;</td> <td class="paramname"> <em>tiedAndZero</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">double *&nbsp;</td> <td class="paramname"> <em>pval</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">int&nbsp;</td> <td class="paramname"> <em>tail_type</em>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">bool&nbsp;</td> <td class="paramname"> <em>log_p</em></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p>Performs a signed rank test. This is the full interface.</p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x</em>&nbsp;</td><td>The array of values to analyze. </td></tr> <tr><td valign="top"></td><td valign="top"><em>n</em>&nbsp;</td><td>The number of points in the x array. </td></tr> <tr><td valign="top"></td><td valign="top"><em>tied</em>&nbsp;</td><td>The number of observations that were tied. </td></tr> <tr><td valign="top"></td><td valign="top"><em>nZero</em>&nbsp;</td><td>The number of observations that were zero. </td></tr> <tr><td valign="top"></td><td valign="top"><em>tiedAndZero</em>&nbsp;</td><td>The number of observations that were tied and zero. </td></tr> <tr><td valign="top"></td><td valign="top"><em>pval</em>&nbsp;</td><td>The p-value. </td></tr> <tr><td valign="top"></td><td valign="top"><em>signal</em>&nbsp;</td><td>The pseudo median. </td></tr> <tr><td valign="top"></td><td valign="top"><em>tail_type</em>&nbsp;</td><td>The tail type for the test (one of ONE_SIDED_UPPER, ONE_SIDED_LOWER, TWO_SIDED) </td></tr> <tr><td valign="top"></td><td valign="top"><em>log_p</em>&nbsp;</td><td>Flag indicating if the p-value should be logged. </td></tr> </table> </dd> </dl> <p>Definition at line <a class="el" href="statfun_8cpp_source.html#l00735">735</a> of file <a class="el" href="statfun_8cpp_source.html">statfun.cpp</a>.</p> <p>References <a class="el" href="statfun_8h_source.html#l00075">APPROX_SIGNRANK_CUTOFF</a>, <a class="el" href="statfun_8h_source.html#l00057">LOG_TWO</a>, <a class="el" href="statfun_8h_source.html#l00083">ONE_SIDED_LOWER</a>, <a class="el" href="statfun_8h_source.html#l00086">ONE_SIDED_UPPER</a>, <a class="el" href="statfun_8cpp_source.html#l00634">psignrank()</a>, and <a class="el" href="statfun_8h_source.html#l00089">TWO_SIDED</a>.</p> </div> </div> <a class="anchor" id="a4e27f62d77c9d54ed10eaebfcf9b981d"></a><!-- doxytag: member="affxstat::uprob" ref="a4e27f62d77c9d54ed10eaebfcf9b981d" args="(T1 x)" --> <div class="memitem"> <div class="memproto"> <div class="memtemplate"> template&lt;typename T1 &gt; </div> <table class="memname"> <tr> <td class="memname">T1 affxstat::uprob </td> <td>(</td> <td class="paramtype">T1&nbsp;</td> <td class="paramname"> <em>x</em></td> <td>&nbsp;)&nbsp;</td> <td></td> </tr> </table> </div> <div class="memdoc"> <p>upper probability of the u distribution (u=-0.85) /// </p> <dl><dt><b>Parameters:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>x</em>&nbsp;</td><td>??? /// </td></tr> </table> </dd> </dl> <dl class="return"><dt><b>Returns:</b></dt><dd>0.0-1.0 </dd></dl> <p>Definition at line <a class="el" href="stats-distributions_8h_source.html#l00099">99</a> of file <a class="el" href="stats-distributions_8h_source.html">stats-distributions.h</a>.</p> <p>Referenced by <a class="el" href="stats-distributions_8h_source.html#l00061">chisqrprob()</a>.</p> </div> </div> </div> <hr class="footer"/><address class="footer"><small>Generated on Fri Mar 20 2015 18:03:59 for Affymetrix Power Tools by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.1 </small></address> </body> </html>
einon/affymetrix-power-tools
sdk/dox/html/namespaceaffxstat.html
HTML
lgpl-2.1
63,416
# $Id: DebianMakefile,v 1.1 2006-04-07 13:06:48 ctl Exp $ # Installs 3dm on a Debian system (change paths for other Linuxes) # NOTE: Quick-and-dirty hack TARGETDIR=/usr/local/3dm BINDIR=/usr/local/bin #TARGETDIR=tmp2 #BINDIR=tmp2 VERID=0.1.5beta1-custom install: ant contrib-get ant -D3dm.version=$(VERID) release install -d -m 0755 $(TARGETDIR) install -m 0755 build/3dm-$(VERID).jar $(TARGETDIR)/3dm.jar install -m 0755 3dm $(BINDIR)
JiangYouxin/3dm
Makefile
Makefile
lgpl-2.1
443
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library 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 library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.functions.arrays; import lucee.runtime.PageContext; import lucee.runtime.exp.FunctionException; import lucee.runtime.exp.PageException; import lucee.runtime.ext.function.BIF; import lucee.runtime.functions.closure.ClosureFunc; import lucee.runtime.functions.closure.Some; import lucee.runtime.op.Caster; import lucee.runtime.type.Array; import lucee.runtime.type.UDF; public class ArraySome extends BIF { private static final long serialVersionUID = -7449844630816343951L; public static boolean call(PageContext pc, Array array, UDF udf) throws PageException { return _call(pc, array, udf, false, 20); } public static boolean call(PageContext pc, Array array, UDF udf, boolean parallel) throws PageException { return _call(pc, array, udf, parallel, 20); } public static boolean call(PageContext pc, Array array, UDF udf, boolean parallel, double maxThreads) throws PageException { return _call(pc, array, udf, parallel, (int) maxThreads); } private static boolean _call(PageContext pc, Array array, UDF udf, boolean parallel, int maxThreads) throws PageException { return Some._call(pc, array, udf, parallel, maxThreads, ClosureFunc.TYPE_ARRAY); } @Override public Object invoke(PageContext pc, Object[] args) throws PageException { if (args.length == 2) return call(pc, Caster.toArray(args[0]), Caster.toFunction(args[1])); if (args.length == 3) return call(pc, Caster.toArray(args[0]), Caster.toFunction(args[1]), Caster.toBooleanValue(args[2])); if (args.length == 4) return call(pc, Caster.toArray(args[0]), Caster.toFunction(args[1]), Caster.toBooleanValue(args[2]), Caster.toDoubleValue(args[3])); throw new FunctionException(pc, "ArraySome", 2, 4, args.length); } }
jzuijlek/Lucee
core/src/main/java/lucee/runtime/functions/arrays/ArraySome.java
Java
lgpl-2.1
2,520
using System.Collections.Generic; using System.Configuration; namespace PubComp.Caching.Core.Config.Loaders { /// <summary> /// Load the cache configuration using App/Web.config files using <see cref="System.Configuration.ConfigurationManager" /> /// </summary> public class SystemConfigurationManagerCacheConfigLoader : ICacheConfigLoader { public IList<ConfigNode> LoadConfig() { return ConfigurationManager.GetSection("PubComp/CacheConfig") as IList<ConfigNode>; } } }
pub-comp/caching
Core/Config/Loaders/SystemConfigurationManagerCacheConfigLoader.cs
C#
lgpl-2.1
535
# Yum plugin to re-patch container rootfs after a yum update is done # # Copyright (C) 2012 Oracle # # Authors: # Dwight Engen <dwight.engen@oracle.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 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 Library General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # import os from fnmatch import fnmatch from yum.plugins import TYPE_INTERACTIVE from yum.plugins import PluginYumExit requires_api_version = '2.0' plugin_type = (TYPE_INTERACTIVE,) def posttrans_hook(conduit): pkgs = [] patch_required = False # If we aren't root, we can't have updated anything if os.geteuid(): return # See what packages have files that were patched confpkgs = conduit.confString('main', 'packages') if not confpkgs: return tmp = confpkgs.split(",") for confpkg in tmp: pkgs.append(confpkg.strip()) conduit.info(2, "lxc-patch: checking if updated pkgs need patching...") ts = conduit.getTsInfo() for tsmem in ts.getMembers(): for pkg in pkgs: if fnmatch(pkg, tsmem.po.name): patch_required = True if patch_required: conduit.info(2, "lxc-patch: patching container...") os.spawnlp(os.P_WAIT, "lxc-patch", "lxc-patch", "--patch", "/")
czchen/debian-lxc
config/yum/lxc-patch.py
Python
lgpl-2.1
1,850
/* * dLeyna * * Copyright (C) 2012-2013 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU Lesser General Public License, * version 2.1, as published by the Free Software Foundation. * * This program is distributed in the hope 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., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * * Ludovic Ferrandis <ludovic.ferrandis@intel.com> * Regis Merlino <regis.merlino@intel.com> * */ #ifndef DLS_SERVICE_TASK_H__ #define DLS_SERVICE_TASK_H__ #include <glib.h> #include <libgupnp/gupnp-service-proxy.h> #include <libdleyna/core/task-atom.h> #include "server.h" typedef struct dls_service_task_t_ dls_service_task_t; typedef GUPnPServiceProxyAction *(*dls_service_task_action) (dls_service_task_t *task, GUPnPServiceProxy *proxy, gboolean *failed); const char *dls_service_task_create_source(void); void dls_service_task_add(const dleyna_task_queue_key_t *queue_id, dls_service_task_action action, dls_device_t *device, GUPnPServiceProxy *proxy, GUPnPServiceProxyActionCallback action_cb, GDestroyNotify free_func, gpointer cb_user_data); void dls_service_task_begin_action_cb(GUPnPServiceProxy *proxy, GUPnPServiceProxyAction *action, gpointer user_data); void dls_service_task_process_cb(dleyna_task_atom_t *atom, gpointer user_data); void dls_service_task_cancel_cb(dleyna_task_atom_t *atom, gpointer user_data); void dls_service_task_delete_cb(dleyna_task_atom_t *atom, gpointer user_data); dls_device_t *dls_service_task_get_device(dls_service_task_t *task); gpointer *dls_service_task_get_user_data(dls_service_task_t *task); #endif /* DLS_SERVICE_TASK_H__ */
cguiraud/dleyna-server
lib/service-task.h
C
lgpl-2.1
2,139
/* * JBoss, Home of Professional Open Source. * Copyright 2011, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 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. 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.as.host.controller.operations; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CORE_SERVICE; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DISCOVERY_OPTIONS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.HOST_ENVIRONMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT_MAJOR_VERSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT_MICRO_VERSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT_MINOR_VERSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.MANAGEMENT_OPERATIONS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.NAMESPACES; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PRODUCT_NAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.PRODUCT_VERSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RELEASE_CODENAME; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.RELEASE_VERSION; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SCHEMA_LOCATIONS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SERVICE; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationDefinition; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.descriptions.ModelDescriptionConstants; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.as.controller.registry.PlaceholderResource; import org.jboss.as.controller.registry.Resource; import org.jboss.as.host.controller.HostControllerEnvironment; import org.jboss.as.host.controller.HostModelUtil; import org.jboss.as.host.controller.discovery.DiscoveryOptionsResource; import org.jboss.as.host.controller.ignored.IgnoredDomainResourceRegistry; import org.jboss.as.host.controller.logging.HostControllerLogger; import org.jboss.as.platform.mbean.PlatformMBeanConstants; import org.jboss.as.platform.mbean.RootPlatformMBeanResource; import org.jboss.as.version.Version; import org.jboss.dmr.ModelNode; import org.jboss.modules.ModuleClassLoader; /** * The handler to add the local host definition to the DomainModel. * * @author <a href="mailto:darran.lofthouse@jboss.com">Darran Lofthouse</a> */ public class HostModelRegistrationHandler implements OperationStepHandler { private static final RuntimeCapability<Void> HOST_RUNTIME_CAPABILITY = RuntimeCapability .Builder.of("org.wildfly.host.controller", false) .build(); public static final String OPERATION_NAME = "register-host-model"; //Private method does not need resources for description public static final OperationDefinition DEFINITION = new SimpleOperationDefinitionBuilder(OPERATION_NAME, null) .setPrivateEntry() .build(); private final HostControllerEnvironment hostControllerEnvironment; private final IgnoredDomainResourceRegistry ignoredDomainResourceRegistry; private final HostModelUtil.HostModelRegistrar hostModelRegistrar; private final Resource modelControllerResource; public HostModelRegistrationHandler(final HostControllerEnvironment hostControllerEnvironment, final IgnoredDomainResourceRegistry ignoredDomainResourceRegistry, final HostModelUtil.HostModelRegistrar hostModelRegistrar, final Resource modelControllerResource) { this.hostControllerEnvironment = hostControllerEnvironment; this.ignoredDomainResourceRegistry = ignoredDomainResourceRegistry; this.hostModelRegistrar = hostModelRegistrar; this.modelControllerResource = modelControllerResource; } /** * {@inheritDoc} */ public void execute(OperationContext context, ModelNode operation) { if (!context.isBooting()) { throw HostControllerLogger.ROOT_LOGGER.invocationNotAllowedAfterBoot(OPERATION_NAME); } context.registerCapability(HOST_RUNTIME_CAPABILITY); final String hostName = operation.require(NAME).asString(); // Set up the host model registrations final ManagementResourceRegistration rootRegistration = context.getResourceRegistrationForUpdate(); hostModelRegistrar.registerHostModel(hostName, rootRegistration); final PathAddress hostAddress = PathAddress.pathAddress(PathElement.pathElement(HOST, hostName)); final Resource rootResource = context.createResource(hostAddress); final ModelNode model = rootResource.getModel(); initCoreModel(model, hostControllerEnvironment); // Create the management resources Resource management = context.createResource(hostAddress.append(PathElement.pathElement(CORE_SERVICE, MANAGEMENT))); if (modelControllerResource != null) { management.registerChild(PathElement.pathElement(SERVICE, MANAGEMENT_OPERATIONS), modelControllerResource); } //Create the empty host-environment resource context.addResource(hostAddress.append(PathElement.pathElement(CORE_SERVICE, HOST_ENVIRONMENT)), PlaceholderResource.INSTANCE); //Create the empty module-loading resource rootResource.registerChild(PathElement.pathElement(ModelDescriptionConstants.CORE_SERVICE, ModelDescriptionConstants.MODULE_LOADING), PlaceholderResource.INSTANCE); //Create the empty capability registry resource rootResource.registerChild(PathElement.pathElement(ModelDescriptionConstants.CORE_SERVICE, ModelDescriptionConstants.CAPABILITY_REGISTRY), PlaceholderResource.INSTANCE); // Wire in the platform mbean resources. We're bypassing the context.createResource API here because // we want to use our own resource type. But it's ok as the createResource calls above have taken the lock rootResource.registerChild(PlatformMBeanConstants.ROOT_PATH, new RootPlatformMBeanResource()); // Wire in the ignored-resources resource Resource.ResourceEntry ignoredRoot = ignoredDomainResourceRegistry.getRootResource(); rootResource.registerChild(ignoredRoot.getPathElement(), ignoredRoot); // Create the empty discovery options resource context.addResource(hostAddress.append(PathElement.pathElement(CORE_SERVICE, DISCOVERY_OPTIONS)), new DiscoveryOptionsResource()); } private static void initCoreModel(final ModelNode root, HostControllerEnvironment environment) { try { root.get(RELEASE_VERSION).set(Version.AS_VERSION); root.get(RELEASE_CODENAME).set(Version.AS_RELEASE_CODENAME); } catch (RuntimeException e) { if (HostModelRegistrationHandler.class.getClassLoader() instanceof ModuleClassLoader) { //The standalone tests can't get this info throw e; } } root.get(MANAGEMENT_MAJOR_VERSION).set(Version.MANAGEMENT_MAJOR_VERSION); root.get(MANAGEMENT_MINOR_VERSION).set(Version.MANAGEMENT_MINOR_VERSION); root.get(MANAGEMENT_MICRO_VERSION).set(Version.MANAGEMENT_MICRO_VERSION); // Community uses UNDEF values ModelNode nameNode = root.get(PRODUCT_NAME); ModelNode versionNode = root.get(PRODUCT_VERSION); if (environment != null) { String productName = environment.getProductConfig().getProductName(); String productVersion = environment.getProductConfig().getProductVersion(); if (productName != null) { nameNode.set(productName); } if (productVersion != null) { versionNode.set(productVersion); } } //Set empty lists for namespaces and schema-locations to pass model validation root.get(NAMESPACES).setEmptyList(); root.get(SCHEMA_LOCATIONS).setEmptyList(); } }
JiriOndrusek/wildfly-core
host-controller/src/main/java/org/jboss/as/host/controller/operations/HostModelRegistrationHandler.java
Java
lgpl-2.1
9,656
/** * DSS - Digital Signature Services * Copyright (C) 2015 European Commission, provided under the CEF programme * * This file is part of the "DSS - Digital Signature Services" project. * * This library 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 library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package eu.europa.esig.dss.jades.signature; import eu.europa.esig.dss.enumerations.JWSSerializationType; import eu.europa.esig.dss.enumerations.SignaturePackaging; import eu.europa.esig.dss.jades.DSSJsonUtils; import eu.europa.esig.dss.jades.JAdESSignatureParameters; import eu.europa.esig.dss.jades.JWSJsonSerializationGenerator; import eu.europa.esig.dss.jades.JWSJsonSerializationObject; import eu.europa.esig.dss.jades.validation.JWS; import eu.europa.esig.dss.model.DSSDocument; import eu.europa.esig.dss.model.InMemoryDocument; import eu.europa.esig.dss.model.MimeType; import eu.europa.esig.dss.model.SignatureValue; import eu.europa.esig.dss.spi.DSSASN1Utils; import eu.europa.esig.dss.utils.Utils; import eu.europa.esig.dss.validation.CertificateVerifier; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; /** * Builds a JWS JSON Serialization signature * */ public class JAdESSerializationBuilder extends AbstractJAdESBuilder { /** The JWS signature container */ private JWSJsonSerializationObject jwsJsonSerializationObject; /** * The default constructor * * @param certificateVerifier {@link CertificateVerifier} * @param parameters {@link JAdESSignatureParameters} * @param documentsToSign a list of {@link DSSDocument}s to sign */ public JAdESSerializationBuilder(final CertificateVerifier certificateVerifier, final JAdESSignatureParameters parameters, final List<DSSDocument> documentsToSign) { super(certificateVerifier, parameters, documentsToSign); } /** * The constructor from an existing signature * * @param certificateVerifier {@link CertificateVerifier} * @param parameters {@link JAdESSignatureParameters} * @param jwsJsonSerializationObject {@link JWSJsonSerializationObject} representing the existing signature(s) */ public JAdESSerializationBuilder(final CertificateVerifier certificateVerifier, final JAdESSignatureParameters parameters, final JWSJsonSerializationObject jwsJsonSerializationObject) { super(certificateVerifier, parameters, extractDocumentToBeSigned(parameters, jwsJsonSerializationObject)); this.jwsJsonSerializationObject = jwsJsonSerializationObject; } private static List<DSSDocument> extractDocumentToBeSigned(JAdESSignatureParameters parameters, JWSJsonSerializationObject jwsJsonSerializationObject) { if (Utils.isStringNotBlank(jwsJsonSerializationObject.getPayload())) { // enveloping signature JWS jws = jwsJsonSerializationObject.getSignatures().get(0); byte[] payloadBytes; if (jws.isRfc7797UnencodedPayload()) { payloadBytes = jwsJsonSerializationObject.getPayload().getBytes(StandardCharsets.UTF_8); } else { payloadBytes = DSSJsonUtils.fromBase64Url(jwsJsonSerializationObject.getPayload()); } return Collections.singletonList(new InMemoryDocument(payloadBytes)); } else if (Utils.isCollectionNotEmpty(parameters.getDetachedContents())) { // detached signature return parameters.getDetachedContents(); } else { throw new IllegalArgumentException("The payload or detached content must be provided!"); } } @Override public DSSDocument build(SignatureValue signatureValue) { assertConfigurationValidity(parameters); JWS jws = getJWS(); if (jwsJsonSerializationObject == null) { jwsJsonSerializationObject = new JWSJsonSerializationObject(); if (!SignaturePackaging.DETACHED.equals(parameters.getSignaturePackaging())) { // do not include payload for detached case jwsJsonSerializationObject.setPayload(jws.getSignedPayload()); } } else { assertB64ConfigurationConsistent(); } byte[] signatureValueBytes = DSSASN1Utils.ensurePlainSignatureValue(parameters.getEncryptionAlgorithm(), signatureValue.getValue()); jws.setSignature(signatureValueBytes); jwsJsonSerializationObject.getSignatures().add(jws); JWSJsonSerializationGenerator generator = new JWSJsonSerializationGenerator(jwsJsonSerializationObject, parameters.getJwsSerializationType()); return generator.generate(); } /** * All not detached signatures must have the same 'b64' value */ private void assertB64ConfigurationConsistent() { // verify only for non-detached cases if (!SignaturePackaging.DETACHED.equals(parameters.getSignaturePackaging())) { boolean base64UrlEncodedPayload = parameters.isBase64UrlEncodedPayload(); for (JWS jws : jwsJsonSerializationObject.getSignatures()) { if (base64UrlEncodedPayload != !jws.isRfc7797UnencodedPayload()) { throw new IllegalArgumentException("'b64' value shall be the same for all signatures! " + "Change 'Base64UrlEncodedPayload' signature parameter or sign another file!"); } } } } private JWS getJWS() { JWS jws = new JWS(); incorporateHeader(jws); incorporatePayload(jws); return jws; } @Override public MimeType getMimeType() { return MimeType.JOSE_JSON; } @Override protected void assertConfigurationValidity(JAdESSignatureParameters signatureParameters) { SignaturePackaging packaging = signatureParameters.getSignaturePackaging(); if ((packaging != SignaturePackaging.ENVELOPING) && (packaging != SignaturePackaging.DETACHED)) { throw new IllegalArgumentException("Unsupported signature packaging for JSON Serialization Signature: " + packaging); } if (!JWSSerializationType.JSON_SERIALIZATION.equals(signatureParameters.getJwsSerializationType()) && jwsJsonSerializationObject != null) { throw new IllegalArgumentException(String.format("The '%s' type is not supported for a parallel signing!", signatureParameters.getJwsSerializationType())); } } }
esig/dss
dss-jades/src/main/java/eu/europa/esig/dss/jades/signature/JAdESSerializationBuilder.java
Java
lgpl-2.1
6,556
/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2003 by the OpenSG Forum * * * * www.opensg.org * * * * contact: dirk@opensg.org, gerrit.voss@vossg.org, jbehr@zgdv.de * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ #ifndef _OSGMFIELDVECTOR_H_ #define _OSGMFIELDVECTOR_H_ #ifdef __sgi #pragma once #endif #include "OSGConfig.h" #include <vector> OSG_BEGIN_NAMESPACE #if defined(__sgi) || defined(__linux) || defined(__APPLE__) || \ defined(__sun) || defined(__hpux) #if defined(__sgi) #pragma set woff 1375 #endif #if defined(__linux) || defined(__hpux) || defined(__APPLE__) || defined(__sun) # if defined(__GNUC__) # if __GNUC__ >= 3 # define OSG_STL_ALLOCATOR_DEFAULT(TP) = std::allocator<TP> # endif # elif defined (__ICL) # define OSG_STL_ALLOCATOR_DEFAULT(TP) = std::allocator<TP> # elif defined (OSG_HPUX_ACC) # define OSG_STL_ALLOCATOR_DEFAULT(TP) _RWSTD_COMPLEX_DEFAULT(std::allocator<TP>) # elif defined(OSG_SUN_CC) # define OSG_STL_ALLOCATOR_DEFAULT(TP) _RWSTD_COMPLEX_DEFAULT(std::allocator<TP>) # else # define OSG_STL_ALLOCATOR_DEFAULT(TP) = std::__STL_DEFAULT_ALLOCATOR(TP) # endif #else # define OSG_STL_ALLOCATOR_DEFAULT(TP) = std::__STL_DEFAULT_ALLOCATOR(TP) #endif /*! \ingroup GrpBaseField \ingroup GrpBaseFieldMulti \ingroup GrpLibOSGBase \nohierarchy */ template <class Tp, class Alloc OSG_STL_ALLOCATOR_DEFAULT(Tp) > class MFieldVector : public std::vector<Tp, Alloc> { public: typedef std::vector<Tp, Alloc> Inherited; private: typedef MFieldVector<Tp, Alloc> Self; public: typedef typename Inherited::allocator_type allocator_type; typedef typename Inherited::size_type size_type; explicit MFieldVector(const allocator_type& __a = allocator_type()); MFieldVector( size_type __n, const Tp &__value, const allocator_type &__a = allocator_type()); explicit MFieldVector(size_type __n); MFieldVector(const std::vector <Tp, Alloc>& __x); MFieldVector(const MFieldVector<Tp, Alloc>& __x); #ifdef __STL_MEMBER_TEMPLATES // Check whether it's an integral type. If so, it's not an iterator. template <class InputIterator> MFieldVector( InputIterator __first, InputIterator __last, const allocator_type &__a = allocator_type()); #else MFieldVector(const Tp *__first, const Tp *__last, const allocator_type &__a = allocator_type()); #endif /* __STL_MEMBER_TEMPLATES */ ~MFieldVector(); void shareValues (Self &other, bool bDeleteOld); void resolveShare(void ); void dump( UInt32 uiIndent = 0, const BitVector bvFlags = 0) const; }; #if defined(__sgi) #pragma reset woff 1375 #endif #elif defined(WIN32) /*! \ingroup GrpBaseField \ingroup GrpBaseFieldMulti \ingroup GrpLibOSGBase \nohierarchy */ #define OSG_STL_ALLOCATOR_DEFAULT(TP) = std::allocator< TP > template<class Ty, class A = std::allocator<Ty> > class MFieldVector : public std::vector<Ty, A> { public: typedef std::vector<Ty, A> Inherited; private : typedef typename Inherited::const_iterator It; typedef MFieldVector<Ty, A> Self; public : typedef typename Inherited::allocator_type allocator_type; typedef typename Inherited::size_type size_type; explicit MFieldVector(const A& _Al = A()); explicit MFieldVector( size_type _N, const Ty &_V = Ty(), const A &_Al = A ()); MFieldVector(const MFieldVector<Ty, A> &_X); MFieldVector( It _F, It _L, const A &_Al = A()); ~MFieldVector(void); void shareValues (Self &other, bool bDeleteOld); void resolveShare(void ); void dump( UInt32 uiIndent = 0, const BitVector bvFlags = 0) const; }; #endif OSG_END_NAMESPACE #include "OSGMFieldVector.inl" #endif /* _OSGMFIELDVECTOR_H_ */
jondo2010/OpenSG
Source/Base/Field/OSGMFieldVector.h
C
lgpl-2.1
7,023
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the demos of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef BROWSERWINDOW_H #define BROWSERWINDOW_H #include <QWidget> class QTimeLine; class QUrl; class BrowserView; class HomeView; class BrowserWindow : public QWidget { Q_OBJECT public: BrowserWindow(); private slots: void initialize(); void navigate(const QUrl &url); void gotoAddress(const QString &address); public slots: void showBrowserView(); void showHomeView(); void slide(int); protected: void keyReleaseEvent(QKeyEvent *event); void resizeEvent(QResizeEvent *event); private: HomeView *m_homeView; BrowserView *m_browserView; QTimeLine *m_timeLine; }; #endif // BROWSERWINDOW_H
radekp/qt
demos/embedded/anomaly/src/BrowserWindow.h
C
lgpl-2.1
2,136
/***************************************************************************** * VLCMediaDiscoverer.h: VLCKit.framework VLCMediaDiscoverer header ***************************************************************************** * Copyright (C) 2007 Pierre d'Herbemont * Copyright (C) 2015 Felix Paul Kühne * Copyright (C) 2007, 2015 VLC authors and VideoLAN * $Id$ * * Authors: Pierre d'Herbemont <pdherbemont # videolan.org> * Felix Paul Kühne <fkuehne # videolan.org> * * 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., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #import <Foundation/Foundation.h> #import "VLCMediaList.h" @class VLCLibrary; @class VLCMediaList; @class VLCMediaDiscoverer; /** * VLCMediaDiscovererDelegate */ @protocol VLCMediaDiscovererDelegate <NSObject> @optional /** * delegate method triggered when a discoverer was started * * \param the discoverer that was started */ - (void)discovererStarted:(VLCMediaDiscoverer *)theDiscoverer; /** * delegate method triggered when a discoverer was stopped * * \param the discoverer that was stopped */ - (void)discovererStopped:(VLCMediaDiscoverer *)theDiscoverer; @end /** * VLCMediaDiscoverer */ @interface VLCMediaDiscoverer : NSObject @property (nonatomic, readonly) VLCLibrary *libraryInstance; /** * delegate property to listen to start/stop events */ @property (weak, readwrite) id<VLCMediaDiscovererDelegate> delegate; /** * Maintains a list of available media discoverers. This list is populated as new media * discoverers are created. * \return A list of available media discoverers. */ + (NSArray *)availableMediaDiscoverer; /* Initializers */ /** * Initializes new object with specified name. * \param aServiceName Name of the service for this VLCMediaDiscoverer object. * \returns Newly created media discoverer. * \note with VLCKit 3.0 and above, you need to start the discoverer explicitly after creation */ - (instancetype)initWithName:(NSString *)aServiceName; /** * start media discovery * \returns -1 if start failed, otherwise 0 */ - (int)startDiscoverer; /** * stop media discovery */ - (void)stopDiscoverer; /** * a read-only property to retrieve the list of discovered media items */ @property (weak, readonly) VLCMediaList *discoveredMedia; /** * returns the localized name of the discovery module if available, otherwise in US English */ @property (readonly, copy) NSString *localizedName; /** * read-only property to check if the discovery service is active * \return boolean value */ @property (readonly) BOOL isRunning; @end
larrytin/VLCKit
Headers/Public/VLCMediaDiscoverer.h
C
lgpl-2.1
3,312
/* * This file is part of the KDE libraries * Copyright (C) 2007 Harri Porten <porten@kde.org> * Copyright (C) 2006 George Staikos <staikos@kde.org> * Copyright (C) 2006 Alexey Proskuryakov <ap@nypop.com> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. * */ #ifndef KJS_UNICODE_LIBC_H #define KJS_UNICODE_LIBC_H #include "wtf/ASCIICType.h" #include <assert.h> #include "../UnicodeCategory.h" namespace WTF { namespace Unicode { inline int toLower(uint16_t *str, int strLength, uint16_t *&destIfNeeded) { destIfNeeded = nullptr; for (int i = 0; i < strLength; ++i) { str[i] = toASCIILower(str[i]); } return strLength; } inline int toUpper(uint16_t *str, int strLength, uint16_t *&destIfNeeded) { destIfNeeded = nullptr; for (int i = 0; i < strLength; ++i) { str[i] = toASCIIUpper(str[i]); } return strLength; } inline bool isSeparatorSpace(int32_t c) { return (c & 0xffff0000) == 0 && isASCIISpace(static_cast<unsigned short>(c)); } inline CharCategory category(int32_t c) { if (c < 0) { return NoCategory; } if (c < 0x000000ff) { static const CharCategory cats[] = { Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Separator_Space, Punctuation_Other, Punctuation_Other, Punctuation_Other, Symbol_Currency, Punctuation_Other, Punctuation_Other, Punctuation_Other, Punctuation_Open, Punctuation_Close, Punctuation_Other, Symbol_Math, Punctuation_Other, Punctuation_Dash, Punctuation_Other, Punctuation_Other, Number_DecimalDigit, Number_DecimalDigit, Number_DecimalDigit, Number_DecimalDigit, Number_DecimalDigit, Number_DecimalDigit, Number_DecimalDigit, Number_DecimalDigit, Number_DecimalDigit, Number_DecimalDigit, Punctuation_Other, Punctuation_Other, Symbol_Math, Symbol_Math, Symbol_Math, Punctuation_Other, Punctuation_Other, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Punctuation_Open, Punctuation_Other, Punctuation_Close, Symbol_Modifier, Punctuation_Connector, Symbol_Modifier, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Punctuation_Open, Symbol_Math, Punctuation_Close, Symbol_Math, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Other_Control, Separator_Space, Punctuation_Other, Symbol_Currency, Symbol_Currency, Symbol_Currency, Symbol_Currency, Symbol_Other, Symbol_Other, Symbol_Modifier, Symbol_Other, Letter_Lowercase, Punctuation_InitialQuote, Symbol_Math, Other_Format, Symbol_Other, Symbol_Modifier, Symbol_Other, Symbol_Math, Number_Other, Number_Other, Symbol_Modifier, Letter_Lowercase, Symbol_Other, Punctuation_Other, Symbol_Modifier, Number_Other, Letter_Lowercase, Punctuation_FinalQuote, Number_Other, Number_Other, Number_Other, Punctuation_Other, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Symbol_Math, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Uppercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Symbol_Math, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase, Letter_Lowercase }; assert(sizeof(cats) / sizeof(CharCategory) == 0x0100); return cats[c]; } // FIXME: implement for the rest ... return NoCategory; } } } #endif
KDE/kjs
src/wtf/unicode/libc/UnicodeLibC.h
C
lgpl-2.1
7,394
/**************************************************************************** * Copyright 2015 Evan Drumwright * This library is distributed under the terms of the Apache V2.0 License ****************************************************************************/ #ifndef PLANARJOINT #error This class is not to be included by the user directly. Use PlanarJointd.h or PlanarJointf.h instead. #endif /// Defines a joint that constrains motion to a plane class PLANARJOINT : public virtual JOINT { public: PLANARJOINT(); virtual void update_spatial_axes(); virtual void determine_q(VECTORN& q); virtual boost::shared_ptr<const POSE3> get_induced_pose(); virtual unsigned num_dof() const { return 3; } virtual void evaluate_constraints(REAL C[]); virtual void calc_constraint_jacobian(bool inboard, MATRIXN& Cq); virtual void calc_constraint_jacobian_dot(bool inboard, MATRIXN& Cq); virtual bool is_singular_config() const { return false; } void set_normal(const VECTOR3& normal); virtual const std::vector<SVELOCITY>& get_spatial_axes_dot() { return _s_dot; } protected: void update_offset(); /// Vectors orthogonal to the normal vector in the outboard link frame VECTOR3 _vi, _vj; /// The plane normal and tangents (global frame) VECTOR3 _normal, _tan1, _tan2; /// The plane offset such that n'*x = offset REAL _offset; /// The derivative of the spatial axis std::vector<SVELOCITY> _s_dot; }; // end class
PositronicsLab/Ravelin
include/Ravelin/PlanarJoint.h
C
lgpl-2.1
1,505
/* * Copyright 2002-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.toplink.support; import oracle.toplink.exceptions.TopLinkException; import oracle.toplink.sessions.Session; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.support.DaoSupport; import org.springframework.orm.toplink.SessionFactory; import org.springframework.orm.toplink.SessionFactoryUtils; import org.springframework.orm.toplink.TopLinkTemplate; /** * Convenient super class for TopLink data access objects. * * <p>Requires a SessionFactory to be set, providing a TopLinkTemplate * based on it to subclasses. Can alternatively be initialized directly via * a TopLinkTemplate, to reuse the latter's settings like SessionFactory, * exception translator, etc. * * <p>This base class is mainly intended for TopLinkTemplate usage * but can also be used when working with SessionFactoryUtils directly, * e.g. in combination with TopLinkInterceptor-managed Sessions. * Convenience <code>getSession</code> and <code>releaseSession</code> * methods are provided for that usage style. * * @author Juergen Hoeller * @since 1.2 * @see #setSessionFactory * @see #setTopLinkTemplate * @see #getSession * @see #releaseSession * @see org.springframework.orm.toplink.TopLinkTemplate * @see org.springframework.orm.toplink.TopLinkInterceptor */ public abstract class TopLinkDaoSupport extends DaoSupport { private TopLinkTemplate topLinkTemplate; /** * Set the TopLink SessionFactory to be used by this DAO. * Will automatically create a TopLinkTemplate for the given SessionFactory. * @see #createTopLinkTemplate * @see #setTopLinkTemplate */ public final void setSessionFactory(SessionFactory sessionFactory) { this.topLinkTemplate = createTopLinkTemplate(sessionFactory); } /** * Create a TopLinkTemplate for the given SessionFactory. * Only invoked if populating the DAO with a SessionFactory reference! * <p>Can be overridden in subclasses to provide a TopLinkTemplate instance * with different configuration, or a custom TopLinkTemplate subclass. * @param sessionFactory the TopLink SessionFactory to create a TopLinkTemplate for * @return the new TopLinkTemplate instance * @see #setSessionFactory */ protected TopLinkTemplate createTopLinkTemplate(SessionFactory sessionFactory) { return new TopLinkTemplate(sessionFactory); } /** * Return the TopLink SessionFactory used by this DAO. */ public final SessionFactory getSessionFactory() { return (this.topLinkTemplate != null ? this.topLinkTemplate.getSessionFactory() : null); } /** * Set the TopLinkTemplate for this DAO explicitly, * as an alternative to specifying a SessionFactory. * @see #setSessionFactory */ public final void setTopLinkTemplate(TopLinkTemplate topLinkTemplate) { this.topLinkTemplate = topLinkTemplate; } /** * Return the TopLinkTemplate for this DAO, * pre-initialized with the SessionFactory or set explicitly. */ public final TopLinkTemplate getTopLinkTemplate() { return topLinkTemplate; } protected final void checkDaoConfig() { if (this.topLinkTemplate == null) { throw new IllegalArgumentException("sessionFactory or topLinkTemplate is required"); } } /** * Get a TopLink Session, either from the current transaction or a new one. * The latter is only allowed if the "allowCreate" setting of this bean's * TopLinkTemplate is true. * <p><b>Note that this is not meant to be invoked from TopLinkTemplate code * but rather just in plain TopLink code.</b> Either rely on a thread-bound * Session (via TopLinkInterceptor), or use it in combination with * <code>releaseSession</code>. * <p>In general, it is recommended to use TopLinkTemplate, either with * the provided convenience operations or with a custom TopLinkCallback * that provides you with a Session to work on. TopLinkTemplate will care * for all resource management and for proper exception conversion. * @return the TopLink Session * @throws DataAccessResourceFailureException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and allowCreate false * @see TopLinkTemplate * @see org.springframework.orm.toplink.SessionFactoryUtils#getSession(SessionFactory, boolean) * @see org.springframework.orm.toplink.TopLinkInterceptor * @see org.springframework.orm.toplink.TopLinkTemplate * @see org.springframework.orm.toplink.TopLinkCallback */ protected final Session getSession() throws DataAccessResourceFailureException, IllegalStateException { return getSession(this.topLinkTemplate.isAllowCreate()); } /** * Get a TopLink Session, either from the current transaction or a new one. * The latter is only allowed if "allowCreate" is true. * <p><b>Note that this is not meant to be invoked from TopLinkTemplate code * but rather just in plain TopLink code.</b> Either rely on a thread-bound * Session (via TopLinkInterceptor), or use it in combination with * <code>releaseSession</code>. * <p>In general, it is recommended to use TopLinkTemplate, either with * the provided convenience operations or with a custom TopLinkCallback * that provides you with a Session to work on. TopLinkTemplate will care * for all resource management and for proper exception conversion. * @param allowCreate if a new Session should be created if no thread-bound found * @return the TopLink Session * @throws DataAccessResourceFailureException if the Session couldn't be created * @throws IllegalStateException if no thread-bound Session found and allowCreate false * @see org.springframework.orm.toplink.SessionFactoryUtils#getSession(SessionFactory, boolean) * @see org.springframework.orm.toplink.TopLinkInterceptor * @see org.springframework.orm.toplink.TopLinkTemplate * @see org.springframework.orm.toplink.TopLinkCallback */ protected final Session getSession(boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { return SessionFactoryUtils.getSession(this.getSessionFactory(), allowCreate); } /** * Convert the given TopLinkException to an appropriate exception from the * <code>org.springframework.dao</code> hierarchy. Will automatically detect * wrapped SQLExceptions and convert them accordingly. * <p>Delegates to the convertTopLinkAccessException method of this * DAO's TopLinkTemplate. * @param ex TopLinkException that occured * @return the corresponding DataAccessException instance * @see #setTopLinkTemplate * @see org.springframework.orm.toplink.TopLinkTemplate#convertTopLinkAccessException */ protected final DataAccessException convertTopLinkAccessException(TopLinkException ex) { return this.topLinkTemplate.convertTopLinkAccessException(ex); } /** * Close the given TopLink Session, created via this DAO's SessionFactory, * if it isn't bound to the thread. * @param session the TopLink Session to close * @see org.springframework.orm.toplink.SessionFactoryUtils#releaseSession */ protected final void releaseSession(Session session) { SessionFactoryUtils.releaseSession(session, getSessionFactory()); } }
raedle/univis
lib/springframework-1.2.8/src/org/springframework/orm/toplink/support/TopLinkDaoSupport.java
Java
lgpl-2.1
7,833
// --------------------------------------------------------------------- // // Copyright (C) 1999 - 2017 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, 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. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- #ifndef dealii_fe_system_h #define dealii_fe_system_h /*---------------------------- fe_system.h ---------------------------*/ #include <deal.II/base/config.h> #include <deal.II/base/thread_management.h> #include <deal.II/fe/fe.h> #include <deal.II/fe/fe_tools.h> #include <vector> #include <memory> #include <utility> #include <type_traits> DEAL_II_NAMESPACE_OPEN template <int dim, int spacedim> class FE_Enriched; /** * This class provides an interface to group several elements together into * one. To the outside world, the resulting object looks just like a usual * finite element object, which is composed of several other finite elements * that are possibly of different type. The result is then a vector-valued * finite element. An example is given in the documentation of namespace * FETools::Compositing, when using the "tensor product" strategy. * * %Vector valued elements are discussed in a number of * tutorial programs, for example step-8, step-20, step-21, and in particular * in the * @ref vector_valued * module. * * @dealiiVideoLecture{19,20} * * <h3>FESystem, components and blocks</h3> * * An FESystem, except in the most trivial case, produces a vector-valued * finite element with several components. The number of components * n_components() corresponds to the dimension of the solution function in the * PDE system, and correspondingly also to the number of equations your PDE * system has. For example, the mixed Laplace system covered in step-20 has * $d+1$ components in $d$ space dimensions: the scalar pressure and the $d$ * components of the velocity vector. Similarly, the elasticity equation * covered in step-8 has $d$ components in $d$ space dimensions. In general, * the number of components of a FESystem element is the accumulated number of * components of all base elements times their multiplicities. A bit more on * components is also given in the * @ref GlossComponent "glossary entry on components". * * While the concept of components is important from the viewpoint of a * partial differential equation, the finite element side looks a bit * different Since not only FESystem, but also vector-valued elements like * FE_RaviartThomas, have several components. The concept needed here is a * @ref GlossBlock "block". * Each block encompasses the set of degrees of freedom associated with a * single base element of an FESystem, where base elements with multiplicities * count multiple times. These blocks are usually addressed using the * information in DoFHandler::block_info(). The number of blocks of a FESystem * object is simply the sum of all multiplicities of base elements and is * given by n_blocks(). * * For example, the FESystem for the Taylor-Hood element for the three- * dimensional Stokes problem can be built using the code * * @code * FE_Q<3> u(2); * FE_Q<3> p(1); * FESystem<3> sys1(u,3, p,1); * @endcode * * This example creates an FESystem @p sys1 with four components, three for * the velocity components and one for the pressure, and also four blocks with * the degrees of freedom of each of the velocity components and the pressure * in a separate block each. The number of blocks is four since the first base * element is repeated three times. * * On the other hand, a Taylor-Hood element can also be constructed using * * @code * FESystem<3> U(u,3); * FESystem<3> sys2(U,1, p,1); * @endcode * * The FESystem @p sys2 created here has the same four components, but the * degrees of freedom are distributed into only two blocks. The first block * has all velocity degrees of freedom from @p U, while the second block * contains the pressure degrees of freedom. Note that while @p U itself has 3 * blocks, the FESystem @p sys2 does not attempt to split @p U into its base * elements but considers it a block of its own. By blocking all velocities * into one system first as in @p sys2, we achieve the same block structure * that would be generated if instead of using a $Q_2^3$ element for the * velocities we had used vector-valued base elements, for instance like using * a mixed discretization of Darcy's law using * * @code * FE_RaviartThomas<3> u(1); * FE_DGQ<3> p(1); * FESystem<3> sys3(u,1, p,1); * @endcode * * This example also produces a system with four components, but only two * blocks. * * In most cases, the composed element behaves as if it were a usual element. * It just has more degrees of freedom than most of the "common" elements. * However the underlying structure is visible in the restriction, * prolongation and interface constraint matrices, which do not couple the * degrees of freedom of the base elements. E.g. the continuity requirement is * imposed for the shape functions of the subobjects separately; no * requirement exist between shape functions of different subobjects, i.e. in * the above example: on a hanging node, the respective value of the @p u * velocity is only coupled to @p u at the vertices and the line on the larger * cell next to this vertex, but there is no interaction with @p v and @p w of * this or the other cell. * * * <h3>Internal information on numbering of degrees of freedom</h3> * * The overall numbering of degrees of freedom is as follows: for each * subobject (vertex, line, quad, or hex), the degrees of freedom are numbered * such that we run over all subelements first, before turning for the next * dof on this subobject or for the next subobject. For example, for an * element of three components in one space dimension, the first two * components being cubic lagrange elements and the third being a quadratic * lagrange element, the ordering for the system <tt>s=(u,v,p)</tt> is: * * <ul> * <li> First vertex: <tt>u0, v0, p0 = s0, s1, s2</tt> * <li> Second vertex: <tt>u1, v1, p1 = s3, s4, s5</tt> * <li> First component on the line: <tt>u2, u3 = s4, s5</tt> * <li> Second component on the line: <tt>v2, v3 = s6, s7</tt>. * <li> Third component on the line: <tt>p2 = s8</tt>. * </ul> * That said, you should not rely on this numbering in your application as * these %internals might change in future. Rather use the functions * system_to_component_index() and component_to_system_index(). * * For more information on the template parameter <tt>spacedim</tt> see the * documentation of Triangulation. * * @ingroup febase fe vector_valued * * @author Wolfgang Bangerth, Guido Kanschat, 1999, 2002, 2003, 2006, Ralf * Hartmann 2001. */ template <int dim, int spacedim=dim> class FESystem : public FiniteElement<dim,spacedim> { public: /** * Constructor. Take a finite element and the number of elements you want to * group together using this class. * * The object @p fe is not actually used for anything other than creating a * copy that will then be owned by the current object. In other words, it is * completely fine to call this constructor with a temporary object for the * finite element, as in this code snippet: * @code * FESystem<dim> fe (FE_Q<dim>(2), 2); * @endcode * Here, <code>FE_Q@<dim@>(2)</code> constructs an unnamed, temporary object * that is passed to the FESystem constructor to create a finite element * that consists of two components, both of which are quadratic FE_Q * elements. The temporary is destroyed again at the end of the code that * corresponds to this line, but this does not matter because FESystem * creates its own copy of the FE_Q object. * * This constructor (or its variants below) is used in essentially all * tutorial programs that deal with vector valued problems. See step-8, * step-20, step-22 and others for use cases. Also see the module on * @ref vector_valued "Handling vector valued problems". * * @dealiiVideoLecture{19,20} * * @param[in] fe The finite element that will be used to represent the * components of this composed element. * @param[in] n_elements An integer denoting how many copies of @p fe this * element should consist of. */ FESystem (const FiniteElement<dim,spacedim> &fe, const unsigned int n_elements); /** * Constructor for mixed discretizations with two base elements. * * See the other constructor above for an explanation of the general idea of * composing elements. */ FESystem (const FiniteElement<dim,spacedim> &fe1, const unsigned int n1, const FiniteElement<dim,spacedim> &fe2, const unsigned int n2); /** * Constructor for mixed discretizations with three base elements. * * See the other constructor above for an explanation of the general idea of * composing elements. */ FESystem (const FiniteElement<dim,spacedim> &fe1, const unsigned int n1, const FiniteElement<dim,spacedim> &fe2, const unsigned int n2, const FiniteElement<dim,spacedim> &fe3, const unsigned int n3); /** * Constructor for mixed discretizations with four base elements. * * See the first of the other constructors above for an explanation of the * general idea of composing elements. */ FESystem (const FiniteElement<dim,spacedim> &fe1, const unsigned int n1, const FiniteElement<dim,spacedim> &fe2, const unsigned int n2, const FiniteElement<dim,spacedim> &fe3, const unsigned int n3, const FiniteElement<dim,spacedim> &fe4, const unsigned int n4); /** * Constructor for mixed discretizations with five base elements. * * See the first of the other constructors above for an explanation of the * general idea of composing elements. */ FESystem (const FiniteElement<dim,spacedim> &fe1, const unsigned int n1, const FiniteElement<dim,spacedim> &fe2, const unsigned int n2, const FiniteElement<dim,spacedim> &fe3, const unsigned int n3, const FiniteElement<dim,spacedim> &fe4, const unsigned int n4, const FiniteElement<dim,spacedim> &fe5, const unsigned int n5); /** * Same as above but for any number of base elements. Pointers to the base * elements and their multiplicities are passed as vectors to this * constructor. The lengths of these vectors are assumed to be equal. * * As above, the finite element objects pointed to by the first argument are * not actually used other than to create copies internally. Consequently, * you can delete these pointers immediately again after calling this * constructor. * * <h4>How to use this constructor</h4> * * Using this constructor is a bit awkward at times because you need to pass * two vectors in a place where it may not be straightforward to construct * such a vector -- for example, in the member initializer list of a class * with an FESystem member variable. For example, if your main class looks * like this: * @code * template <int dim> * class MySimulator { * public: * MySimulator (const unsigned int polynomial_degree); * private: * FESystem<dim> fe; * }; * * template <int dim> * MySimulator<dim>::MySimulator (const unsigned int polynomial_degree) * : * fe (...) // what to pass here??? * {} * @endcode * * Using the C++11 language standard (or later) you could do something like * this to create an element with four base elements and multiplicities 1, * 2, 3 and 4: * @code * template <int dim> * MySimulator<dim>::MySimulator (const unsigned int polynomial_degree) * : * fe (std::vector<const FiniteElement<dim>*> { new FE_Q<dim>(1), * new FE_Q<dim>(2), * new FE_Q<dim>(3), * new FE_Q<dim>(4) }, * std::vector<unsigned int> { 1, 2, 3, 4 }) * {} * @endcode * This creates two vectors in place and initializes them using the * initializer list enclosed in braces <code>{ ... }</code>. * * This code has a problem: it creates four memory leaks because the first * vector above is created with pointers to elements that are allocated with * <code>new</code> but never destroyed. Without C++11, you would have another * problem: brace-initializer don't exist in earlier C++ standards. * * The solution to the second of these problems is to create two static * member functions that can create vectors. Here is an example: * @code * template <int dim> * class MySimulator { * public: * MySimulator (const unsigned int polynomial_degree); * * private: * FESystem<dim> fe; * * static std::vector<const FiniteElement<dim>*> * create_fe_list (const unsigned int polynomial_degree); * * static std::vector<unsigned int> * create_fe_multiplicities (); * }; * * template <int dim> * std::vector<const FiniteElement<dim>*> * MySimulator<dim>::create_fe_list (const unsigned int polynomial_degree) * { * std::vector<const FiniteElement<dim>*> fe_list; * fe_list.push_back (new FE_Q<dim>(1)); * fe_list.push_back (new FE_Q<dim>(2)); * fe_list.push_back (new FE_Q<dim>(3)); * fe_list.push_back (new FE_Q<dim>(4)); * return fe_list; * } * * template <int dim> * std::vector<unsigned int> * MySimulator<dim>::create_fe_multiplicities () * { * std::vector<unsigned int> multiplicities; * multiplicities.push_back (1); * multiplicities.push_back (2); * multiplicities.push_back (3); * multiplicities.push_back (4); * return multiplicities; * } * * template <int dim> * MySimulator<dim>::MySimulator (const unsigned int polynomial_degree) * : * fe (create_fe_list (polynomial_degree), * create_fe_multiplicities ()) * {} * @endcode * * The way this works is that we have two static member functions that * create the necessary vectors to pass to the constructor of the member * variable <code>fe</code>. They need to be static because they are called * during the constructor of <code>MySimulator</code> at a time when the * <code>*this</code> object isn't fully constructed and, consequently, * regular member functions cannot be called yet. * * The code above does not solve the problem with the memory leak yet, * though: the <code>create_fe_list()</code> function creates a vector of * pointers, but nothing destroys these. This is the solution: * @code * template <int dim> * class MySimulator { * public: * MySimulator (const unsigned int polynomial_degree); * * private: * FESystem<dim> fe; * * struct VectorElementDestroyer { * const std::vector<const FiniteElement<dim>*> data; * VectorElementDestroyer (const std::vector<const FiniteElement<dim>*> &pointers); * ~VectorElementDestroyer (); // destructor to delete the pointers * const std::vector<const FiniteElement<dim>*> & get_data () const; * }; * * static std::vector<const FiniteElement<dim>*> * create_fe_list (const unsigned int polynomial_degree); * * static std::vector<unsigned int> * create_fe_multiplicities (); * }; * * template <int dim> * MySimulator<dim>::VectorElementDestroyer:: * VectorElementDestroyer (const std::vector<const FiniteElement<dim>*> &pointers) * : data(pointers) * {} * * template <int dim> * MySimulator<dim>::VectorElementDestroyer:: * ~VectorElementDestroyer () * { * for (unsigned int i=0; i<data.size(); ++i) * delete data[i]; * } * * template <int dim> * const std::vector<const FiniteElement<dim>*> & * MySimulator<dim>::VectorElementDestroyer:: * get_data () const * { * return data; * } * * * template <int dim> * MySimulator<dim>::MySimulator (const unsigned int polynomial_degree) * : * fe (VectorElementDestroyer(create_fe_list (polynomial_degree)).get_data(), * create_fe_multiplicities ()) * {} * @endcode * * In other words, the vector we receive from the * <code>create_fe_list()</code> is packed into a temporary object of type * <code>VectorElementDestroyer</code>; we then get the vector from this * temporary object immediately to pass it to the constructor of * <code>fe</code>; and finally, the <code>VectorElementDestroyer</code> * destructor is called at the end of the entire expression (after the * constructor of <code>fe</code> has finished) and destroys the elements of * the temporary vector. Voila: not short nor elegant, but it works! */ FESystem (const std::vector<const FiniteElement<dim,spacedim>*> &fes, const std::vector<unsigned int> &multiplicities); /** * Constructor taking an arbitrary number of parameters of type * <code>std::pair<std::unique_ptr<FiniteElement<dim, spacedim>>, unsigned int></code>. * In combination with FiniteElement::operator^, this allows to construct FESystem objects * as follows: * @code * FiniteElementType1<dim,spacedim> fe_1; * FiniteElementType1<dim,spacedim> fe_2; * FESystem<dim,spacedim> fe_system = ( fe_1^dim, fe_2^1 ); * @endcode * * The FiniteElement objects are not actually used for anything other than creating a * copy that will then be owned by the current object. In other words, it is * completely fine to call this constructor with a temporary object for the * finite element, as in this code snippet: * @code * FESystem<dim> fe (FE_Q<dim>(2)^2); * @endcode * Here, <code>FE_Q@<dim@>(2)</code> constructs an unnamed, temporary object * that is passed to the FESystem constructor to create a finite element * that consists of two components, both of which are quadratic FE_Q * elements. The temporary is destroyed again at the end of the code that * corresponds to this line, but this does not matter because FESystem * creates its own copy of the FE_Q object. * * As a shortcut, this constructor also allows calling * @code * FESystem<dim> fe (FE_Q<dim>(2)^dim, FE_Q<dim>(1)); * @endcode * instead of the more explicit * @code * FESystem<dim> fe (FE_Q<dim>(2)^dim, FE_Q<dim>(1)^1); * @endcode * In other words, if no multiplicity for an element is explicitly specified * via the exponentiation operation, then it is assumed to be one (as one * would have expected). */ template <class... FEPairs, typename = typename enable_if_all< (std::is_same<typename std::decay<FEPairs>::type, std::pair<std::unique_ptr<FiniteElement<dim, spacedim>>, unsigned int>>::value || std::is_base_of<FiniteElement<dim, spacedim>, typename std::decay<FEPairs>::type>::value) ... >::type > FESystem (FEPairs &&... fe_pairs); /** * Same as above allowing the following syntax: * @code * FiniteElementType1<dim,spacedim> fe_1; * FiniteElementType1<dim,spacedim> fe_2; * FESystem<dim,spacedim> fe_system = { fe_1^dim, fe_2^1 }; * @endcode */ FESystem (const std::initializer_list<std::pair<std::unique_ptr<FiniteElement<dim, spacedim>>, unsigned int>> &fe_systems); /** * Copy constructor. This constructor is deleted, i.e., copying * FESystem objects is not allowed. */ FESystem (const FESystem<dim,spacedim> &) = delete; /** * Move constructor. */ FESystem (FESystem<dim,spacedim> &&) = default; /** * Destructor. */ virtual ~FESystem () = default; /** * Return a string that uniquely identifies a finite element. This element * returns a string that is composed of the strings @p name1...@p nameN * returned by the basis elements. From these, we create a sequence * <tt>FESystem<dim>[name1^m1-name2^m2-...-nameN^mN]</tt>, where @p mi are * the multiplicities of the basis elements. If a multiplicity is equal to * one, then the superscript is omitted. */ virtual std::string get_name () const; virtual std::unique_ptr<FiniteElement<dim,spacedim> > clone() const; virtual UpdateFlags requires_update_flags (const UpdateFlags update_flags) const; // make variant with ComponentMask also available: using FiniteElement<dim,spacedim>::get_sub_fe; /** * @copydoc FiniteElement<dim,spacedim>::get_sub_fe() */ virtual const FiniteElement<dim,spacedim> & get_sub_fe (const unsigned int first_component, const unsigned int n_selected_components) const; /** * Return the value of the @p ith shape function at the point @p p. @p p is * a point on the reference element. Since this finite element is always * vector-valued, we return the value of the only non-zero component of the * vector value of this shape function. If the shape function has more than * one non-zero component (which we refer to with the term non-primitive), * then throw an exception of type @p ExcShapeFunctionNotPrimitive. * * An @p ExcUnitShapeValuesDoNotExist is thrown if the shape values of the * @p FiniteElement (corresponding to the @p ith shape function) depend on * the shape of the cell in real space. */ virtual double shape_value (const unsigned int i, const Point<dim> &p) const; /** * Return the value of the @p componentth vector component of the @p ith * shape function at the point @p p. See the FiniteElement base class for * more information about the semantics of this function. * * Since this element is vector valued in general, it relays the computation * of these values to the base elements. */ virtual double shape_value_component (const unsigned int i, const Point<dim> &p, const unsigned int component) const; /** * Return the gradient of the @p ith shape function at the point @p p. @p p * is a point on the reference element, and likewise the gradient is the * gradient on the unit cell with respect to unit cell coordinates. Since * this finite element is always vector-valued, we return the value of the * only non-zero component of the vector value of this shape function. If * the shape function has more than one non-zero component (which we refer * to with the term non-primitive), then throw an exception of type @p * ExcShapeFunctionNotPrimitive. * * An @p ExcUnitShapeValuesDoNotExist is thrown if the shape values of the * @p FiniteElement (corresponding to the @p ith shape function) depend on * the shape of the cell in real space. */ virtual Tensor<1,dim> shape_grad (const unsigned int i, const Point<dim> &p) const; /** * Return the gradient of the @p componentth vector component of the @p ith * shape function at the point @p p. See the FiniteElement base class for * more information about the semantics of this function. * * Since this element is vector valued in general, it relays the computation * of these values to the base elements. */ virtual Tensor<1,dim> shape_grad_component (const unsigned int i, const Point<dim> &p, const unsigned int component) const; /** * Return the tensor of second derivatives of the @p ith shape function at * point @p p on the unit cell. The derivatives are derivatives on the unit * cell with respect to unit cell coordinates. Since this finite element is * always vector-valued, we return the value of the only non-zero component * of the vector value of this shape function. If the shape function has * more than one non-zero component (which we refer to with the term non- * primitive), then throw an exception of type @p * ExcShapeFunctionNotPrimitive. * * An @p ExcUnitShapeValuesDoNotExist is thrown if the shape values of the * @p FiniteElement (corresponding to the @p ith shape function) depend on * the shape of the cell in real space. */ virtual Tensor<2,dim> shape_grad_grad (const unsigned int i, const Point<dim> &p) const; /** * Return the second derivatives of the @p componentth vector component of * the @p ith shape function at the point @p p. See the FiniteElement base * class for more information about the semantics of this function. * * Since this element is vector valued in general, it relays the computation * of these values to the base elements. */ virtual Tensor<2,dim> shape_grad_grad_component (const unsigned int i, const Point<dim> &p, const unsigned int component) const; /** * Return the tensor of third derivatives of the @p ith shape function at * point @p p on the unit cell. The derivatives are derivatives on the unit * cell with respect to unit cell coordinates. Since this finite element is * always vector-valued, we return the value of the only non-zero component * of the vector value of this shape function. If the shape function has * more than one non-zero component (which we refer to with the term non- * primitive), then throw an exception of type @p * ExcShapeFunctionNotPrimitive. * * An @p ExcUnitShapeValuesDoNotExist is thrown if the shape values of the * @p FiniteElement (corresponding to the @p ith shape function) depend on * the shape of the cell in real space. */ virtual Tensor<3,dim> shape_3rd_derivative (const unsigned int i, const Point<dim> &p) const; /** * Return the third derivatives of the @p componentth vector component of * the @p ith shape function at the point @p p. See the FiniteElement base * class for more information about the semantics of this function. * * Since this element is vector valued in general, it relays the computation * of these values to the base elements. */ virtual Tensor<3,dim> shape_3rd_derivative_component (const unsigned int i, const Point<dim> &p, const unsigned int component) const; /** * Return the tensor of fourth derivatives of the @p ith shape function at * point @p p on the unit cell. The derivatives are derivatives on the unit * cell with respect to unit cell coordinates. Since this finite element is * always vector-valued, we return the value of the only non-zero component * of the vector value of this shape function. If the shape function has * more than one non-zero component (which we refer to with the term non- * primitive), then throw an exception of type @p * ExcShapeFunctionNotPrimitive. * * An @p ExcUnitShapeValuesDoNotExist is thrown if the shape values of the * @p FiniteElement (corresponding to the @p ith shape function) depend on * the shape of the cell in real space. */ virtual Tensor<4,dim> shape_4th_derivative (const unsigned int i, const Point<dim> &p) const; /** * Return the fourth derivatives of the @p componentth vector component of * the @p ith shape function at the point @p p. See the FiniteElement base * class for more information about the semantics of this function. * * Since this element is vector valued in general, it relays the computation * of these values to the base elements. */ virtual Tensor<4,dim> shape_4th_derivative_component (const unsigned int i, const Point<dim> &p, const unsigned int component) const; /** * Return the matrix interpolating from the given finite element to the * present one. The size of the matrix is then @p dofs_per_cell times * <tt>source.dofs_per_cell</tt>. * * These matrices are available if source and destination element are both * @p FESystem elements, have the same number of base elements with same * element multiplicity, and if these base elements also implement their @p * get_interpolation_matrix functions. Otherwise, an exception of type * FiniteElement<dim,spacedim>::ExcInterpolationNotImplemented is thrown. */ virtual void get_interpolation_matrix (const FiniteElement<dim,spacedim> &source, FullMatrix<double> &matrix) const; /** * Access to a composing element. The index needs to be smaller than the * number of base elements. Note that the number of base elements may in * turn be smaller than the number of components of the system element, if * the multiplicities are greater than one. */ virtual const FiniteElement<dim,spacedim> & base_element (const unsigned int index) const; /** * This function returns @p true, if the shape function @p shape_index has * non-zero function values somewhere on the face @p face_index. */ virtual bool has_support_on_face (const unsigned int shape_index, const unsigned int face_index) const; /** * Projection from a fine grid space onto a coarse grid space. Overrides the * respective method in FiniteElement, implementing lazy evaluation * (initialize when requested). * * If this projection operator is associated with a matrix @p P, then the * restriction of this matrix @p P_i to a single child cell is returned * here. * * The matrix @p P is the concatenation or the sum of the cell matrices @p * P_i, depending on the #restriction_is_additive_flags. This distinguishes * interpolation (concatenation) and projection with respect to scalar * products (summation). * * Row and column indices are related to coarse grid and fine grid spaces, * respectively, consistent with the definition of the associated operator. * * If projection matrices are not implemented in the derived finite element * class, this function aborts with an exception of type * FiniteElement::ExcProjectionVoid. You can check whether this would happen * by first calling the restriction_is_implemented() or the * isotropic_restriction_is_implemented() function. */ virtual const FullMatrix<double> & get_restriction_matrix (const unsigned int child, const RefinementCase<dim> &refinement_case=RefinementCase<dim>::isotropic_refinement) const; /** * Embedding matrix between grids. Overrides the respective method in * FiniteElement, implementing lazy evaluation (initialize when queried). * * The identity operator from a coarse grid space into a fine grid space is * associated with a matrix @p P. The restriction of this matrix @p P_i to a * single child cell is returned here. * * The matrix @p P is the concatenation, not the sum of the cell matrices @p * P_i. That is, if the same non-zero entry <tt>j,k</tt> exists in in two * different child matrices @p P_i, the value should be the same in both * matrices and it is copied into the matrix @p P only once. * * Row and column indices are related to fine grid and coarse grid spaces, * respectively, consistent with the definition of the associated operator. * * These matrices are used by routines assembling the prolongation matrix * for multi-level methods. Upon assembling the transfer matrix between * cells using this matrix array, zero elements in the prolongation matrix * are discarded and will not fill up the transfer matrix. * * If prolongation matrices are not implemented in one of the base finite * element classes, this function aborts with an exception of type * FiniteElement::ExcEmbeddingVoid. You can check whether this would happen * by first calling the prolongation_is_implemented() or the * isotropic_prolongation_is_implemented() function. */ virtual const FullMatrix<double> & get_prolongation_matrix (const unsigned int child, const RefinementCase<dim> &refinement_case=RefinementCase<dim>::isotropic_refinement) const; /** * Given an index in the natural ordering of indices on a face, return the * index of the same degree of freedom on the cell. * * To explain the concept, consider the case where we would like to know * whether a degree of freedom on a face, for example as part of an FESystem * element, is primitive. Unfortunately, the is_primitive() function in the * FiniteElement class takes a cell index, so we would need to find the cell * index of the shape function that corresponds to the present face index. * This function does that. * * Code implementing this would then look like this: * @code * for (i=0; i<dofs_per_face; ++i) * if (fe.is_primitive(fe.face_to_cell_index(i, some_face_no))) * ... do whatever * @endcode * The function takes additional arguments that account for the fact that * actual faces can be in their standard ordering with respect to the cell * under consideration, or can be flipped, oriented, etc. * * @param face_dof_index The index of the degree of freedom on a face. This * index must be between zero and dofs_per_face. * @param face The number of the face this degree of freedom lives on. This * number must be between zero and GeometryInfo::faces_per_cell. * @param face_orientation One part of the description of the orientation of * the face. See * @ref GlossFaceOrientation. * @param face_flip One part of the description of the orientation of the * face. See * @ref GlossFaceOrientation. * @param face_rotation One part of the description of the orientation of * the face. See * @ref GlossFaceOrientation. * @return The index of this degree of freedom within the set of degrees of * freedom on the entire cell. The returned value will be between zero and * dofs_per_cell. */ virtual unsigned int face_to_cell_index (const unsigned int face_dof_index, const unsigned int face, const bool face_orientation = true, const bool face_flip = false, const bool face_rotation = false) const; /** * Implementation of the respective function in the base class. */ virtual Point<dim> unit_support_point (const unsigned int index) const; /** * Implementation of the respective function in the base class. */ virtual Point<dim-1> unit_face_support_point (const unsigned int index) const; /** * Return a list of constant modes of the element. The returns table has as * many rows as there are components in the element and dofs_per_cell * columns. To each component of the finite element, the row in the returned * table contains a basis representation of the constant function 1 on the * element. Concatenates the constant modes of each base element. */ virtual std::pair<Table<2,bool>, std::vector<unsigned int> > get_constant_modes () const; /** * @name Functions to support hp * @{ */ /** * Return whether this element implements its hanging node constraints in * the new way, which has to be used to make elements "hp compatible". * * This function returns @p true iff all its base elements return @p true * for this function. */ virtual bool hp_constraints_are_implemented () const; /** * Return the matrix interpolating from a face of of one element to the face * of the neighboring element. The size of the matrix is then * <tt>source.dofs_per_face</tt> times <tt>this->dofs_per_face</tt>. * * Base elements of this element will have to implement this function. They * may only provide interpolation matrices for certain source finite * elements, for example those from the same family. If they don't implement * interpolation from a given element, then they must throw an exception of * type FiniteElement<dim,spacedim>::ExcInterpolationNotImplemented, which * will get propagated out from this element. */ virtual void get_face_interpolation_matrix (const FiniteElement<dim,spacedim> &source, FullMatrix<double> &matrix) const; /** * Return the matrix interpolating from a face of of one element to the * subface of the neighboring element. The size of the matrix is then * <tt>source.dofs_per_face</tt> times <tt>this->dofs_per_face</tt>. * * Base elements of this element will have to implement this function. They * may only provide interpolation matrices for certain source finite * elements, for example those from the same family. If they don't implement * interpolation from a given element, then they must throw an exception of * type FiniteElement<dim,spacedim>::ExcInterpolationNotImplemented, which * will get propagated out from this element. */ virtual void get_subface_interpolation_matrix (const FiniteElement<dim,spacedim> &source, const unsigned int subface, FullMatrix<double> &matrix) const; /** * If, on a vertex, several finite elements are active, the hp code first * assigns the degrees of freedom of each of these FEs different global * indices. It then calls this function to find out which of them should get * identical values, and consequently can receive the same global DoF index. * This function therefore returns a list of identities between DoFs of the * present finite element object with the DoFs of @p fe_other, which is a * reference to a finite element object representing one of the other finite * elements active on this particular vertex. The function computes which of * the degrees of freedom of the two finite element objects are equivalent, * both numbered between zero and the corresponding value of dofs_per_vertex * of the two finite elements. The first index of each pair denotes one of * the vertex dofs of the present element, whereas the second is the * corresponding index of the other finite element. */ virtual std::vector<std::pair<unsigned int, unsigned int> > hp_vertex_dof_identities (const FiniteElement<dim,spacedim> &fe_other) const; /** * Same as hp_vertex_dof_indices(), except that the function treats degrees * of freedom on lines. */ virtual std::vector<std::pair<unsigned int, unsigned int> > hp_line_dof_identities (const FiniteElement<dim,spacedim> &fe_other) const; /** * Same as hp_vertex_dof_indices(), except that the function treats degrees * of freedom on quads. */ virtual std::vector<std::pair<unsigned int, unsigned int> > hp_quad_dof_identities (const FiniteElement<dim,spacedim> &fe_other) const; /** * Return whether this element dominates the one given as argument when they * meet at a common face, whether it is the other way around, whether * neither dominates, or if either could dominate. * * For a definition of domination, see FiniteElementDomination::Domination * and in particular the * @ref hp_paper "hp paper". */ virtual FiniteElementDomination::Domination compare_for_face_domination (const FiniteElement<dim,spacedim> &fe_other) const; //@} /** * Implementation of the * FiniteElement::convert_generalized_support_point_values_to_dof_values() * function. * * This function simply calls * FiniteElement::convert_generalized_support_point_values_to_dof_values * of the base elements and re-assembles everything into the output * argument. If a base element is non-interpolatory the corresponding dof * values are filled with "signaling" NaNs instead. * * The function fails if none of the base elements of the FESystem are * interpolatory. */ virtual void convert_generalized_support_point_values_to_dof_values (const std::vector<Vector<double> > &support_point_values, std::vector<double> &dof_values) const; /** * Determine an estimate for the memory consumption (in bytes) of this * object. * * This function is made virtual, since finite element objects are usually * accessed through pointers to their base class, rather than the class * itself. */ virtual std::size_t memory_consumption () const; protected: virtual typename FiniteElement<dim,spacedim>::InternalDataBase * get_data (const UpdateFlags update_flags, const Mapping<dim,spacedim> &mapping, const Quadrature<dim> &quadrature, dealii::internal::FEValues::FiniteElementRelatedData<dim, spacedim> &output_data) const; virtual typename FiniteElement<dim,spacedim>::InternalDataBase * get_face_data (const UpdateFlags update_flags, const Mapping<dim,spacedim> &mapping, const Quadrature<dim-1> &quadrature, dealii::internal::FEValues::FiniteElementRelatedData<dim, spacedim> &output_data) const; virtual typename FiniteElement<dim,spacedim>::InternalDataBase * get_subface_data (const UpdateFlags update_flags, const Mapping<dim,spacedim> &mapping, const Quadrature<dim-1> &quadrature, dealii::internal::FEValues::FiniteElementRelatedData<dim, spacedim> &output_data) const; virtual void fill_fe_values (const typename Triangulation<dim,spacedim>::cell_iterator &cell, const CellSimilarity::Similarity cell_similarity, const Quadrature<dim> &quadrature, const Mapping<dim,spacedim> &mapping, const typename Mapping<dim,spacedim>::InternalDataBase &mapping_internal, const dealii::internal::FEValues::MappingRelatedData<dim, spacedim> &mapping_data, const typename FiniteElement<dim,spacedim>::InternalDataBase &fe_internal, dealii::internal::FEValues::FiniteElementRelatedData<dim, spacedim> &output_data) const; virtual void fill_fe_face_values (const typename Triangulation<dim,spacedim>::cell_iterator &cell, const unsigned int face_no, const Quadrature<dim-1> &quadrature, const Mapping<dim,spacedim> &mapping, const typename Mapping<dim,spacedim>::InternalDataBase &mapping_internal, const dealii::internal::FEValues::MappingRelatedData<dim, spacedim> &mapping_data, const typename FiniteElement<dim,spacedim>::InternalDataBase &fe_internal, dealii::internal::FEValues::FiniteElementRelatedData<dim, spacedim> &output_data) const; virtual void fill_fe_subface_values (const typename Triangulation<dim,spacedim>::cell_iterator &cell, const unsigned int face_no, const unsigned int sub_no, const Quadrature<dim-1> &quadrature, const Mapping<dim,spacedim> &mapping, const typename Mapping<dim,spacedim>::InternalDataBase &mapping_internal, const dealii::internal::FEValues::MappingRelatedData<dim, spacedim> &mapping_data, const typename FiniteElement<dim,spacedim>::InternalDataBase &fe_internal, dealii::internal::FEValues::FiniteElementRelatedData<dim, spacedim> &output_data) const; /** * Do the work for the three <tt>fill_fe*_values</tt> functions. * * Calls (among other things) <tt>fill_fe_([sub]face)_values</tt> of the * base elements. Calls @p fill_fe_values if * <tt>face_no==invalid_face_no</tt> and <tt>sub_no==invalid_face_no</tt>; * calls @p fill_fe_face_values if <tt>face_no==invalid_face_no</tt> and * <tt>sub_no!=invalid_face_no</tt>; and calls @p fill_fe_subface_values if * <tt>face_no!=invalid_face_no</tt> and <tt>sub_no!=invalid_face_no</tt>. */ template <int dim_1> void compute_fill (const Mapping<dim,spacedim> &mapping, const typename Triangulation<dim,spacedim>::cell_iterator &cell, const unsigned int face_no, const unsigned int sub_no, const Quadrature<dim_1> &quadrature, const CellSimilarity::Similarity cell_similarity, const typename Mapping<dim,spacedim>::InternalDataBase &mapping_internal, const typename FiniteElement<dim,spacedim>::InternalDataBase &fe_data, const internal::FEValues::MappingRelatedData<dim,spacedim> &mapping_data, internal::FEValues::FiniteElementRelatedData<dim,spacedim> &output_data) const; private: /** * Value to indicate that a given face or subface number is invalid. */ static const unsigned int invalid_face_number = numbers::invalid_unsigned_int; /** * Pointers to underlying finite element objects. * * This object contains a pointer to each contributing element of a mixed * discretization and its multiplicity. It is created by the constructor and * constant afterwards. */ std::vector<std::pair<std::unique_ptr<const FiniteElement<dim,spacedim> >, unsigned int> > base_elements; /** * An index table that maps generalized support points of a base element * to the vector of generalized support points of the FE System. * It holds true that * @code * auto n = generalized_support_points_index_table[i][j]; * generalized_support_points[n] == * base_elements[i].generalized_support_points[j]; * @endcode * for each base element (indexed by i) and each g. s. point of the base * element (index by j). */ std::vector<std::vector<std::size_t>> generalized_support_points_index_table; /** * This function is simply singled out of the constructors since there are * several of them. It sets up the index table for the system as well as @p * restriction and @p prolongation matrices. */ void initialize (const std::vector<const FiniteElement<dim,spacedim>*> &fes, const std::vector<unsigned int> &multiplicities); /** * Used by @p initialize. */ void build_interface_constraints (); /** * A function that computes the hp_vertex_dof_identities(), * hp_line_dof_identities(), or hp_quad_dof_identities(), depending on the * value of the template parameter. */ template <int structdim> std::vector<std::pair<unsigned int, unsigned int> > hp_object_dof_identities (const FiniteElement<dim,spacedim> &fe_other) const; /** * Usually: Fields of cell-independent data. * * However, here, this class does not itself store the data but only * pointers to @p InternalData objects for each of the base elements. */ class InternalData : public FiniteElement<dim,spacedim>::InternalDataBase { public: /** * Constructor. Is called by the @p get_data function. Sets the size of * the @p base_fe_datas vector to @p n_base_elements. */ InternalData (const unsigned int n_base_elements); /** * Destructor. Deletes all @p InternalDatas whose pointers are stored by * the @p base_fe_datas vector. */ ~InternalData(); /** * Give write-access to the pointer to a @p InternalData of the @p * base_noth base element. */ void set_fe_data(const unsigned int base_no, typename FiniteElement<dim,spacedim>::InternalDataBase *); /** * Give read-access to the pointer to a @p InternalData of the @p * base_noth base element. */ typename FiniteElement<dim,spacedim>::InternalDataBase & get_fe_data (const unsigned int base_no) const; /** * Give read-access to the pointer to an object to which into which the * <code>base_no</code>th base element will write its output when calling * FiniteElement::fill_fe_values() and similar functions. */ internal::FEValues::FiniteElementRelatedData<dim,spacedim> & get_fe_output_object (const unsigned int base_no) const; private: /** * Pointers to @p InternalData objects for each of the base elements. They * are accessed to by the @p set_ and @p get_fe_data functions. * * The size of this vector is set to @p n_base_elements by the * InternalData constructor. It is filled by the @p get_data function. * Note that since the data for each instance of a base class is * necessarily the same, we only need as many of these objects as there * are base elements, irrespective of their multiplicity. */ typename std::vector<typename FiniteElement<dim,spacedim>::InternalDataBase *> base_fe_datas; /** * A collection of objects to which the base elements will write their * output when we call FiniteElement::fill_fe_values() and related * functions on them. * * The size of this vector is set to @p n_base_elements by the * InternalData constructor. */ mutable std::vector<internal::FEValues::FiniteElementRelatedData<dim,spacedim> > base_fe_output_objects; }; /* * Mutex for protecting initialization of restriction and embedding matrix. */ mutable Threads::Mutex mutex; friend class FE_Enriched<dim,spacedim>; }; //------------------------variadic template constructor------------------------ #ifndef DOXYGEN namespace { template <int dim, int spacedim> unsigned int count_nonzeros (const std::initializer_list<std::pair<std::unique_ptr<FiniteElement<dim, spacedim>>, unsigned int>> &fe_systems) { return std::count_if(fe_systems.begin(), fe_systems.end(), [](const std::pair<std::unique_ptr<FiniteElement<dim, spacedim>>, unsigned int> &fe_system) { return fe_system.second > 0; }); } template <int dim, int spacedim> std::pair<std::unique_ptr<FiniteElement<dim, spacedim> >, unsigned int> promote_to_fe_pair (const FiniteElement<dim,spacedim> &fe) { return std::make_pair<std::unique_ptr<FiniteElement<dim, spacedim> >, unsigned int> (std::move(fe.clone()), 1u); } template <int dim, int spacedim> auto promote_to_fe_pair (std::pair<std::unique_ptr<FiniteElement<dim, spacedim> >, unsigned int> &&p) -> decltype(std::forward<std::pair<std::unique_ptr<FiniteElement<dim, spacedim> >, unsigned int> >(p)) { return std::forward<std::pair<std::unique_ptr<FiniteElement<dim, spacedim> >, unsigned int> >(p); } } // We are just forwarding/delegating to the constructor taking a std::initializer_list. // If we decide to remove the deprecated constructors, we might just use the variadic // constructor with a suitable static_assert instead of the std::enable_if. template<int dim, int spacedim> template <class... FEPairs, typename> FESystem<dim,spacedim>::FESystem (FEPairs &&... fe_pairs) : FESystem<dim, spacedim> ({promote_to_fe_pair<dim,spacedim>(std::forward<FEPairs>(fe_pairs))...}) {} template <int dim, int spacedim> FESystem<dim,spacedim>::FESystem (const std::initializer_list<std::pair<std::unique_ptr<FiniteElement<dim, spacedim>>, unsigned int>> &fe_systems) : FiniteElement<dim,spacedim> (FETools::Compositing::multiply_dof_numbers<dim,spacedim>(fe_systems), FETools::Compositing::compute_restriction_is_additive_flags<dim,spacedim> (fe_systems), FETools::Compositing::compute_nonzero_components<dim,spacedim>(fe_systems)), base_elements(count_nonzeros(fe_systems)) { std::vector<const FiniteElement<dim,spacedim>*> fes; std::vector<unsigned int> multiplicities; const auto extract = [&fes, &multiplicities] (const std::pair<std::unique_ptr<FiniteElement<dim, spacedim>>, unsigned int> &fe_system) { fes.push_back(fe_system.first.get()); multiplicities.push_back(fe_system.second); }; for (const auto &p : fe_systems) extract (p); initialize(fes, multiplicities); } #endif //DOXYGEN DEAL_II_NAMESPACE_CLOSE #endif /*---------------------------- fe_system.h ---------------------------*/
sairajat/dealii
include/deal.II/fe/fe_system.h
C
lgpl-2.1
54,506
package osmo.tester.examples.tutorial.online; import osmo.tester.OSMOConfiguration; import osmo.tester.OSMOTester; import osmo.tester.generator.ReflectiveModelFactory; import osmo.tester.generator.endcondition.Length; /** @author Teemu Kanstren */ public class Main4 { public static void main(String[] args) { OSMOTester tester = new OSMOTester(); tester.addModelObject(new HelloModel3()); tester.setTestEndCondition(new Length(5)); tester.setSuiteEndCondition(new Length(4)); tester.getConfig().setUnwrapExceptions(true); tester.getConfig().setStopTestOnError(true); tester.generate(52); } }
mukatee/osmo
examples/src/osmo/tester/examples/tutorial/online/Main4.java
Java
lgpl-2.1
646
/* This file is part of the KDE project. Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). This library 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 or 3 of the License. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #include "ancestormovemonitor.h" #include "utils.h" #include "videooutput.h" #ifndef QT_NO_DEBUG #include "objectdump.h" #endif #include <QPaintEvent> #include <QPainter> #include <QMoveEvent> #include <QResizeEvent> #include <QtCore/private/qcore_symbian_p.h> // for qt_TRect2QRect #include <QtGui/private/qwidget_p.h> // to access QWExtra #include <coecntrl.h> #include <coemain.h> // for CCoeEnv QT_BEGIN_NAMESPACE using namespace Phonon; using namespace Phonon::MMF; /*! \class MMF::VideoOutput \internal */ //----------------------------------------------------------------------------- // Constants //----------------------------------------------------------------------------- static const Phonon::VideoWidget::AspectRatio DefaultAspectRatio = Phonon::VideoWidget::AspectRatioAuto; static const Phonon::VideoWidget::ScaleMode DefaultScaleMode = Phonon::VideoWidget::FitInView; //----------------------------------------------------------------------------- // Constructor / destructor //----------------------------------------------------------------------------- MMF::VideoOutput::VideoOutput (AncestorMoveMonitor* ancestorMoveMonitor, QWidget* parent) : QWidget(parent) , m_ancestorMoveMonitor(ancestorMoveMonitor) , m_aspectRatio(DefaultAspectRatio) , m_scaleMode(DefaultScaleMode) { TRACE_CONTEXT(VideoOutput::VideoOutput, EVideoInternal); TRACE_ENTRY("parent 0x%08x", parent); setPalette(QPalette(Qt::black)); setAttribute(Qt::WA_OpaquePaintEvent, true); setAttribute(Qt::WA_NoSystemBackground, true); setAutoFillBackground(false); qt_widget_private(this)->extraData()->nativePaintMode = QWExtra::ZeroFill; qt_widget_private(this)->extraData()->receiveNativePaintEvents = true; getVideoWindowRect(); registerForAncestorMoved(); dump(); TRACE_EXIT_0(); } MMF::VideoOutput::~VideoOutput() { TRACE_CONTEXT(VideoOutput::~VideoOutput, EVideoInternal); TRACE_ENTRY_0(); m_ancestorMoveMonitor->unRegisterTarget(this); TRACE_EXIT_0(); } void MMF::VideoOutput::setVideoSize(const QSize& frameSize) { TRACE_CONTEXT(VideoOutput::setVideoSize, EVideoInternal); TRACE("oldSize %d %d newSize %d %d", m_videoFrameSize.width(), m_videoFrameSize.height(), frameSize.width(), frameSize.height()); if (frameSize != m_videoFrameSize) { m_videoFrameSize = frameSize; updateGeometry(); } } void MMF::VideoOutput::ancestorMoved() { TRACE_CONTEXT(VideoOutput::ancestorMoved, EVideoInternal); TRACE_ENTRY_0(); RWindowBase *const window = videoWindow(); if(window) { const TPoint newWindowPosSymbian = window->AbsPosition(); const QPoint newWindowPos(newWindowPosSymbian.iX, newWindowPosSymbian.iY); if(newWindowPos != m_videoWindowRect.topLeft()) { m_videoWindowRect.moveTo(newWindowPos); emit videoWindowChanged(); } } TRACE_EXIT_0(); } //----------------------------------------------------------------------------- // QWidget //----------------------------------------------------------------------------- QSize MMF::VideoOutput::sizeHint() const { // TODO: replace this with a more sensible default QSize result(320, 240); if (!m_videoFrameSize.isNull()) result = m_videoFrameSize; return result; } void MMF::VideoOutput::paintEvent(QPaintEvent* event) { TRACE_CONTEXT(VideoOutput::paintEvent, EVideoInternal); TRACE("rect %d %d - %d %d", event->rect().left(), event->rect().top(), event->rect().right(), event->rect().bottom()); TRACE("regions %d", event->region().rectCount()); TRACE("type %d", event->type()); // Do nothing } void MMF::VideoOutput::resizeEvent(QResizeEvent* event) { TRACE_CONTEXT(VideoOutput::resizeEvent, EVideoInternal); TRACE("%d %d -> %d %d", event->oldSize().width(), event->oldSize().height(), event->size().width(), event->size().height()); if(event->size() != event->oldSize()) { m_videoWindowRect.setSize(event->size()); emit videoWindowChanged(); } } void MMF::VideoOutput::moveEvent(QMoveEvent* event) { TRACE_CONTEXT(VideoOutput::moveEvent, EVideoInternal); TRACE("%d %d -> %d %d", event->oldPos().x(), event->oldPos().y(), event->pos().x(), event->pos().y()); if(event->pos() != event->oldPos()) { m_videoWindowRect.moveTo(event->pos()); emit videoWindowChanged(); } } bool MMF::VideoOutput::event(QEvent* event) { TRACE_CONTEXT(VideoOutput::event, EVideoInternal); if (event->type() == QEvent::WinIdChange) { TRACE_0("WinIdChange"); getVideoWindowRect(); emit videoWindowChanged(); return true; } else if (event->type() == QEvent::ParentChange) { // Tell ancestor move monitor to update ancestor list for this widget registerForAncestorMoved(); return true; } else return QWidget::event(event); } //----------------------------------------------------------------------------- // Public functions //----------------------------------------------------------------------------- RWindowBase* MMF::VideoOutput::videoWindow() { CCoeControl *control = internalWinId(); if(!control) control = effectiveWinId(); RWindowBase *window = 0; if(control) window = control->DrawableWindow(); return window; } const QRect& MMF::VideoOutput::videoWindowRect() const { return m_videoWindowRect; } Phonon::VideoWidget::AspectRatio MMF::VideoOutput::aspectRatio() const { return m_aspectRatio; } void MMF::VideoOutput::setAspectRatio (Phonon::VideoWidget::AspectRatio aspectRatio) { if(m_aspectRatio != aspectRatio) { m_aspectRatio = aspectRatio; emit aspectRatioChanged(); } } Phonon::VideoWidget::ScaleMode MMF::VideoOutput::scaleMode() const { return m_scaleMode; } void MMF::VideoOutput::setScaleMode (Phonon::VideoWidget::ScaleMode scaleMode) { if(m_scaleMode != scaleMode) { m_scaleMode = scaleMode; emit scaleModeChanged(); } } //----------------------------------------------------------------------------- // Private functions //----------------------------------------------------------------------------- void MMF::VideoOutput::getVideoWindowRect() { RWindowBase *const window = videoWindow(); if(window) m_videoWindowRect = qt_TRect2QRect(TRect(window->AbsPosition(), window->Size())); } void MMF::VideoOutput::registerForAncestorMoved() { m_ancestorMoveMonitor->registerTarget(this); } void MMF::VideoOutput::dump() const { #ifndef QT_NO_DEBUG TRACE_CONTEXT(VideoOutput::dump, EVideoInternal); QScopedPointer<ObjectDump::QVisitor> visitor(new ObjectDump::QVisitor); visitor->setPrefix("Phonon::MMF"); // to aid searchability of logs ObjectDump::addDefaultAnnotators(*visitor); TRACE("Dumping tree from leaf 0x%08x:", this); ObjectDump::dumpTreeFromLeaf(*this, *visitor); QScopedPointer<ObjectDump::QDumper> dumper(new ObjectDump::QDumper); dumper->setPrefix("Phonon::MMF"); // to aid searchability of logs ObjectDump::addDefaultAnnotators(*dumper); TRACE_0("Dumping VideoOutput:"); dumper->dumpObject(*this); #endif } void MMF::VideoOutput::beginNativePaintEvent(const QRect& /*controlRect*/) { emit beginVideoWindowNativePaint(); } void MMF::VideoOutput::endNativePaintEvent(const QRect& /*controlRect*/) { // Ensure that draw ops are executed into the WSERV output framebuffer CCoeEnv::Static()->WsSession().Flush(); emit endVideoWindowNativePaint(); } QT_END_NAMESPACE
kobolabs/qt-everywhere-opensource-src-4.6.2
src/3rdparty/phonon/mmf/videooutput.cpp
C++
lgpl-2.1
8,469
<?php //this script may only be included - so its better to die if called directly. if (strpos($_SERVER["SCRIPT_NAME"],basename(__FILE__)) !== false) { header("location: index.php"); exit; } /*This file is part of J4PHP - Ensembles de propriétés et méthodes permettant le developpment rapide d'application web modulaire Copyright (c) 2002-2004 @PICNet 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. 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. */ APIC::import("org.apicnet.io.File"); APIC::import("org.apicnet.io.CDir"); /** * OOoUtil * * @package * @author apicnet * @copyright Copyright (c) 2004 * @version $Id: OOoUtil.php,v 1.3 2005-05-18 11:01:39 mose Exp $ * @access public **/ class OOoUtil extends absOOo{ var $directories = array("Images", "META-INF"); var $pictures = array("gif", "png"); var $tmpdir; var $docExist; function __construct(){} function isTextDocument () {} function isCalcDocument () {} function isContent () {} function isMeta () {} function isSettings () {} function Ouput(){ } function Zip($name){ $file = new File($this->tmpdir."/".$name, FALSE); if ($file->exists()) { $file->delFile(); $file->createFile(); } $zip = APIC::LoadClass("org.apicnet.io.archive.CZip"); if ($this->docExist) { $cdir = new CDir(); $cdir->Read( $this->tmpdir."/", "", true, 5 , true, true); $allFiles = array(); reset( $cdir->aFiles ); while( list( $sKey, $aFile ) = each( $cdir->aFiles ) ){ $sFileName = $cdir->FileName($aFile); $sFilePath = $cdir->GetPath($aFile); $allFiles[] = $this->tmpdir."/".$sFilePath.$sFileName; } $zip->zip($allFiles, $name); } else { $this -> ErrorTracker(4, "Vous devez d'abord créer un document OpenOffice", 'Zip', __FILE__, __LINE__); } } function unZip($dir, $file){ $zip = APIC::LoadClass("org.apicnet.io.archive.CZip"); $zip->extract($dir, $file); } function createDirectories(){ $this->tmpdir = CACHE_PATH."/OOotmp".rand(); mkdir ($this->tmpdir); for($i = 0; $i < count($this->directories); $i++){ mkdir ($this->tmpdir."/".$this->directories[$i]); } } function delDir($dir){ $current_dir = opendir($dir); while($entryname = readdir($current_dir)){ if(is_dir("$dir/$entryname") and ($entryname != "." and $entryname!="..")){ $this->delDir("${dir}/${entryname}"); }elseif($entryname != "." and $entryname!=".."){ unlink("${dir}/${entryname}"); } } closedir($current_dir); rmdir(${dir}); } function convert($img, $format){ } function listFiles(){ $cdir = new CDir(); $cdir->Read( $this->tmpdir."/", "", true, 5 , true, true); $allFiles = array(); reset( $cdir->aFiles ); while( list( $sKey, $aFile ) = each( $cdir->aFiles ) ){ $sFileName = $cdir->FileName($aFile); $sFilePath = $cdir->GetPath($aFile); $allFiles[] = $this->tmpdir."/".$sFilePath.$sFileName; } return $allFiles; } function isImpressDocument () {} function isDrawDocument () {} function main(){ $this->Directories(); } }
tikiorg/tiki
lib/sheet/include/org/apicnet/io/OOo/OOoUtil.php
PHP
lgpl-2.1
3,563
// // Copyright (C) 2007-2008 Sebastian Kuzminsky // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // #include <asm/io.h> #include "rtapi.h" #include "rtapi_app.h" #include "rtapi_math.h" #include "rtapi_string.h" #include "hal.h" #include "hal/drivers/mesa-hostmot2/hostmot2-lowlevel.h" #include "hal/drivers/mesa-hostmot2/hm2_7i43.h" static int comp_id; #ifdef MODULE_INFO MODULE_INFO(emc2, "component:hm2_7i43:EMC HAL driver for the Mesa Electronics 7i43 EPP Anything IO board with HostMot2 firmware."); MODULE_INFO(emc2, "license:GPL"); #endif // MODULE_INFO MODULE_LICENSE("GPL"); static int ioaddr[HM2_7I43_MAX_BOARDS] = { 0x378, 0x3f8, [2 ... (HM2_7I43_MAX_BOARDS-1)] = 0 }; static int num_ioaddrs = HM2_7I43_MAX_BOARDS; module_param_array(ioaddr, int, &num_ioaddrs, S_IRUGO); MODULE_PARM_DESC(ioaddr, "base address of the parallel port(s) (see hm2_7i43(9) manpage)"); static int ioaddr_hi[HM2_7I43_MAX_BOARDS] = { [0 ... (HM2_7I43_MAX_BOARDS-1)] = 0 }; static int num_ioaddr_his = HM2_7I43_MAX_BOARDS; module_param_array(ioaddr_hi, int, &num_ioaddr_his, S_IRUGO); MODULE_PARM_DESC(ioaddr_hi, "secondary address of the parallel port(s) (see hm2_7i43(9) manpage)"); static int epp_wide[HM2_7I43_MAX_BOARDS] = { [0 ... (HM2_7I43_MAX_BOARDS-1)] = 1 }; static int num_epp_wides = HM2_7I43_MAX_BOARDS; module_param_array(epp_wide, int, &num_epp_wides, S_IRUGO); MODULE_PARM_DESC(epp_wide, "set to 0 to disable wide EPP mode (see (hm2_7i43(9) manpage)"); int debug_epp = 0; RTAPI_MP_INT(debug_epp, "Developer/debug use only! Enable debug logging of most EPP\ntransfers."); static char *config[HM2_7I43_MAX_BOARDS]; static int num_config_strings = HM2_7I43_MAX_BOARDS; module_param_array(config, charp, &num_config_strings, S_IRUGO); MODULE_PARM_DESC(config, "config string(s) for the 7i43 board(s) (see hostmot2(9) manpage)"); // // this data structure keeps track of all the 7i43 boards found // static hm2_7i43_t board[HM2_7I43_MAX_BOARDS]; static int num_boards; // // EPP I/O code // static inline void hm2_7i43_epp_addr8(u8 addr, hm2_7i43_t *board) { outb(addr, board->port.base + HM2_7I43_EPP_ADDRESS_OFFSET); LL_PRINT_IF(debug_epp, "selected address 0x%02X\n", addr); } static inline void hm2_7i43_epp_addr16(u16 addr, hm2_7i43_t *board) { outb((addr & 0x00FF), board->port.base + HM2_7I43_EPP_ADDRESS_OFFSET); outb((addr >> 8), board->port.base + HM2_7I43_EPP_ADDRESS_OFFSET); LL_PRINT_IF(debug_epp, "selected address 0x%04X\n", addr); } static inline void hm2_7i43_epp_write(int w, hm2_7i43_t *board) { outb(w, board->port.base + HM2_7I43_EPP_DATA_OFFSET); LL_PRINT_IF(debug_epp, "wrote data 0x%02X\n", w); } static inline int hm2_7i43_epp_read(hm2_7i43_t *board) { int val; val = inb(board->port.base + HM2_7I43_EPP_DATA_OFFSET); LL_PRINT_IF(debug_epp, "read data 0x%02X\n", val); return val; } static inline u32 hm2_7i43_epp_read32(hm2_7i43_t *board) { uint32_t data; if (board->epp_wide) { data = inl(board->port.base + HM2_7I43_EPP_DATA_OFFSET); LL_PRINT_IF(debug_epp, "read data 0x%08X\n", data); } else { uint8_t a, b, c, d; a = hm2_7i43_epp_read(board); b = hm2_7i43_epp_read(board); c = hm2_7i43_epp_read(board); d = hm2_7i43_epp_read(board); data = a + (b<<8) + (c<<16) + (d<<24); } return data; } static inline void hm2_7i43_epp_write32(uint32_t w, hm2_7i43_t *board) { if (board->epp_wide) { outl(w, board->port.base + HM2_7I43_EPP_DATA_OFFSET); LL_PRINT_IF(debug_epp, "wrote data 0x%08X\n", w); } else { hm2_7i43_epp_write((w) & 0xFF, board); hm2_7i43_epp_write((w >> 8) & 0xFF, board); hm2_7i43_epp_write((w >> 16) & 0xFF, board); hm2_7i43_epp_write((w >> 24) & 0xFF, board); } } static inline uint8_t hm2_7i43_epp_read_status(hm2_7i43_t *board) { uint8_t val; val = inb(board->port.base + HM2_7I43_EPP_STATUS_OFFSET); LL_PRINT_IF(debug_epp, "read status 0x%02X\n", val); return val; } static inline void hm2_7i43_epp_write_status(uint8_t status_byte, hm2_7i43_t *board) { outb(status_byte, board->port.base + HM2_7I43_EPP_STATUS_OFFSET); LL_PRINT_IF(debug_epp, "wrote status 0x%02X\n", status_byte); } static inline void hm2_7i43_epp_write_control(uint8_t control_byte, hm2_7i43_t *board) { outb(control_byte, board->port.base + HM2_7I43_EPP_CONTROL_OFFSET); LL_PRINT_IF(debug_epp, "wrote control 0x%02X\n", control_byte); } // returns TRUE if there's a timeout static inline int hm2_7i43_epp_check_for_timeout(hm2_7i43_t *board) { return (hm2_7i43_epp_read_status(board) & 0x01); } static int hm2_7i43_epp_clear_timeout(hm2_7i43_t *board) { uint8_t status; if (!hm2_7i43_epp_check_for_timeout(board)) { return 1; } /* To clear timeout some chips require double read */ (void)hm2_7i43_epp_read_status(board); // read in the actual status register status = hm2_7i43_epp_read_status(board); hm2_7i43_epp_write_status(status | 0x01, board); // Some reset by writing 1 hm2_7i43_epp_write_status(status & 0xFE, board); // Others by writing 0 if (hm2_7i43_epp_check_for_timeout(board)) { LL_PRINT("failed to clear EPP Timeout!\n"); return 0; // fail } return 1; // success } // // misc generic helper functions // // FIXME: this is bogus static void hm2_7i43_nanosleep(unsigned long int nanoseconds) { long int max_ns_delay; max_ns_delay = rtapi_delay_max(); while (nanoseconds > max_ns_delay) { rtapi_delay(max_ns_delay); nanoseconds -= max_ns_delay; } rtapi_delay(nanoseconds); } // // these are the low-level i/o functions exported to the hostmot2 driver // int hm2_7i43_read(hm2_lowlevel_io_t *this, u32 addr, void *buffer, int size) { int bytes_remaining = size; hm2_7i43_t *board = this->private; hm2_7i43_epp_addr16(addr | HM2_7I43_ADDR_AUTOINCREMENT, board); for (; bytes_remaining > 3; bytes_remaining -= 4) { *((u32*)buffer) = hm2_7i43_epp_read32(board); buffer += 4; } for ( ; bytes_remaining > 0; bytes_remaining --) { *((u8*)buffer) = hm2_7i43_epp_read(board); buffer ++; } if (hm2_7i43_epp_check_for_timeout(board)) { THIS_PRINT("EPP timeout on data cycle of read(addr=0x%04x, size=%d)\n", addr, size); (*this->io_error) = 1; this->needs_reset = 1; hm2_7i43_epp_clear_timeout(board); return 0; // fail } return 1; // success } int hm2_7i43_write(hm2_lowlevel_io_t *this, u32 addr, void *buffer, int size) { int bytes_remaining = size; hm2_7i43_t *board = this->private; hm2_7i43_epp_addr16(addr | HM2_7I43_ADDR_AUTOINCREMENT, board); for (; bytes_remaining > 3; bytes_remaining -= 4) { hm2_7i43_epp_write32(*((u32*)buffer), board); buffer += 4; } for ( ; bytes_remaining > 0; bytes_remaining --) { hm2_7i43_epp_write(*((u8*)buffer), board); buffer ++; } if (hm2_7i43_epp_check_for_timeout(board)) { THIS_PRINT("EPP timeout on data cycle of write(addr=0x%04x, size=%d)\n", addr, size); (*this->io_error) = 1; this->needs_reset = 1; hm2_7i43_epp_clear_timeout(board); return 0; } return 1; } int hm2_7i43_program_fpga(hm2_lowlevel_io_t *this, const bitfile_t *bitfile) { int orig_debug_epp = debug_epp; // we turn off EPP debugging for this part... hm2_7i43_t *board = this->private; int64_t start_time, end_time; int i; void *firmware = bitfile->e.data; // // send the firmware // debug_epp = 0; start_time = rtapi_get_time(); // select the CPLD's data address hm2_7i43_epp_addr8(0, board); for (i = 0; i < (bitfile->e.size & ~0x3); i += 4, firmware += 4) { hm2_7i43_epp_write32(*(u32 *)firmware, board); } for (; i < bitfile->e.size; i ++, firmware ++) { hm2_7i43_epp_write(*(u8 *)firmware, board); } end_time = rtapi_get_time(); debug_epp = orig_debug_epp; // see if it worked if (hm2_7i43_epp_check_for_timeout(board)) { THIS_PRINT("EPP Timeout while sending firmware!\n"); return -EIO; } // // brag about how fast it was // { uint32_t duration_ns; duration_ns = (uint32_t)(end_time - start_time); if (duration_ns != 0) { THIS_INFO( "%d bytes of firmware sent (%u KB/s)\n", bitfile->e.size, (uint32_t)(((double)bitfile->e.size / ((double)duration_ns / (double)(1000 * 1000 * 1000))) / 1024) ); } } return 0; } // return 0 if the board has been reset, -errno if not int hm2_7i43_reset(hm2_lowlevel_io_t *this) { hm2_7i43_t *board = this->private; uint8_t byte; // // this resets the FPGA *only* if it's currently configured with the // HostMot2 or GPIO firmware // hm2_7i43_epp_addr16(0x7F7F, board); hm2_7i43_epp_write(0x5A, board); // // this code resets the FPGA *only* if the CPLD is in charge of the // parallel port // // select the control register hm2_7i43_epp_addr8(1, board); // bring the Spartan3's PROG_B line low for 1 us (the specs require 300-500 ns or longer) hm2_7i43_epp_write(0x00, board); hm2_7i43_nanosleep(1000); // bring the Spartan3's PROG_B line high and wait for 2 ms before sending firmware (required by spec) hm2_7i43_epp_write(0x01, board); hm2_7i43_nanosleep(2 * 1000 * 1000); // make sure the FPGA is not asserting its /DONE bit byte = hm2_7i43_epp_read(board); if ((byte & 0x01) != 0) { LL_PRINT("/DONE is not low after CPLD reset!\n"); return -EIO; } return 0; } // // setup and cleanup code // static void hm2_7i43_cleanup(void) { int i; // NOTE: hal_malloc() doesnt have a matching free for (i = 0; i < num_boards; i ++) { hm2_lowlevel_io_t *this = &board[i].llio; THIS_PRINT("releasing board\n"); hm2_unregister(this); hal_parport_release(&board[i].port); } } static int hm2_7i43_setup(void) { int i; LL_PRINT("loading HostMot2 Mesa 7i43 driver version %s\n", HM2_7I43_VERSION); // zero the board structs memset(board, 0, HM2_7I43_MAX_BOARDS * sizeof(hm2_7i43_t)); num_boards = 0; for (i = 0; i < num_config_strings; i ++) { hm2_lowlevel_io_t *this; int r; board[i].epp_wide = epp_wide[i]; // // claim the I/O regions for the parport // r = hal_parport_get(comp_id, &board[i].port, ioaddr[i], ioaddr_hi[i], PARPORT_MODE_EPP); if(r < 0) return r; // set up the parport for EPP if(board[i].port.base_hi) { outb(0x94, board[i].port.base_hi + HM2_7I43_ECP_CONTROL_HIGH_OFFSET); // select EPP mode in ECR } // // when we get here, the parallel port is in epp mode and ready to go // // select the device and tell it to make itself ready for io hm2_7i43_epp_write_control(0x04, &board[i]); // set control lines and input mode hm2_7i43_epp_clear_timeout(&board[i]); snprintf(board[i].llio.name, HAL_NAME_LEN, "%s.%d", HM2_LLIO_NAME, i); board[i].llio.comp_id = comp_id; board[i].llio.read = hm2_7i43_read; board[i].llio.write = hm2_7i43_write; board[i].llio.program_fpga = hm2_7i43_program_fpga; board[i].llio.reset = hm2_7i43_reset; board[i].llio.num_ioport_connectors = 2; board[i].llio.ioport_connector_name[0] = "P4"; board[i].llio.ioport_connector_name[1] = "P3"; board[i].llio.private = &board[i]; this = &board[i].llio; // // now we want to detect if this 7i43 has the big FPGA or the small one // 3s200tq144 for the small board // 3s400tq144 for the big // // make sure the CPLD is in charge of the parallel port hm2_7i43_reset(&board[i].llio); // select CPLD data register hm2_7i43_epp_addr8(0, &board[i]); if (hm2_7i43_epp_read(&board[i]) & 0x01) { board[i].llio.fpga_part_number = "3s400tq144"; } else { board[i].llio.fpga_part_number = "3s200tq144"; } THIS_DBG("detected FPGA '%s'\n", board[i].llio.fpga_part_number); r = hm2_register(&board[i].llio, config[i]); if (r != 0) { THIS_ERR( "board at (ioaddr=0x%04X, ioaddr_hi=0x%04X, epp_wide %s) not found!\n", board[i].port.base, board[i].port.base_hi, (board[i].epp_wide ? "ON" : "OFF") ); hal_parport_release(&board[i].port); return r; } THIS_PRINT( "board at (ioaddr=0x%04X, ioaddr_hi=0x%04X, epp_wide %s) found\n", board[i].port.base, board[i].port.base_hi, (board[i].epp_wide ? "ON" : "OFF") ); num_boards ++; } return 0; } int rtapi_app_main(void) { int r = 0; comp_id = hal_init(HM2_LLIO_NAME); if (comp_id < 0) return comp_id; r = hm2_7i43_setup(); if (r) { hm2_7i43_cleanup(); hal_exit(comp_id); } else { hal_ready(comp_id); } return r; } void rtapi_app_exit(void) { hm2_7i43_cleanup(); hal_exit(comp_id); LL_PRINT("driver unloaded\n"); }
yishinli/emc2
src/hal/drivers/mesa-hostmot2/hm2_7i43.c
C
lgpl-2.1
14,274
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.envers.test.integration.manytomany; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.SortedMap; import java.util.SortedSet; import javax.persistence.EntityManager; import org.hibernate.envers.test.BaseEnversJPAFunctionalTestCase; import org.hibernate.envers.test.Priority; import org.hibernate.envers.test.entities.StrTestEntity; import org.hibernate.envers.test.entities.StrTestEntityComparator; import org.hibernate.envers.test.entities.manytomany.SortedSetEntity; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author Michal Skowronek (mskowr at o2 pl) */ public class CustomComparatorEntityTest extends BaseEnversJPAFunctionalTestCase { private Integer id1; private Integer id2; private Integer id3; private Integer id4; @Override protected Class<?>[] getAnnotatedClasses() { return new Class[] {StrTestEntity.class, SortedSetEntity.class}; } @Test @Priority(10) public void initData() { EntityManager em = getEntityManager(); SortedSetEntity entity1 = new SortedSetEntity( 1, "sortedEntity1" ); // Revision 1 em.getTransaction().begin(); em.persist( entity1 ); em.getTransaction().commit(); // Revision 2 em.getTransaction().begin(); entity1 = em.find( SortedSetEntity.class, 1 ); final StrTestEntity strTestEntity1 = new StrTestEntity( "abc" ); em.persist( strTestEntity1 ); id1 = strTestEntity1.getId(); entity1.getSortedSet().add( strTestEntity1 ); entity1.getSortedMap().put( strTestEntity1, "abc" ); em.getTransaction().commit(); // Revision 3 em.getTransaction().begin(); entity1 = em.find( SortedSetEntity.class, 1 ); final StrTestEntity strTestEntity2 = new StrTestEntity( "aaa" ); em.persist( strTestEntity2 ); id2 = strTestEntity2.getId(); entity1.getSortedSet().add( strTestEntity2 ); entity1.getSortedMap().put( strTestEntity2, "aaa" ); em.getTransaction().commit(); // Revision 4 em.getTransaction().begin(); entity1 = em.find( SortedSetEntity.class, 1 ); final StrTestEntity strTestEntity3 = new StrTestEntity( "aba" ); em.persist( strTestEntity3 ); id3 = strTestEntity3.getId(); entity1.getSortedSet().add( strTestEntity3 ); entity1.getSortedMap().put( strTestEntity3, "aba" ); em.getTransaction().commit(); // Revision 5 em.getTransaction().begin(); entity1 = em.find( SortedSetEntity.class, 1 ); final StrTestEntity strTestEntity4 = new StrTestEntity( "aac" ); em.persist( strTestEntity4 ); id4 = strTestEntity4.getId(); entity1.getSortedSet().add( strTestEntity4 ); entity1.getSortedMap().put( strTestEntity4, "aac" ); em.getTransaction().commit(); } @Test public void testRevisionsCounts() { assertEquals( Arrays.asList( 1, 2, 3, 4, 5 ), getAuditReader().getRevisions( SortedSetEntity.class, 1 ) ); assertEquals( Arrays.asList( 2 ), getAuditReader().getRevisions( StrTestEntity.class, id1 ) ); assertEquals( Arrays.asList( 3 ), getAuditReader().getRevisions( StrTestEntity.class, id2 ) ); assertEquals( Arrays.asList( 4 ), getAuditReader().getRevisions( StrTestEntity.class, id3 ) ); assertEquals( Arrays.asList( 5 ), getAuditReader().getRevisions( StrTestEntity.class, id4 ) ); } @Test public void testCurrentStateOfEntity1() { final SortedSetEntity entity1 = getEntityManager().find( SortedSetEntity.class, 1 ); assertEquals( "sortedEntity1", entity1.getData() ); assertEquals( Integer.valueOf( 1 ), entity1.getId() ); final SortedSet<StrTestEntity> sortedSet = entity1.getSortedSet(); assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); assertEquals( 4, sortedSet.size() ); final Iterator<StrTestEntity> iterator = sortedSet.iterator(); checkStrTestEntity( iterator.next(), id2, "aaa" ); checkStrTestEntity( iterator.next(), id4, "aac" ); checkStrTestEntity( iterator.next(), id3, "aba" ); checkStrTestEntity( iterator.next(), id1, "abc" ); final SortedMap<StrTestEntity, String> sortedMap = entity1.getSortedMap(); assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); assertEquals( 4, sortedMap.size() ); Iterator<Map.Entry<StrTestEntity, String>> mapIterator = sortedMap.entrySet().iterator(); checkStrTestEntity( mapIterator.next().getKey(), id2, "aaa" ); checkStrTestEntity( mapIterator.next().getKey(), id4, "aac" ); checkStrTestEntity( mapIterator.next().getKey(), id3, "aba" ); checkStrTestEntity( mapIterator.next().getKey(), id1, "abc" ); mapIterator = sortedMap.entrySet().iterator(); assertEquals( mapIterator.next().getValue(), "aaa" ); assertEquals( mapIterator.next().getValue(), "aac" ); assertEquals( mapIterator.next().getValue(), "aba" ); assertEquals( mapIterator.next().getValue(), "abc" ); } private void checkStrTestEntity(StrTestEntity entity, Integer id, String sortKey) { assertEquals( id, entity.getId() ); assertEquals( sortKey, entity.getStr() ); } @Test public void testHistoryOfEntity1() throws Exception { SortedSetEntity entity1 = getAuditReader().find( SortedSetEntity.class, 1, 1 ); assertEquals( "sortedEntity1", entity1.getData() ); assertEquals( Integer.valueOf( 1 ), entity1.getId() ); SortedSet<StrTestEntity> sortedSet = entity1.getSortedSet(); assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); assertEquals( 0, sortedSet.size() ); SortedMap<StrTestEntity, String> sortedMap = entity1.getSortedMap(); assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); assertEquals( 0, sortedMap.size() ); entity1 = getAuditReader().find( SortedSetEntity.class, 1, 2 ); assertEquals( "sortedEntity1", entity1.getData() ); assertEquals( Integer.valueOf( 1 ), entity1.getId() ); sortedSet = entity1.getSortedSet(); assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); assertEquals( 1, sortedSet.size() ); Iterator<StrTestEntity> iterator = sortedSet.iterator(); checkStrTestEntity( iterator.next(), id1, "abc" ); sortedMap = entity1.getSortedMap(); assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); assertEquals( 1, sortedMap.size() ); Iterator<Map.Entry<StrTestEntity, String>> mapIterator = sortedMap.entrySet().iterator(); checkStrTestEntity( mapIterator.next().getKey(), id1, "abc" ); mapIterator = sortedMap.entrySet().iterator(); assertEquals( mapIterator.next().getValue(), "abc" ); entity1 = getAuditReader().find( SortedSetEntity.class, 1, 3 ); assertEquals( "sortedEntity1", entity1.getData() ); assertEquals( Integer.valueOf( 1 ), entity1.getId() ); sortedSet = entity1.getSortedSet(); assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); assertEquals( 2, sortedSet.size() ); iterator = sortedSet.iterator(); checkStrTestEntity( iterator.next(), id2, "aaa" ); checkStrTestEntity( iterator.next(), id1, "abc" ); sortedMap = entity1.getSortedMap(); assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); assertEquals( 2, sortedMap.size() ); mapIterator = sortedMap.entrySet().iterator(); checkStrTestEntity( mapIterator.next().getKey(), id2, "aaa" ); checkStrTestEntity( mapIterator.next().getKey(), id1, "abc" ); mapIterator = sortedMap.entrySet().iterator(); assertEquals( mapIterator.next().getValue(), "aaa" ); assertEquals( mapIterator.next().getValue(), "abc" ); entity1 = getAuditReader().find( SortedSetEntity.class, 1, 4 ); assertEquals( "sortedEntity1", entity1.getData() ); assertEquals( Integer.valueOf( 1 ), entity1.getId() ); sortedSet = entity1.getSortedSet(); assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); assertEquals( 3, sortedSet.size() ); iterator = sortedSet.iterator(); checkStrTestEntity( iterator.next(), id2, "aaa" ); checkStrTestEntity( iterator.next(), id3, "aba" ); checkStrTestEntity( iterator.next(), id1, "abc" ); sortedMap = entity1.getSortedMap(); assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); assertEquals( 3, sortedMap.size() ); mapIterator = sortedMap.entrySet().iterator(); checkStrTestEntity( mapIterator.next().getKey(), id2, "aaa" ); checkStrTestEntity( mapIterator.next().getKey(), id3, "aba" ); checkStrTestEntity( mapIterator.next().getKey(), id1, "abc" ); mapIterator = sortedMap.entrySet().iterator(); assertEquals( mapIterator.next().getValue(), "aaa" ); assertEquals( mapIterator.next().getValue(), "aba" ); assertEquals( mapIterator.next().getValue(), "abc" ); entity1 = getAuditReader().find( SortedSetEntity.class, 1, 5 ); assertEquals( "sortedEntity1", entity1.getData() ); assertEquals( Integer.valueOf( 1 ), entity1.getId() ); sortedSet = entity1.getSortedSet(); assertEquals( StrTestEntityComparator.class, sortedSet.comparator().getClass() ); assertEquals( 4, sortedSet.size() ); iterator = sortedSet.iterator(); checkStrTestEntity( iterator.next(), id2, "aaa" ); checkStrTestEntity( iterator.next(), id4, "aac" ); checkStrTestEntity( iterator.next(), id3, "aba" ); checkStrTestEntity( iterator.next(), id1, "abc" ); sortedMap = entity1.getSortedMap(); assertEquals( StrTestEntityComparator.class, sortedMap.comparator().getClass() ); assertEquals( 4, sortedMap.size() ); mapIterator = sortedMap.entrySet().iterator(); checkStrTestEntity( mapIterator.next().getKey(), id2, "aaa" ); checkStrTestEntity( mapIterator.next().getKey(), id4, "aac" ); checkStrTestEntity( mapIterator.next().getKey(), id3, "aba" ); checkStrTestEntity( mapIterator.next().getKey(), id1, "abc" ); mapIterator = sortedMap.entrySet().iterator(); assertEquals( mapIterator.next().getValue(), "aaa" ); assertEquals( mapIterator.next().getValue(), "aac" ); assertEquals( mapIterator.next().getValue(), "aba" ); assertEquals( mapIterator.next().getValue(), "abc" ); } }
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-envers/src/test/java/org/hibernate/envers/test/integration/manytomany/CustomComparatorEntityTest.java
Java
lgpl-2.1
10,193
/****************************************************************** * * Test file for the XSLT Bindings Generator (XBiG) * * It handles a struct with an inner class * ******************************************************************/ #ifdef WIN32 #define EXPORT __declspec(dllexport) #else #define EXPORT #endif struct EXPORT A { A(); class EXPORT B { public: float x (int y); double z; }; int a(float b); };
rhajamor/xbig
tests/t3_8/include/t3_8.h
C
lgpl-2.1
431
/****************************************************************************** * $Id: GDALTestIO.java 18017 2009-11-14 13:47:26Z rouault $ * * Name: GDALTestIO.java * Project: GDAL Java Interface * Purpose: A sample app to test ReadRaster_Direct / WriteRaster_Direct * Author: Even Rouault, <even dot rouault at mines dash paris dot org> * * Adapted from a sample by Ivan Lucena * ****************************************************************************** * Copyright (c) 2009, Even Rouault * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. *****************************************************************************/ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import org.gdal.gdal.gdal; import org.gdal.gdal.Band; import org.gdal.gdal.Dataset; import org.gdal.gdal.Driver; import org.gdal.gdalconst.gdalconst; public class GDALTestIO implements Runnable { String filename; int nbIters; static final int METHOD_DBB = 1; static final int METHOD_JAVA_ARRAYS = 2; static int method; public GDALTestIO(String filename, int nbIters) { this.filename = filename; this.nbIters = nbIters; } public void run() { Dataset dataset = null; Driver driver = null; Band band = null; int xsize = 4000; int ysize = 400; driver = gdal.GetDriverByName("GTiff"); ByteBuffer byteBuffer = ByteBuffer.allocateDirect(4 * xsize); byteBuffer.order(ByteOrder.nativeOrder()); FloatBuffer floatBuffer = byteBuffer.asFloatBuffer(); int[] intArray = new int[xsize]; float[] floatArray = new float[xsize]; dataset = driver.Create(filename, xsize, ysize, 1, gdalconst.GDT_Float32); band = dataset.GetRasterBand(1); for(int iter = 0; iter < nbIters; iter++) { if (method == METHOD_DBB) { for( int i = 0; i < ysize; i++) { for( int j = 0; j < xsize; j++) { floatBuffer.put(j, (float) (i + j)); } band.WriteRaster_Direct(0, i, xsize, 1, gdalconst.GDT_Float32, byteBuffer); } } else { for( int i = 0; i < ysize; i++) { for( int j = 0; j < xsize; j++) { floatArray[j] = (float) (i + j); } band.WriteRaster(0, i, xsize, 1, floatArray); } } } dataset.delete(); /* Open the file to check the values */ dataset = gdal.Open(filename); band = dataset.GetRasterBand(1); for(int iter = 0; iter < nbIters; iter++) { if (method == METHOD_DBB) { for( int i = 0; i < ysize; i++) { band.ReadRaster_Direct(0, i, xsize, 1, xsize, 1, gdalconst.GDT_Int32, byteBuffer); for( int j = 0; j < xsize; j++) { int val = byteBuffer.getInt(j*4); if (val != (i + j)) throw new RuntimeException("Bad value for (" + j + "," + i + ") : " + val); } } } else { for( int i = 0; i < ysize; i++) { band.ReadRaster(0, i, xsize, 1, intArray); for( int j = 0; j < xsize; j++) { int val = intArray[j]; if (val != (i + j)) throw new RuntimeException("Bad value for (" + j + "," + i + ") : " + val); } } } } dataset.delete(); /* Free the memory occupied by the /vsimem file */ gdal.Unlink(filename); } public static void main(String[] args) throws InterruptedException { gdal.AllRegister(); int nbIters = 50; method = METHOD_JAVA_ARRAYS; if (args.length >= 1 && args[0].equalsIgnoreCase("-dbb")) method = METHOD_DBB; Thread t1 = new Thread(new GDALTestIO("/vsimem/test1.tif", nbIters)); Thread t2 = new Thread(new GDALTestIO("/vsimem/test2.tif", nbIters)); t1.start(); t2.start(); t1.join(); t2.join(); System.out.println("Success !"); } }
hyyh619/OpenSceneGraph-3.4.0
3rdparty/gdal/swig/java/apps/GDALTestIO.java
Java
lgpl-2.1
5,589
<?php namespace Pierce; use Noair\Event; class Logger extends \Noair\Listener { private $logger; public function __construct(\Monolog\Logger $logger) { $this->handlers[] = ['all', [$this, 'log'], \Noair\Noair::PRIORITY_URGENT, true]; $this->logger = $logger; } public function log(Event $e) { if ($e->name != 'timer'): echo $e->name . "\n"; print_r($e->data); echo "\n"; endif; } }
garrettw/pierce
src/Logger.php
PHP
lgpl-2.1
482
/* BEGIN_COMMON_COPYRIGHT_HEADER * (c)LGPL2+ * * Razor - a lightweight, Qt based, desktop toolset * http://razor-qt.org * * Copyright: 2010-2011 Razor team * Authors: * Alexander Sokoloff <sokoloff.a@gmail.com> * * This program or library 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 library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General * Public License along with this library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301 USA * * END_COMMON_COPYRIGHT_HEADER */ #include "xdgdirs.h" #include <stdlib.h> #include <QDir> #include <QDebug> /************************************************ Helper func. ************************************************/ void fixBashShortcuts(QString &s) { if (s.startsWith('~')) s = QString(getenv("HOME")) + (s).mid(1); } /************************************************ Helper func. ************************************************/ QString xdgSingleDir(const QString &envVar, const QString &def, bool createDir) { #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QString s(getenv(envVar.toAscii())); #else QString s(getenv(envVar.toLatin1())); #endif if (!s.isEmpty()) fixBashShortcuts(s); else s = QString("%1/%2").arg(getenv("HOME"), def); QDir d(s); if (createDir && !d.exists()) { if (!d.mkpath(".")) qWarning() << QString("Can't create %1 directory.").arg(d.absolutePath()); } return d.absolutePath(); } /************************************************ Helper func. ************************************************/ QStringList xdgDirList(const QString &envVar, const QString &postfix) { #if QT_VERSION < QT_VERSION_CHECK(5,0,0) QStringList dirs = QString(getenv(envVar.toAscii())).split(':', QString::SkipEmptyParts); #else QStringList dirs = QString(getenv(envVar.toLatin1())).split(':', QString::SkipEmptyParts); #endif for (QStringList::Iterator i=dirs.begin(); i!=dirs.end(); ++i) { fixBashShortcuts((*i)); *i += postfix; } return dirs; } /************************************************ ************************************************/ QString XdgDirs::dataHome(bool createDir) { return xdgSingleDir("XDG_DATA_HOME", ".local/share", createDir); } /************************************************ ************************************************/ QString XdgDirs::configHome(bool createDir) { return xdgSingleDir("XDG_CONFIG_HOME", ".config", createDir); } /************************************************ ************************************************/ QStringList XdgDirs::dataDirs(const QString &postfix) { QStringList dirs = xdgDirList("XDG_DATA_DIRS", postfix); if (dirs.isEmpty()) { dirs << "/usr/local/share/" + postfix; dirs << "/usr/share/" + postfix; } return dirs; } /************************************************ ************************************************/ QStringList XdgDirs::configDirs(const QString &postfix) { QStringList dirs = xdgDirList("XDG_CONFIG_DIRS", postfix); if (dirs.isEmpty()) { dirs << "/etc/xdg" << postfix; } return dirs; } /************************************************ ************************************************/ QString XdgDirs::cacheHome(bool createDir) { return xdgSingleDir("XDG_CACHE_HOME", ".cache", createDir); } /************************************************ ************************************************/ QString XdgDirs::runtimeDir() { QString result(getenv("XDG_RUNTIME_DIR")); fixBashShortcuts(result); return result; } /************************************************ ************************************************/ QString XdgDirs::autostartHome(bool createDir) { QDir dir(QString("%1/autostart").arg(configHome(createDir))); if (createDir && !dir.exists()) { if (!dir.mkpath(".")) qWarning() << QString("Can't create %1 directory.").arg(dir.absolutePath()); } return dir.absolutePath(); } /************************************************ ************************************************/ QStringList XdgDirs::autostartDirs(const QString &postfix) { QStringList dirs; foreach(QString dir, configDirs()) dirs << QString("%1/autostart").arg(dir) + postfix; return dirs; }
gilir/libqtxdg-qt5
xdgdirs.cpp
C++
lgpl-2.1
4,865
/*************************************************************************** ASTCreator.cpp This class works as a framework for the creation of an abstract syntax tree specific for a grammar ------------------- begin : Sun Jun 2 2002 copyright : (C) 2002 by Manuel Astudillo ***************************************************************************/ /*************************************************************************** * * * 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 of the * * License, or (at your option) any later version. * * * ***************************************************************************/ #include "ASTCreator.h" // Include the header with YOUR AST node classes ASTNode *ASTCreator::createTree (const Symbol &reductionTree) { // If the tree is an empty terminal node return null return getASTNode (&reductionTree, NULL); } ASTNode *ASTCreator::getASTNode (const Symbol *reduction, ASTNode *parent) { /*! This method has to be customized for YOUR Abstract Grammar. Base your Abstract Grammar in the Context Free Grammar. Check for nodes that are equivalent in both grammars and convert the nodes that are not equivalent. */ //vector <ASTNode*> *children= NULL; wstring sym = reduction->symbol; deque <Symbol*> rdcChildren; if (reduction->type == NON_TERMINAL) { rdcChildren = ((NonTerminal*) reduction)->children; } /* Next is a colection of if statements that checks for the equivalency between nodes in the reduction tree and in the desired Abstract Syntax Tree. Note as we always pass the latest node as the parent for the children. Having the parent is often usefull when doing the type analysis or interpreting the AST. */ /* // (Example of a simple rule) Check for Start node /////////////////////////////////////////////////// // Original Rule: <Start> ::= begin <ConstList> defs <DefsList> prog <StatementList> end // Translated to: <Start> ::= <ConstList> <DefsList> <StatementList> if ( sym == L"Start" ) { Start *start = new Start (); start->init (reduction, parent); start->addChild (getASTNode(rdcChildren[1], start)); start->addChild (getASTNode(rdcChildren[3], start)); start->addChild (getASTNode(rdcChildren[5], start)); return start; } // (Example of a List) //////////////////////// // Original Rule: <StatementList> ::= <Statement> ';' <StatementList> | // Translated to: <StatementList> ::= <Statement>* if (sym == L"StatementList") { StatementList *statementList = new StatementList (); statementList->init (reduction, parent); if (rdcChildren.size() == 3) { statementList->addChild (getASTNode (rdcChildren[0], stmtList)); children = stmtList->getChildren(); getASTNodeList (children, rdcChildren[2]->reduction, 1, 3, stmtList); } return stmtList; } */ /* If the symbol constants are included it is possible to do it in the possible way: // <If Statement> ::= if <Expression> then <StatementList> end if (sym == RULE_IF_THEN_END_STATEMENT) { IfStatement *ifStatement = new IfStatement (); ifStatement->init (reduction, parent); ifStmt->addChild (getASTNode(rdcChildren[1], ifStmt)); ifStmt->addChild (getASTNode(rdcChildren[3], ifStmt)); return ifStmt; } // <If Statement> ::= if <Expression> then <StatementList> else <StatementList> end if ( sym == RULE_IF_THEN_END_ELSE_STATEMENT) { IfStatement *ifStatement = new IfStatement (); ifStatement->init (reduction, parent); ifStmt->addChild (getASTNode(rdcChildren[1], ifStmt)); ifStmt->addChild (getASTNode(rdcChildren[3], ifStmt)); ifStmt->addChild (getASTNode(rdcChildren[5], ifStmt)); return ifStmt; } */ return searchEquivNode( rdcChildren, parent); } /*! If the node has not an equivalent in the Abstract Tree we just search for more equivalent nodes in their children. If none found return NULL. */ ASTNode *ASTCreator::searchEquivNode (const deque <Symbol*> &rdcChildren, ASTNode *parent) { ASTNode *result = NULL; for (unsigned short i=0; i < rdcChildren.size(); i ++) { if (rdcChildren[i]->type == NON_TERMINAL) { result = getASTNode(rdcChildren[i], parent); if (result != NULL) { break; } } } return result; } /*! This method is usefull to create nodes in the tree for rules that have the following structure: NonTerminal1 ::= NonTerminalA NonTerminalB ... NonTerminal1 (Note that left NonTerminal and the last non-terminal in the rule are the same) /param children vector where the children will be added /param reduction reduction tree where the list resides /param nbrInsert specifies the number of children to insert in the vector. Begining from the left of the rule. /param nbrElements specifies the number of element in the "iterative" production. /param parent Parent node, where the list will be hanging. */ void ASTCreator::getASTNodeList (vector <ASTNode*> *children, NonTerminal *reduction, int nbrInsert, int nbrElements, ASTNode *parent) { integer i; ASTNode *ast; deque <Symbol*> rdcChildren = reduction->children; int size = rdcChildren.size(); if (size > 0) { if (size < nbrElements) { for (i=0; i < rdcChildren.size(); i++) { if (i < nbrInsert) { // if we have a rule that produces a // terminal symbol, we only get the node for this reduction if (rdcChildren[i]->type == TERMINAL) { ast = getASTNode (reduction, parent); } else { ast = getASTNode (rdcChildren[i], parent); } // Do not insert NULL childs if (ast!=NULL) { children->push_back(ast); } } } } else { for (i=0; i < rdcChildren.size()-1; i++) { if (i < nbrInsert) { ast = getASTNode (rdcChildren[i], parent); if (ast!=NULL) { children->push_back(ast); } } } if (rdcChildren[i]->type == NON_TERMINAL) { getASTNodeList (children, (NonTerminal*) rdcChildren[i], nbrInsert, nbrElements, parent); } } } } /*! This method is usefull to create nodes in the tree for rules that have the following structure: NonTerminal1 ::= NonTerminalA NonTerminalB ... NonTerminal1 (Note that left NonTerminal and the last non-terminal in the rule are the same) /param children vector where the children will be added /param iterNode name of the Iterative node /param reduction reduction tree where the list resides /param nbrInsert specifies the number of children to insert in the vector. Begining from the left of the rule. /param nbrElements specifies the number of element in the "iterative" production. /param parent Parent node, where the list will be hanging. */ void ASTCreator::getASTNodeList (vector <ASTNode*> *children, wstring iterNode, NonTerminal *reduction, int nbrInsert, int nbrElements, ASTNode *parent) { integer i; ASTNode *ast; wstring sym = reduction->symbol; deque <Symbol*> rdcChildren = reduction->children; if (sym == iterNode) { int size = rdcChildren.size(); if (size > 0) { if (size < nbrElements) { for (i=0; i < rdcChildren.size(); i++) { if (i < nbrInsert) { // if we have a rule that produces a // terminal symbol, we only get the node for this reduction if (rdcChildren[i]->type == TERMINAL) { ast = getASTNode (reduction,parent); } else { ast = getASTNode (rdcChildren[i],parent); } // Do not insert NULL childs if (ast!=NULL) { children->push_back(ast); } } } } else { for (i=0; i < rdcChildren.size()-1; i++) { if (i < nbrInsert) { // Do not insert NULL childs if (rdcChildren[i]->type == NON_TERMINAL) { ast = getASTNode (rdcChildren[i], parent); } else { ast = NULL; } if (ast!=NULL) { children->push_back(ast); } } } if (rdcChildren[i]->type == NON_TERMINAL) { getASTNodeList (children, iterNode, (NonTerminal*) rdcChildren[i], nbrInsert, nbrElements, parent); } } } } else { // If this is not the iterNode then we just push this node as a child. ast = getASTNode (reduction, parent); children->push_back(ast); } }
manast/cpp-gpengine
src/ASTCreator.cpp
C++
lgpl-2.1
9,293
using MaxBootstrap.Core; using MaxBootstrap.Core.View; namespace MaxBootstrap.UI.Views.Options { public class OptionsViewmodel : ViewmodelBase, IOptionsViewmodel { public OptionsViewmodel(IBootstrapperController bootstrapperController, IView view) : base(bootstrapperController, view) { } public override void OnNavigatedTo() { this.BootstrapperController.ViewController.ButtonStateManager.NextButton.Text = "Next"; } } }
Frogman7/MaxBootstrap
Source/MaxBootstrap.UI/Views/Options/OptionsViewmodel.cs
C#
lgpl-2.1
511
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2010 by: - Department of Geography, University of Bonn - and - lat/lon GmbH - This library 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 library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: info@deegree.org ----------------------------------------------------------------------------*/ package org.deegree.tools.rendering.viewer; import java.io.File; import java.util.ArrayList; import java.util.List; import javax.swing.filechooser.FileFilter; /** * The <code>CustomFileFilter</code> class adds functionality to the filefilter mechanism of the JFileChooser. * * @author <a href="mailto:bezema@lat-lon.de">Rutger Bezema</a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class ViewerFileFilter extends FileFilter { private List<String> acceptedExtensions; private String desc; /** * @param acceptedExtensions * list of extensions this filter accepts. * @param description * to show */ public ViewerFileFilter( List<String> acceptedExtensions, String description ) { this.acceptedExtensions = new ArrayList<String>( acceptedExtensions.size() ); StringBuilder sb = new StringBuilder(); if ( acceptedExtensions.size() > 0 ) { sb.append( "(" ); int i = 0; for ( String ext : acceptedExtensions ) { if ( ext.startsWith( "." ) ) { ext = ext.substring( 1 ); } else if ( ext.startsWith( "*." ) ) { ext = ext.substring( 2 ); } else if ( ext.startsWith( "*" ) ) { ext = ext.substring( 1 ); } this.acceptedExtensions.add( ext.trim().toUpperCase() ); sb.append( "*." ); sb.append( ext ); if ( ++i < acceptedExtensions.size() ) { sb.append( ", " ); } } sb.append( ")" ); } sb.append( description ); desc = sb.toString(); } /** * @param extension * @return true if the extension is accepted */ public boolean accepts( String extension ) { return extension != null && acceptedExtensions.contains( extension.toUpperCase() ); } @Override public boolean accept( File pathname ) { if ( pathname.isDirectory() ) { return true; } String extension = getExtension( pathname ); if ( extension != null ) { if ( acceptedExtensions.contains( extension.trim().toUpperCase() ) ) { return true; } } return false; } /** * @param f * @return the file extension (e.g. gml/shp/xml etc.) */ String getExtension( File f ) { String ext = null; String s = f.getName(); int i = s.lastIndexOf( '.' ); if ( i > 0 && i < s.length() - 1 ) { ext = s.substring( i + 1 ).toLowerCase(); } return ext; } @Override public String getDescription() { return desc; } }
deegree/deegree3
deegree-tools/deegree-tools-3d/src/main/java/org/deegree/tools/rendering/viewer/ViewerFileFilter.java
Java
lgpl-2.1
4,138
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH This library 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 library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: info@deegree.org ----------------------------------------------------------------------------*/ package org.deegree.feature.types.property; import java.util.List; import javax.xml.namespace.QName; import org.apache.xerces.xs.XSElementDeclaration; import org.apache.xerces.xs.XSSimpleTypeDefinition; import org.deegree.commons.tom.gml.property.PropertyType; import org.deegree.commons.tom.primitive.BaseType; import org.deegree.commons.tom.primitive.PrimitiveType; /** * A {@link PropertyType} that defines a property with a primitive value, i.e. a value that can be represented as a * single {@link String}. * * @see BaseType * * @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a> * @author last edited by: $Author: schneider $ * * @version $Revision: $, $Date: $ */ public class SimplePropertyType extends AbstractPropertyType { private final PrimitiveType pt; private String codeList; public SimplePropertyType( QName name, int minOccurs, int maxOccurs, BaseType type, XSElementDeclaration elDecl, List<PropertyType> substitutions ) { super( name, minOccurs, maxOccurs, elDecl, substitutions ); this.pt = new PrimitiveType( type ); } public SimplePropertyType( QName name, int minOccurs, int maxOccurs, BaseType type, XSElementDeclaration elDecl, List<PropertyType> substitutions, XSSimpleTypeDefinition xsdType ) { super( name, minOccurs, maxOccurs, elDecl, substitutions ); this.pt = new PrimitiveType( xsdType ); } public void setCodeList( String codeList ) { this.codeList = codeList; } public String getCodeList() { return codeList; } /** * Returns the primitive type. * * @return the primitive type, never <code>null</code> */ public PrimitiveType getPrimitiveType() { return pt; } @Override public String toString() { String s = "- simple property type: '" + name + "', minOccurs=" + minOccurs + ", maxOccurs=" + maxOccurs + ", type: " + pt; return s; } }
deegree/deegree3
deegree-core/deegree-core-base/src/main/java/org/deegree/feature/types/property/SimplePropertyType.java
Java
lgpl-2.1
3,340
# # ICRAR - International Centre for Radio Astronomy Research # (c) UWA - The University of Western Australia, 2015 # Copyright by UWA (in the framework of the ICRAR) # All rights reserved # # This library 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 library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # """ This package contains all python modules implementing the DROP Manager concepts, including their external interface, a web UI and a client """
steve-ord/daliuge
daliuge-engine/dlg/manager/__init__.py
Python
lgpl-2.1
1,112
/* * Material.cpp * * Created on: 22-sep-2009 * Author: hfreire */ #include "Material.h" namespace basics3D { Material::Material() { // TODO Auto-generated constructor stub } Material::~Material() { // TODO Auto-generated destructor stub } }
TLmaK0/pactan
src/basics3D/Material.cpp
C++
lgpl-2.1
267
var searchData= [ ['editable',['editable',['../classBPSDebateView.html#a42784dfc74b99c528a9ee34357b27138',1,'BPSDebateView::editable()'],['../classFocusAndEditTextField.html#af9099a4508112eccd7f6b0aea8cd3970',1,'FocusAndEditTextField::editable()'],['../classOPDDebateView.html#abe79925c1c6e2c9cf8ed5bbdb37e5754',1,'OPDDebateView::editable()'],['../classTable.html#a3c3a525011e324c966b3753eed579d78',1,'Table::editable()']]], ['errors',['errors',['../classMainModel.html#a34dbbb7962b6e0adb074b66a5b2f8056',1,'MainModel']]] ];
Stoeoef/ddt
doxygen/html/search/all_5.js
JavaScript
lgpl-2.1
529
// This file was generated by the Gtk# code generator. // Any changes made will be lost if regenerated. namespace GLib { using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; #region Autogenerated code public partial class DBusSignalInfo : GLib.Opaque { [DllImport ("giosharpglue-3")] extern static uint glibsharp_glib_dbussignalinfo_get_ref_count_offset (); static uint ref_count_offset = glibsharp_glib_dbussignalinfo_get_ref_count_offset (); public int RefCount { get { unsafe { int* raw_ptr = (int*)(((byte*)Handle) + ref_count_offset); return (*raw_ptr); } } set { unsafe { int* raw_ptr = (int*)(((byte*)Handle) + ref_count_offset); *raw_ptr = value; } } } [DllImport ("giosharpglue-3")] extern static uint glibsharp_glib_dbussignalinfo_get_name_offset (); static uint name_offset = glibsharp_glib_dbussignalinfo_get_name_offset (); public string Name { get { unsafe { IntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + name_offset); return GLib.Marshaller.Utf8PtrToString ((*raw_ptr)); } } set { unsafe { IntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + name_offset); *raw_ptr = GLib.Marshaller.StringToPtrGStrdup (value); } } } [DllImport ("giosharpglue-3")] extern static uint glibsharp_glib_dbussignalinfo_get_args_offset (); static uint args_offset = glibsharp_glib_dbussignalinfo_get_args_offset (); public GLib.DBusArgInfo Args { get { unsafe { IntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + args_offset); return (*raw_ptr) == IntPtr.Zero ? null : (GLib.DBusArgInfo) GLib.Opaque.GetOpaque ((*raw_ptr), typeof (GLib.DBusArgInfo), false); } } set { unsafe { IntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + args_offset); *raw_ptr = value == null ? IntPtr.Zero : value.Handle; } } } [DllImport ("giosharpglue-3")] extern static uint glibsharp_glib_dbussignalinfo_get_annotations_offset (); static uint annotations_offset = glibsharp_glib_dbussignalinfo_get_annotations_offset (); public GLib.DBusAnnotationInfo Annotations { get { unsafe { IntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + annotations_offset); return (*raw_ptr) == IntPtr.Zero ? null : (GLib.DBusAnnotationInfo) GLib.Opaque.GetOpaque ((*raw_ptr), typeof (GLib.DBusAnnotationInfo), false); } } set { unsafe { IntPtr* raw_ptr = (IntPtr*)(((byte*)Handle) + annotations_offset); *raw_ptr = value == null ? IntPtr.Zero : value.Handle; } } } [DllImport("libgio-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr g_dbus_signal_info_get_type(); public static GLib.GType GType { get { IntPtr raw_ret = g_dbus_signal_info_get_type(); GLib.GType ret = new GLib.GType(raw_ret); return ret; } } public DBusSignalInfo(IntPtr raw) : base(raw) {} [DllImport("libgio-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr g_dbus_signal_info_ref(IntPtr raw); protected override void Ref (IntPtr raw) { if (!Owned) { g_dbus_signal_info_ref (raw); Owned = true; } } [DllImport("libgio-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern void g_dbus_signal_info_unref(IntPtr raw); protected override void Unref (IntPtr raw) { if (Owned) { g_dbus_signal_info_unref (raw); Owned = false; } } class FinalizerInfo { IntPtr handle; public FinalizerInfo (IntPtr handle) { this.handle = handle; } public bool Handler () { g_dbus_signal_info_unref (handle); return false; } } ~DBusSignalInfo () { if (!Owned) return; FinalizerInfo info = new FinalizerInfo (Handle); GLib.Timeout.Add (50, new GLib.TimeoutHandler (info.Handler)); } #endregion } }
akrisiun/gtk-sharp
gio/generated/GLib/DBusSignalInfo.cs
C#
lgpl-2.1
3,901
#ifndef BIONET_SWIG_TYPES #define BIONET_SWIG_TYPES typedef struct { bionet_hab_t * this; } Hab; typedef struct { void * hab; void * hp; } HabUserData; typedef struct { bionet_node_t * this; } Node; typedef struct { bionet_resource_t * this; } Resource; typedef struct { bionet_datapoint_t * this; } Datapoint; typedef struct { bionet_value_t * this; } Value; typedef struct { bionet_bdm_t * this; } Bdm; typedef struct { bionet_epsilon_t * this; bionet_resource_data_type_t datatype; } Epsilon; typedef struct { bionet_stream_t * this; } Stream; typedef struct { bionet_event_t * this; } Event; #endif /* BIONET_SWIG_TYPES */
ldm5180/hammerhead
util/bionet-swig-types.h
C
lgpl-2.1
687
/* * Created on Feb 20, 2006 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. * * Copyright @2006 the original author or authors. */ package org.springmodules.cache.config; import java.util.List; import java.util.Map; import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.PropertyValue; import org.springframework.beans.factory.config.RuntimeBeanReference; /** * <p> * Stores properties that are common to all configuration strategies. * </p> * * @author Alex Ruiz */ public final class CacheSetupStrategyPropertySource { public final Object cacheKeyGenerator; public final RuntimeBeanReference cacheProviderFacadeReference; public final List cachingListeners; public final Map cachingModelMap; public final Map flushingModelMap; /** * Constructor. * * @param newCacheKeyGenerator * a cache key generator or a reference to an already existing one * @param newCacheProviderFacade * a reference to the cache provider facade * @param newCachingListeners * a list of caching listeners * @param newCachingModelMap * a list of caching models * @param newFlushingModelMap * a list of flushing models */ public CacheSetupStrategyPropertySource(Object newCacheKeyGenerator, RuntimeBeanReference newCacheProviderFacade, List newCachingListeners, Map newCachingModelMap, Map newFlushingModelMap) { super(); cacheKeyGenerator = newCacheKeyGenerator; cacheProviderFacadeReference = newCacheProviderFacade; cachingListeners = newCachingListeners; cachingModelMap = newCachingModelMap; flushingModelMap = newFlushingModelMap; } /** * Returns the properties specified by: * <ul> * <li><code>{@link #getCacheProviderFacadeProperty()}</code></li> * <li><code>{@link #getCachingListenersProperty()}</code></li> * <li><code>{@link #getCachingModelsProperty()}</code></li> * <li><code>{@link #getFlushingModelsProperty()}</code></li> * </ul> * * @return all the properties stored in this object. */ public MutablePropertyValues getAllProperties() { MutablePropertyValues allPropertyValues = new MutablePropertyValues(); allPropertyValues.addPropertyValue(getCacheKeyGeneratorProperty()); allPropertyValues.addPropertyValue(getCacheProviderFacadeProperty()); allPropertyValues.addPropertyValue(getCachingListenersProperty()); allPropertyValues.addPropertyValue(getCachingModelsProperty()); allPropertyValues.addPropertyValue(getFlushingModelsProperty()); return allPropertyValues; } public PropertyValue getCacheKeyGeneratorProperty() { return new PropertyValue("cacheKeyGenerator", cacheKeyGenerator); } public PropertyValue getCacheProviderFacadeProperty() { return new PropertyValue("cacheProviderFacade", cacheProviderFacadeReference); } public PropertyValue getCachingListenersProperty() { return new PropertyValue("cachingListeners", cachingListeners); } public PropertyValue getCachingModelsProperty() { return new PropertyValue("cachingModels", cachingModelMap); } public PropertyValue getFlushingModelsProperty() { return new PropertyValue("flushingModels", flushingModelMap); } }
cacheonix/cacheonix-core
3rdparty/spring-modules-integration-proxy/src/org/springmodules/cache/config/CacheSetupStrategyPropertySource.java
Java
lgpl-2.1
3,790
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QEVENT_P_H #define QEVENT_P_H #include <QtCore/qglobal.h> #include <QtCore/qurl.h> #include <QtGui/qevent.h> QT_BEGIN_NAMESPACE // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // // ### Qt 5: remove class QKeyEventEx : public QKeyEvent { public: QKeyEventEx(Type type, int key, Qt::KeyboardModifiers modifiers, const QString &text, bool autorep, ushort count, quint32 nativeScanCode, quint32 nativeVirtualKey, quint32 nativeModifiers); QKeyEventEx(const QKeyEventEx &other); ~QKeyEventEx(); protected: quint32 nScanCode; quint32 nVirtualKey; quint32 nModifiers; friend class QKeyEvent; }; // ### Qt 5: remove class QMouseEventEx : public QMouseEvent { public: QMouseEventEx(Type type, const QPointF &pos, const QPoint &globalPos, Qt::MouseButton button, Qt::MouseButtons buttons, Qt::KeyboardModifiers modifiers); ~QMouseEventEx(); protected: QPointF posF; friend class QMouseEvent; }; class QTouchEventTouchPointPrivate { public: inline QTouchEventTouchPointPrivate(int id) : ref(1), id(id), state(Qt::TouchPointReleased), pressure(qreal(-1.)) { } inline QTouchEventTouchPointPrivate *detach() { QTouchEventTouchPointPrivate *d = new QTouchEventTouchPointPrivate(*this); d->ref = 1; if (!this->ref.deref()) delete this; return d; } QAtomicInt ref; int id; Qt::TouchPointStates state; QRectF rect, sceneRect, screenRect; QPointF normalizedPos, startPos, startScenePos, startScreenPos, startNormalizedPos, lastPos, lastScenePos, lastScreenPos, lastNormalizedPos; qreal pressure; }; class QNativeGestureEvent : public QEvent { public: enum Type { None, GestureBegin, GestureEnd, Pan, Zoom, Rotate, Swipe }; QNativeGestureEvent() : QEvent(QEvent::NativeGesture), gestureType(None), percentage(0) #ifdef Q_WS_WIN , sequenceId(0), argument(0) #endif { } Type gestureType; float percentage; QPoint position; float angle; #ifdef Q_WS_WIN ulong sequenceId; quint64 argument; #endif }; class QGestureEventPrivate { public: inline QGestureEventPrivate(const QList<QGesture *> &list) : gestures(list), widget(0) { } QList<QGesture *> gestures; QWidget *widget; QMap<Qt::GestureType, bool> accepted; QMap<Qt::GestureType, QWidget *> targetWidgets; }; class QFileOpenEventPrivate { public: inline QFileOpenEventPrivate(const QUrl &url) : url(url) { } QUrl url; }; QT_END_NAMESPACE #endif // QEVENT_P_H
kobolabs/qt-everywhere-opensource-src-4.6.2
src/gui/kernel/qevent_p.h
C
lgpl-2.1
4,893
#include <cstdlib> #include <fstream> #include <iostream> #include <vector> #include "rlcsa_builder.h" #include "misc/utils.h" using namespace CSA; int lineByLineRLCSA(std::string base_name, usint block_size, usint sample_rate, usint buffer_size) { Parameters parameters; parameters.set(RLCSA_BLOCK_SIZE.first, block_size); parameters.set(SAMPLE_RATE.first, sample_rate); if(sample_rate > 0) { parameters.set(SUPPORT_LOCATE.first, 1); parameters.set(SUPPORT_DISPLAY.first, 1); } else { parameters.set(SUPPORT_LOCATE.first, 0); parameters.set(SUPPORT_DISPLAY.first, 0); } std::string parameters_name = base_name + PARAMETERS_EXTENSION; parameters.print(); parameters.write(parameters_name); std::cout << "Input: " << base_name << std::endl; std::ifstream input_file(base_name.c_str(), std::ios_base::binary); if(!input_file) { std::cerr << "Error opening input file!" << std::endl; return 2; } std::cout << "Buffer size: " << buffer_size << " MB" << std::endl; std::cout << std::endl; double start = readTimer(); RLCSABuilder builder(parameters.get(RLCSA_BLOCK_SIZE), parameters.get(SAMPLE_RATE), buffer_size * MEGABYTE); usint lines = 0, total = 0; while(input_file) { char buffer[16384]; // FIXME What if lines are longer? Probably fails. input_file.getline(buffer, 16384); usint chars = input_file.gcount(); lines++; total += chars; if(chars >= 16383) { std::cout << lines << ": " << chars << " chars read!" << std::endl; } if(chars > 1) { builder.insertSequence(buffer, chars - 1, false); } } RLCSA* rlcsa = 0; if(builder.isOk()) { rlcsa = builder.getRLCSA(); rlcsa->writeTo(base_name); } else { std::cerr << "Error: RLCSA construction failed!" << std::endl; return 3; } double time = readTimer() - start; double build_time = builder.getBuildTime(); double search_time = builder.getSearchTime(); double sort_time = builder.getSortTime(); double merge_time = builder.getMergeTime(); double megabytes = rlcsa->getSize() / (double)MEGABYTE; usint sequences = rlcsa->getNumberOfSequences(); std::cout << sequences << " sequences" << std::endl; std::cout << megabytes << " megabytes in " << time << " seconds (" << (megabytes / time) << " MB/s)" << std::endl; std::cout << "(build " << build_time << " s, search " << search_time << "s, sort " << sort_time << " s, merge " << merge_time << " s)" << std::endl; std::cout << std::endl; delete rlcsa; return 0; } int main(int argc, char** argv) { std::cout << "Line-by-line RLCSA builder" << std::endl; if(argc < 3) { std::cout << "Usage: build_rlcsa base_name buffer_size [block_size [sample_rate]]" << std::endl; return 1; } std::cout << std::endl; int name_arg = 1, buffer_arg = 2, block_arg = 3, sample_arg = 4; usint block_size = (argc > block_arg ? atoi(argv[block_arg]) : RLCSA_BLOCK_SIZE.second); usint sample_rate = (argc > sample_arg ? atoi(argv[sample_arg]) : SAMPLE_RATE.second); return lineByLineRLCSA(argv[name_arg], block_size, sample_rate, atoi(argv[buffer_arg])); }
migumar2/uiHRDC
uiHRDC/self-indexes/RLCSAM/rlcsa/build_rlcsa.cpp
C++
lgpl-2.1
3,126
/****************************************************************************** * This file is part of the libqgit2 library * * This library 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 library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "qgitrebaseoptions.h" #include "qgitcheckoutoptions.h" namespace LibQGit2 { struct RebaseOptions::Private { Private(const CheckoutOptions &checkoutOpts) : mOpts() { git_rebase_options &opts = const_cast<git_rebase_options &>(mOpts); git_rebase_init_options(&opts, GIT_REBASE_OPTIONS_VERSION); opts.checkout_options = *checkoutOpts.data(); } const git_rebase_options *constData() const { return &mOpts; } private: const git_rebase_options mOpts; }; RebaseOptions::RebaseOptions(const CheckoutOptions &checkoutOptions) : d_ptr(new Private(checkoutOptions)) { } const git_rebase_options *RebaseOptions::constData() const { return d_ptr->constData(); } }
KDE/libqgit2
src/qgitrebaseoptions.cpp
C++
lgpl-2.1
1,616
/* include standard header */ /* you will need to include this in all of your php extension projects*/ #include "php.h" #include "php_ahcrypto.h" // external function defined in crypto++.cpp void internal_rsa_create_keys( unsigned int keysize, unsigned char * * n_dat, size_t * n_len, unsigned char * * e_dat, size_t * e_len, unsigned char * * d_dat, size_t * d_len, unsigned char * * p_dat, size_t * p_len, unsigned char * * q_dat, size_t * q_len ); void internal_rsa_cipher( unsigned char * clear_data, size_t clear_data_len, unsigned char * n_dat, size_t n_len, unsigned char * e_dat, size_t e_len, unsigned char * * cryptogram, size_t * cryptogram_len ); void internal_rsa_decipher( unsigned char * cryptogram, size_t cryptogram_len, unsigned char * n_dat, size_t n_len, unsigned char * e_dat, size_t e_len, unsigned char * d_dat, size_t d_len, unsigned char * p_dat, size_t p_len, unsigned char * q_dat, size_t q_len, unsigned char * * clear_data, size_t * clear_data_len ); void internal_rsa_sign( unsigned char * data, size_t data_len, unsigned char * n_dat, size_t n_len, unsigned char * e_dat, size_t e_len, unsigned char * d_dat, size_t d_len, unsigned char * p_dat, size_t p_len, unsigned char * q_dat, size_t q_len, unsigned char * * signature, size_t * signature_len ); int internal_rsa_verify( unsigned char * data, size_t data_len, unsigned char * signature, size_t signature_len, unsigned char * n_dat, size_t n_len, unsigned char * e_dat, size_t e_len ); void internal_aes_cipher( unsigned char * clear_data, size_t clear_data_len, unsigned char * k_dat, size_t k_len, unsigned char * * cryptogram, size_t * cryptogram_len ); void internal_aes_decipher( unsigned char * cryptogram, size_t cryptogram_len, unsigned char * k_dat, size_t k_len, unsigned char * * clear_data, size_t * clear_data_len ); function_entry ahcrypto_functions[] = { PHP_FE(ahrsa_create_keys, NULL) PHP_FE(ahrsa_cipher, NULL) PHP_FE(ahrsa_decipher, NULL) PHP_FE(ahrsa_sign, NULL) PHP_FE(ahrsa_verify, NULL) PHP_FE(ahaes_cipher, NULL) PHP_FE(ahaes_decipher, NULL) {NULL, NULL, NULL} }; zend_module_entry ahcrypto_module_entry = { STANDARD_MODULE_HEADER, "AHCRYPTO", ahcrypto_functions, PHP_MINIT(ahcrypto), PHP_MSHUTDOWN(ahcrypto), NULL, NULL, PHP_MINFO(ahcrypto), NO_VERSION_YET, STANDARD_MODULE_PROPERTIES }; #if COMPILE_DL_AHCRYPTO ZEND_GET_MODULE(ahcrypto) #endif PHP_MINIT_FUNCTION(ahcrypto) { return 0; } PHP_MSHUTDOWN_FUNCTION(ahcrypto) { return 0; } PHP_MINFO_FUNCTION(ahcrypto) { php_info_print_table_start(); php_info_print_table_row(2, "Made by", "ADETTI, 2004"); php_info_print_table_end(); } PHP_FUNCTION(ahrsa_create_keys) { int size; unsigned char * n_dat = 0, * e_dat = 0, * d_dat = 0, * p_dat = 0, * q_dat = 0; size_t n_len = 0, e_len = 0, d_len = 0, p_len = 0, q_len = 0; if(ZEND_NUM_ARGS() != 1) WRONG_PARAM_COUNT; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &size) == FAILURE) { RETURN_FALSE; } internal_rsa_create_keys(size, &n_dat, &n_len, &e_dat, &e_len, &d_dat, &d_len, &p_dat, &p_len, &q_dat, &q_len); array_init(return_value); add_assoc_stringl(return_value, "n", n_dat, n_len, 1); add_assoc_stringl(return_value, "e", e_dat, e_len, 1); add_assoc_stringl(return_value, "d", d_dat, d_len, 1); add_assoc_stringl(return_value, "p", p_dat, p_len, 1); add_assoc_stringl(return_value, "q", q_dat, q_len, 1); efree(n_dat); efree(e_dat); efree(d_dat); efree(p_dat); efree(q_dat); } PHP_FUNCTION(ahrsa_cipher) { unsigned char * clear_data; unsigned char * n_dat, * e_dat; size_t clear_data_len, n_len, e_len; unsigned char * cryptogram; size_t cryptogram_len; if(ZEND_NUM_ARGS() != 3) WRONG_PARAM_COUNT; /* Extract parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sss", &clear_data, &clear_data_len, &n_dat, &n_len, &e_dat, &e_len) == FAILURE) { return; } RETVAL_FALSE; if (clear_data_len > n_len - 11) return; // message too long internal_rsa_cipher(clear_data, clear_data_len, n_dat, n_len, e_dat, e_len, &cryptogram, &cryptogram_len); if (cryptogram != NULL && cryptogram_len != 0) { RETVAL_STRINGL(cryptogram, cryptogram_len, TRUE); } if (cryptogram != NULL) efree(cryptogram); } PHP_FUNCTION(ahrsa_decipher) { unsigned char * cryptogram; unsigned char * n_dat, * e_dat, *d_dat, *p_dat, *q_dat; size_t cryptogram_len, n_len, e_len, d_len, p_len, q_len; unsigned char * clear_data; size_t clear_data_len; if(ZEND_NUM_ARGS() != 6) WRONG_PARAM_COUNT; /* Extract parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssssss", &cryptogram, &cryptogram_len, &n_dat, &n_len, &e_dat, &e_len, &d_dat, &d_len, &p_dat, &p_len, &q_dat, &q_len) == FAILURE) { return; } RETVAL_FALSE; internal_rsa_decipher( cryptogram, cryptogram_len, n_dat, n_len, e_dat, e_len, d_dat, d_len, p_dat, p_len, q_dat, q_len, &clear_data, &clear_data_len ); if (clear_data != NULL && clear_data_len != 0) { RETVAL_STRINGL(clear_data, clear_data_len, TRUE); } if (clear_data != NULL) efree(clear_data); } PHP_FUNCTION(ahrsa_sign) { unsigned char * data; unsigned char * n_dat, * e_dat, *d_dat, *p_dat, *q_dat; size_t data_len, n_len, e_len, d_len, p_len, q_len; unsigned char * signature; size_t signature_len; if(ZEND_NUM_ARGS() != 6) WRONG_PARAM_COUNT; /* Extract parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssssss", &data, &data_len, &n_dat, &n_len, &e_dat, &e_len, &d_dat, &d_len, &p_dat, &p_len, &q_dat, &q_len) == FAILURE) { return; } RETVAL_FALSE; internal_rsa_sign( data, data_len, n_dat, n_len, e_dat, e_len, d_dat, d_len, p_dat, p_len, q_dat, q_len, &signature, &signature_len ); if (signature != NULL && signature_len != 0) { RETVAL_STRINGL(signature, signature_len, TRUE); } if (signature != NULL) efree(signature); } PHP_FUNCTION(ahrsa_verify) { unsigned char * data, * signature; unsigned char * n_dat, * e_dat; size_t data_len, signature_len, n_len, e_len; if(ZEND_NUM_ARGS() != 4) WRONG_PARAM_COUNT; /* Extract parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ssss", &data, &data_len, &signature, &signature_len, &n_dat, &n_len, &e_dat, &e_len) == FAILURE) { return; } RETVAL_FALSE; if (internal_rsa_verify( data, data_len, signature, signature_len, n_dat, n_len, e_dat, e_len )) RETVAL_TRUE; } PHP_FUNCTION(ahaes_cipher) { unsigned char * clear_data; unsigned char * k_dat; size_t clear_data_len, k_len; unsigned char * cryptogram; size_t cryptogram_len; if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT; /* Extract parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &clear_data, &clear_data_len, &k_dat, &k_len) == FAILURE) { return; } RETVAL_FALSE; if (k_len != 16 && k_len != 24 && k_len != 32) return; // invalid key internal_aes_cipher(clear_data, clear_data_len, k_dat, k_len, &cryptogram, &cryptogram_len); if (cryptogram != NULL && cryptogram_len != 0) { RETVAL_STRINGL(cryptogram, cryptogram_len, TRUE); } if (cryptogram != NULL) efree(cryptogram); } PHP_FUNCTION(ahaes_decipher) { unsigned char * cryptogram; unsigned char * k_dat; size_t cryptogram_len, k_len; unsigned char * clear_data; size_t clear_data_len; if(ZEND_NUM_ARGS() != 2) WRONG_PARAM_COUNT; /* Extract parameters */ if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ss", &cryptogram, &cryptogram_len, &k_dat, &k_len) == FAILURE) { return; } RETVAL_FALSE; if (k_len != 16 && k_len != 24 && k_len != 32) return; // invalid key internal_aes_decipher( cryptogram, cryptogram_len, k_dat, k_len, &clear_data, &clear_data_len ); if (clear_data != NULL && clear_data_len != 0) { RETVAL_STRINGL(clear_data, clear_data_len, TRUE); } if (clear_data != NULL) efree(clear_data); }
pontocom/opensdrm
server/php_module/ahcrypto/ahcrypto.c
C
lgpl-2.1
8,336
/********************************************************************** * * FILE: Depth.cpp * * DESCRIPTION: Read/Write osg::Depth in binary format to disk. * * CREATED BY: Botorabi AT gmx DOT net * * HISTORY: Created 14.12.2005 * **********************************************************************/ #include "Exception.h" #include "Depth.h" #include "Object.h" using namespace ive; void Depth::write(DataOutputStream* out){ // Write Depth's identification. out->writeInt(IVEDEPTH); // If the osg class is inherited by any other class we should also write this to file. osg::Object* obj = dynamic_cast<osg::Object*>(this); if(obj){ ((ive::Object*)(obj))->write(out); } else throw Exception("Depth::write(): Could not cast this osg::Depth to an osg::Object."); // Write Depth's properties. out->writeInt(getFunction()); out->writeBool(getWriteMask()); out->writeFloat(getZNear()); out->writeFloat(getZFar()); } void Depth::read(DataInputStream* in){ // Peek on Depth's identification. int id = in->peekInt(); if(id == IVEDEPTH){ // Read Depth's identification. id = in->readInt(); // If the osg class is inherited by any other class we should also read this from file. osg::Object* obj = dynamic_cast<osg::Object*>(this); if(obj){ ((ive::Object*)(obj))->read(in); } else throw Exception("Depth::read(): Could not cast this osg::Depth to an osg::Object."); // Read CullFace's properties setFunction((osg::Depth::Function)in->readInt()); setWriteMask(in->readBool()); setZNear(in->readFloat()); setZFar(in->readFloat()); } else{ throw Exception("Depth::read(): Expected Depth identification."); } }
joevandyk/osg
src/osgPlugins/ive/Depth.cpp
C++
lgpl-2.1
1,860
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>fireMessageReceived</title> <!-- <script src="http://use.edgefonts.net/source-sans-pro;source-code-pro.js"></script> --> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic|Source+Code+Pro:300,400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="../assets/css/bootstrap.css"> <link rel="stylesheet" href="../assets/css/jquery.bonsai.css"> <link rel="stylesheet" href="../assets/css/main.css"> <link rel="stylesheet" href="../assets/css/icons.css"> <script type="text/javascript" src="../assets/js/jquery-2.1.0.min.js"></script> <script type="text/javascript" src="../assets/js/bootstrap.js"></script> <script type="text/javascript" src="../assets/js/jquery.bonsai.js"></script> <!-- <script type="text/javascript" src="../assets/js/main.js"></script> --> </head> <body> <div> <!-- Name Title --> <h1>fireMessageReceived</h1> <!-- Type and Stereotype --> <section style="margin-top: .5em;"> <span class="alert alert-info"> <span class="node-icon _icon-UMLOperation"></span> UMLOperation </span> </section> <!-- Path --> <section style="margin-top: 10px"> <span class="label label-info"><a href='cf9c8b720f3815adeccaf3ef6e48c6c4.html'><span class='node-icon _icon-Project'></span>Untitled</a></span> <span>::</span> <span class="label label-info"><a href='6550300e57d7fc770bd2e9afbcdb3ecb.html'><span class='node-icon _icon-UMLModel'></span>JavaReverse</a></span> <span>::</span> <span class="label label-info"><a href='7ff2d96ca3eb7f62f48c1a30b3c7c990.html'><span class='node-icon _icon-UMLPackage'></span>net</a></span> <span>::</span> <span class="label label-info"><a href='7adc4be4f2e4859086f068fc27512d85.html'><span class='node-icon _icon-UMLPackage'></span>gleamynode</a></span> <span>::</span> <span class="label label-info"><a href='bb15307bdbbaf31bfef4f71be74150ae.html'><span class='node-icon _icon-UMLPackage'></span>netty</a></span> <span>::</span> <span class="label label-info"><a href='392fd228dddcffe2ef252f5663cf31a7.html'><span class='node-icon _icon-UMLPackage'></span>channel</a></span> <span>::</span> <span class="label label-info"><a href='f033a5bdbfb1de4788040be6e1f18036.html'><span class='node-icon _icon-UMLClass'></span>Channels</a></span> <span>::</span> <span class="label label-info"><a href='485edef14a75aa28d5ce5d35fbd57675.html'><span class='node-icon _icon-UMLOperation'></span>fireMessageReceived</a></span> </section> <!-- Diagram --> <!-- Description --> <section> <h3>Description</h3> <div> <span class="label label-info">none</span> </div> </section> <!-- Specification --> <!-- Directed Relationship --> <!-- Undirected Relationship --> <!-- Classifier --> <!-- Interface --> <!-- Component --> <!-- Node --> <!-- Actor --> <!-- Use Case --> <!-- Template Parameters --> <!-- Literals --> <!-- Attributes --> <!-- Operations --> <!-- Receptions --> <!-- Extension Points --> <!-- Parameters --> <section> <h3>Parameters</h3> <table class="table table-striped table-bordered"> <tr> <th>Direction</th> <th>Name</th> <th>Type</th> <th>Description</th> </tr> <tr> <td>in</td> <td><a href="02bd01c7252f651bc81696a054b18edb.html">ctx</a></td> <td><a href='df0aa79628578e1a1d7b267be81f8957.html'><span class='node-icon _icon-UMLInterface'></span>ChannelHandlerContext</a></td> <td></td> </tr> <tr> <td>in</td> <td><a href="6058a99b2a43fef803fa8bb2594c8bdb.html">channel</a></td> <td><a href='608db9b18faa13dff5f84e6ba586bc6b.html'><span class='node-icon _icon-UMLInterface'></span>Channel</a></td> <td></td> </tr> <tr> <td>in</td> <td><a href="01c6331dc99f585921fbe33b909d90ed.html">message</a></td> <td><a href='52af50a5b0f2ed4d23d445d13bc072ee.html'><span class='node-icon _icon-UMLClass'></span>Object</a></td> <td></td> </tr> <tr> <td>return</td> <td><a href="a7a7e2fa51fed8d42ef376d7fa487b8d.html">(unnamed)</a></td> <td>void</td> <td></td> </tr> </table> </section> <!-- Diagrams --> <!-- Behavior --> <!-- Action --> <!-- Interaction --> <!-- CombinedFragment --> <!-- Activity --> <!-- State Machine --> <!-- State Machine --> <!-- State --> <!-- Vertex --> <!-- Transition --> <!-- Properties --> <section> <h3>Properties</h3> <table class="table table-striped table-bordered"> <tr> <th width="50%">Name</th> <th width="50%">Value</th> </tr> <tr> <td>name</td> <td>fireMessageReceived</td> </tr> <tr> <td>stereotype</td> <td><span class='label label-info'>null</span></td> </tr> <tr> <td>visibility</td> <td>public</td> </tr> <tr> <td>isStatic</td> <td><span class='label label-info'>true</span></td> </tr> <tr> <td>isLeaf</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>parameters</td> <td> <a href='02bd01c7252f651bc81696a054b18edb.html'><span class='node-icon _icon-UMLParameter'></span>ctx</a> <span>, </span> <a href='6058a99b2a43fef803fa8bb2594c8bdb.html'><span class='node-icon _icon-UMLParameter'></span>channel</a> <span>, </span> <a href='01c6331dc99f585921fbe33b909d90ed.html'><span class='node-icon _icon-UMLParameter'></span>message</a> <span>, </span> <a href='a7a7e2fa51fed8d42ef376d7fa487b8d.html'><span class='node-icon _icon-UMLParameter'></span>(Parameter)</a> </td> </tr> <tr> <td>raisedExceptions</td> <td> </td> </tr> <tr> <td>concurrency</td> <td>sequential</td> </tr> <tr> <td>isQuery</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>isAbstract</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>specification</td> <td></td> </tr> </table> </section> <!-- Tags --> <!-- Constraints, Dependencies, Dependants --> <!-- Relationships --> <!-- Owned Elements --> </div> </body> </html>
jiangbo212/netty-init
html-docs/contents/485edef14a75aa28d5ce5d35fbd57675.html
HTML
lgpl-2.1
9,439
package test.de.meinkonzern.gtdclient.model; public class ActionTest { // private static Validator validator; // @BeforeClass // protected void setUp() throws Exception { // super.setUp(); // ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); // validator = factory.getValidator(); // } // // //@ Test // public void testDescription() { // // Action action = new GTDModel().createNewTopActionOfInputStack(); // action.setDescription("test"); // // Set<ConstraintViolation<Action>> constraintViolations = validator // .validate(action); // // if (constraintViolations.size() > 0) { // assertEquals(1, constraintViolations.size()); // assertEquals("Description must be valid", constraintViolations // .iterator().next().getMessage()); // } // // } }
FunThomas424242/gtdclient
src/test/java/test/de/meinkonzern/gtdclient/model/ActionTest.java
Java
lgpl-2.1
792
/* Copyright (c) 2013 Android Lin <acen@dmp.com.tw>. All right reserved. This library 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 library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "Arduino.h" #include "io.h" #include "USBCore.h" #include "mcm.h" #include "irq.h" #include "stdio.h" void *USBDEV = NULL; unsigned long CLOCKS_PER_MICROSEC = 300L; // The default value is 300Mhz for 86Duino, you should call init() to set it automatically. unsigned long VORTEX86EX_CLOCKS_PER_MS = 300000L; // The default value is 300000 for 86Duino, you should call init() to set it automatically. bool Global_irq_Init = false; unsigned long millis() { return timer_NowTime(); } void delay(unsigned long ms) { timer_Delay(ms); } // For 86Duino IDE, only use micros() after calling init() unsigned long micros() { return (unsigned long) (timer_GetClocks64()/CLOCKS_PER_MICROSEC); } void delayMicroseconds(unsigned long us) { timer_DelayMicroseconds(us); } bool init() { int i, crossbarBase, gpioBase; if(io_Init() == false) return false; timer_NowTime(); // initialize timer CLOCKS_PER_MICROSEC = vx86_CpuCLK(); VORTEX86EX_CLOCKS_PER_MS = CLOCKS_PER_MICROSEC*1000UL; // Set IRQ4 as level-trigger io_outpb(0x4D0, io_inpb(0x4D0) | 0x10); //set corssbar Base Address crossbarBase = sb_Read16(SB_CROSSBASE) & 0xfffe; if(crossbarBase == 0 || crossbarBase == 0xfffe) sb_Write16(SB_CROSSBASE, CROSSBARBASE | 0x01); // Force set HIGH speed ISA on SB sb_Write(SB_FCREG, sb_Read(SB_FCREG) | 0x8000C000L); //set SB GPIO Base Address gpioBase = sb_Read16(SB_GPIOBASE) & 0xfffe; if(gpioBase == 0 || gpioBase == 0xfffe) { sb_Write16(SB_GPIOBASE, GPIOCTRLBASE | 0x01); gpioBase = GPIOCTRLBASE; } // Enable GPIO 0 ~ 7 io_outpdw(gpioBase, 0x00ff); // set GPIO Port 0~7 dircetion & data Address for(i=0;i<8;i++) io_outpdw(gpioBase + (i+1)*4,((GPIODIRBASE + i*4)<<16) + GPIODATABASE + i*4); // set ADC Base Address sb_Write(0xbc, sb_Read(0xbc) & (~(1L<<28))); // active adc sb1_Write16(0xde, sb1_Read16(0xde) | 0x02); // not Available for 8051A Access ADC sb1_Write(0xe0, 0x0050fe00L); // baseaddr = 0xfe00, disable irq io_outpb(0xfe01, 0x00); while((io_inpb(0xfe02) & 0x01) != 0) io_inpb(0xfe04); // set MCM Base Address mcmInit(); for(i=0; i<4; i++) mc_SetMode(i, MCMODE_PWM_SIFB); // init spinlock spinLockInit(); #if defined (DMP_DOS_BC) || defined (DMP_DOS_DJGPP) if(Global_irq_Init == false) { // set MCM IRQ if(irq_Init() == false) { printf("MCM IRQ init fail\n"); return false; } if(irq_Setting(GetMCIRQ(), IRQ_LEVEL_TRIGGER + IRQ_DISABLE_INTR) == false) { printf("MCM IRQ Setting fail\n"); return false; } Set_MCIRQ(GetMCIRQ()); Global_irq_Init = true; } //CDC USBDEV = CreateUSBDevice(); if(USBDEV == NULL) { printf("init error\n"); return false; } usb_SetUSBPins(USBDEV, 7, 0, 7, 1); usb_SetTimeOut(USBDEV, 0L, 500L); // USB RX timerout is 0ms and TX timeout is 500ms if(usb_Init(USBDEV) == false) { printf("init2 error\n"); return false; } #endif //io_Close(); return true; }
roboard/86Duino_Linux_SDK
cores/wiring.cpp
C++
lgpl-2.1
3,757
#!/usr/bin/env python # -*- coding: utf-8 -*- # ------------------------------------------------------------------- # Copyright (c) 2010-2019 Denis Machard # This file is part of the extensive automation project # # This library 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 library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # MA 02110-1301 USA # ------------------------------------------------------------------- import threading import time from ea.libs.NetLayerLib import ServerAgent as NetLayerLib from ea.libs.NetLayerLib import Messages as Messages from ea.libs.NetLayerLib import FifoCallBack as FifoCallBack from ea.serverinterfaces import EventServerInterface as ESI from ea.serverinterfaces import AgentServerInterface as ASI from ea.libs import Logger, Settings class TestServerInterface(Logger.ClassLogger, NetLayerLib.ServerAgent): def __init__(self, listeningAddress, agentName='TSI', context=None): """ Constructs TCP Server Inferface @param listeningAddress: @type listeningAddress: """ NetLayerLib.ServerAgent.__init__(self, listeningAddress=listeningAddress, agentName=agentName, keepAliveInterval=Settings.getInt( 'Network', 'keepalive-interval'), inactivityTimeout=Settings.getInt( 'Network', 'inactivity-timeout'), responseTimeout=Settings.getInt( 'Network', 'response-timeout'), selectTimeout=Settings.get( 'Network', 'select-timeout'), pickleVer=Settings.getInt( 'Network', 'pickle-version') ) self.context = context self.__mutex__ = threading.RLock() self.__fifoThread = None self.tests = {} # {'task-id': Boolean} # test register, with background running or not self.testsConnected = {} # all tests connected def startFifo(self): """ Start the fifo """ self.__fifoThread = FifoCallBack.FifoCallbackThread() self.__fifoThread.start() self.trace("TSI: fifo started.") def stopFifo(self): """ Stop the fifo """ self.__fifoThread.stop() self.__fifoThread.join() self.trace("TSI: fifo stopped.") def registerTest(self, id, background): """ Register the test on the server @param id: @type id: @param background: @type background: boolean """ try: self.tests[str(id)] = bool(background) self.trace( 'Test=%s registered, running in Background=%s' % (id, background)) except Exception as e: self.error(err=e) return False return True def onConnection(self, client): """ Called on connection of the test @param client: @type client: """ NetLayerLib.ServerAgent.onConnection(self, client) self.testsConnected[client.client_address] = {'connected-at': time.time(), 'probes': [], 'agents': []} self.trace('test is starting: %s' % str(client.client_address)) def onDisconnection(self, client): """ Called on disconnection of test @param client: @type client: """ NetLayerLib.ServerAgent.onDisconnection(self, client) self.trace('test is endding: %s' % str(client.client_address)) def resetRunningAgent(self, client): """ Reset all running agents used by the client passed as argument @param client: @type client: """ self.trace('Trying to cleanup active agents') for p in client['agents']: # we can reset only agent in ready state (ready message received) if 'agent-name' in p: agent = ASI.instance().getAgent(aname=p['agent-name']) if agent is not None: self.trace('Reset Agent=%s for Script=%s and Adapter=%s' % (p['agent-name'], p['script-id'], p['source-adapter'])) data = {'event': 'agent-reset', 'script_id': p['script-id'], 'source-adapter': p['source-adapter'], 'uuid': p['uuid']} ASI.instance().notify(client=agent['address'], data=data) def onRequest(self, client, tid, request): """ Reimplemented from ServerAgent Called on incoming request @param client: @type client: @param tid: @type tid: @param request: @type request: """ self.__mutex__.acquire() try: _body_ = request['body'] if client not in self.testsConnected: self.__mutex__.release() return self.testsConnected[client]['task-id'] = _body_['task-id'] # handle notify and save some statistics on the database if request['cmd'] == Messages.RSQ_NOTIFY: try: if _body_['event'] in ['agent-data', 'agent-notify', 'agent-init', 'agent-reset', 'agent-alive', 'agent-ready']: if _body_['event'] == 'agent-ready': self.testsConnected[client]['agents'].append( { 'agent-name': _body_['destination-agent'], 'script-id': _body_['script_id'], 'uuid': _body_['uuid'], 'source-adapter': _body_['source-adapter'] } ) ASI.instance().notifyAgent(client, tid, data=_body_) except Exception as e: self.error('unable to handle notify for agent: %s' % e) if _body_['event'] == 'testcase-stopped': # reset agents self.resetRunningAgent(client=self.testsConnected[client]) if _body_['task-id'] in self.tests: if not self.tests[_body_['task-id']]: # check connected time of the associated user and test # if connected-at of the user > connected-at of the test # then not necessary to send events userFounded = self.context.getUser( login=_body_['from']) if userFounded is not None: if client not in self.testsConnected: self.error( 'unknown test from %s' % str(client)) else: if userFounded['connected-at'] < self.testsConnected[client]['connected-at']: if _body_['channel-id']: ESI.instance().notify(body=('event', _body_), toAddress=_body_['channel-id']) else: ESI.instance().notify(body=('event', _body_)) else: self.error('test unknown: %s' % _body_['task-id']) if _body_['event'] == 'script-stopped': # reset agents self.resetRunningAgent(client=self.testsConnected[client]) if _body_['task-id'] in self.tests: self.tests.pop(_body_['task-id']) else: self.error('task-id unknown: %s' % _body_['task-id']) if client in self.testsConnected: self.testsConnected.pop(client) else: self.error('test unknown: %s' % str(client)) # handle requests elif request['cmd'] == Messages.RSQ_CMD: self.trace("cmd received: %s" % _body_['cmd']) if 'cmd' in _body_: # handle interact command if _body_['cmd'] == Messages.CMD_INTERACT: self.trace('interact called') if _body_['task-id'] in self.tests: if not self.tests[_body_['task-id']]: # check connected time of the associated user and test # if connected-at of the user > connected-at of # the test then not necessary to send events userFounded = self.context.getUser( login=_body_['from']) if userFounded is not None: if client not in self.testsConnected: self.error( 'unknown test from %s' % str(client)) else: if userFounded['connected-at'] < self.testsConnected[client]['connected-at']: self.__fifoThread.putItem(lambda: self.onInteract(client, tid, bodyReq=_body_, timeout=_body_['timeout'])) else: self.error('test unknown: %s' % _body_['task-id']) else: self.error('cmd unknown %s' % _body_['cmd']) rsp = {'cmd': _body_['cmd'], 'res': Messages.CMD_ERROR} NetLayerLib.ServerAgent.failed( self, client, tid, body=rsp) else: self.error('cmd is missing') # handle other request else: self.trace('%s received ' % request['cmd']) except Exception as e: self.error("unable to handle incoming request: %s" % e) self.__mutex__.release() def onInteract(self, client, tid, bodyReq, timeout=0.0): """ Called on interact """ inter = Interact(client, tid, bodyReq, timeout=timeout) testThread = threading.Thread(target=lambda: inter.run()) testThread.start() def trace(self, txt): """ Trace message """ if Settings.instance() is not None: if Settings.get('Trace', 'debug-level') == 'VERBOSE': Logger.ClassLogger.trace(self, txt=txt) class Interact(object): def __init__(self, client, tid, bodyReq, timeout=0.0): """ Interact object, not blocking """ self.client = client self.tid = tid self.bodyReq = bodyReq self.timeout = timeout def run(self): """ On run """ rsp = ESI.instance().interact(body=self.bodyReq, timeout=self.timeout) _data_ = {'cmd': Messages.CMD_INTERACT} if rsp is None: _data_['rsp'] = None else: _data_['rsp'] = rsp['body'] instance().ok(self.client, self.tid, body=_data_) TSI = None def instance(): """ Returns the singleton @return: @rtype: """ return TSI def initialize(listeningAddress, context): """ Instance creation @param listeningAddress: @type listeningAddress: """ global TSI TSI = TestServerInterface(listeningAddress=listeningAddress, context=context) TSI.startFifo() def finalize(): """ Destruction of the singleton """ global TSI if TSI: TSI.stopFifo() TSI.stopSA() TSI = None
dmachard/extensive-testing
src/ea/serverinterfaces/TestServerInterface.py
Python
lgpl-2.1
13,189
/* * driver-hypervisor.h: entry points for hypervisor drivers * * Copyright (C) 2006-2015 Red Hat, Inc. * * This library 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 library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. */ #ifndef __VIR_DRIVER_HYPERVISOR_H__ # define __VIR_DRIVER_HYPERVISOR_H__ # ifndef __VIR_DRIVER_H_INCLUDES___ # error "Don't include this file directly, only use driver.h" # endif typedef virDrvOpenStatus (*virDrvConnectOpen)(virConnectPtr conn, virConnectAuthPtr auth, virConfPtr conf, unsigned int flags); typedef int (*virDrvConnectClose)(virConnectPtr conn); typedef int (*virDrvConnectSupportsFeature)(virConnectPtr conn, int feature); typedef const char * (*virDrvConnectGetType)(virConnectPtr conn); typedef int (*virDrvConnectGetVersion)(virConnectPtr conn, unsigned long *hvVer); typedef int (*virDrvConnectGetLibVersion)(virConnectPtr conn, unsigned long *libVer); typedef char * (*virDrvConnectGetHostname)(virConnectPtr conn); typedef char * (*virDrvConnectGetURI)(virConnectPtr conn); typedef char * (*virDrvConnectGetSysinfo)(virConnectPtr conn, unsigned int flags); typedef int (*virDrvConnectGetMaxVcpus)(virConnectPtr conn, const char *type); typedef int (*virDrvNodeGetInfo)(virConnectPtr conn, virNodeInfoPtr info); typedef char * (*virDrvConnectGetCapabilities)(virConnectPtr conn); typedef char * (*virDrvConnectGetDomainCapabilities)(virConnectPtr conn, const char *emulatorbin, const char *arch, const char *machine, const char *virttype, unsigned int flags); typedef int (*virDrvConnectListDomains)(virConnectPtr conn, int *ids, int maxids); typedef int (*virDrvConnectNumOfDomains)(virConnectPtr conn); typedef virDomainPtr (*virDrvDomainCreateXML)(virConnectPtr conn, const char *xmlDesc, unsigned int flags); typedef virDomainPtr (*virDrvDomainCreateXMLWithFiles)(virConnectPtr conn, const char *xmlDesc, unsigned int nfiles, int *files, unsigned int flags); typedef virDomainPtr (*virDrvDomainLookupByID)(virConnectPtr conn, int id); typedef virDomainPtr (*virDrvDomainLookupByUUID)(virConnectPtr conn, const unsigned char *uuid); typedef virDomainPtr (*virDrvDomainLookupByName)(virConnectPtr conn, const char *name); typedef int (*virDrvDomainSuspend)(virDomainPtr domain); typedef int (*virDrvDomainResume)(virDomainPtr domain); typedef int (*virDrvDomainPMSuspendForDuration)(virDomainPtr, unsigned int target, unsigned long long duration, unsigned int flags); typedef int (*virDrvDomainPMWakeup)(virDomainPtr domain, unsigned int flags); typedef int (*virDrvDomainShutdown)(virDomainPtr domain); typedef int (*virDrvDomainReboot)(virDomainPtr domain, unsigned int flags); typedef int (*virDrvDomainReset)(virDomainPtr domain, unsigned int flags); typedef int (*virDrvDomainDestroy)(virDomainPtr domain); typedef int (*virDrvDomainDestroyFlags)(virDomainPtr domain, unsigned int flags); typedef char * (*virDrvDomainGetOSType)(virDomainPtr domain); typedef char * (*virDrvDomainGetHostname)(virDomainPtr domain, unsigned int flags); typedef unsigned long long (*virDrvDomainGetMaxMemory)(virDomainPtr domain); typedef int (*virDrvDomainSetMaxMemory)(virDomainPtr domain, unsigned long memory); typedef int (*virDrvDomainSetMemory)(virDomainPtr domain, unsigned long memory); typedef int (*virDrvDomainSetMemoryFlags)(virDomainPtr domain, unsigned long memory, unsigned int flags); typedef int (*virDrvDomainSetMemoryStatsPeriod)(virDomainPtr domain, int period, unsigned int flags); typedef int (*virDrvDomainSetMemoryParameters)(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags); typedef int (*virDrvDomainGetMemoryParameters)(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags); typedef int (*virDrvDomainSetNumaParameters)(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags); typedef int (*virDrvDomainGetNumaParameters)(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags); typedef int (*virDrvDomainSetBlkioParameters)(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags); typedef int (*virDrvDomainGetBlkioParameters)(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags); typedef int (*virDrvDomainGetInfo)(virDomainPtr domain, virDomainInfoPtr info); typedef int (*virDrvDomainGetState)(virDomainPtr domain, int *state, int *reason, unsigned int flags); typedef int (*virDrvDomainGetControlInfo)(virDomainPtr domain, virDomainControlInfoPtr info, unsigned int flags); typedef int (*virDrvDomainSave)(virDomainPtr domain, const char *to); typedef int (*virDrvDomainSaveFlags)(virDomainPtr domain, const char *to, const char *dxml, unsigned int flags); typedef int (*virDrvDomainRestore)(virConnectPtr conn, const char *from); typedef int (*virDrvDomainRestoreFlags)(virConnectPtr conn, const char *from, const char *dxml, unsigned int flags); typedef char * (*virDrvDomainSaveImageGetXMLDesc)(virConnectPtr conn, const char *file, unsigned int flags); typedef int (*virDrvDomainSaveImageDefineXML)(virConnectPtr conn, const char *file, const char *dxml, unsigned int flags); typedef int (*virDrvDomainCoreDump)(virDomainPtr domain, const char *to, unsigned int flags); typedef int (*virDrvDomainCoreDumpWithFormat)(virDomainPtr domain, const char *to, unsigned int dumpformat, unsigned int flags); typedef char * (*virDrvDomainScreenshot)(virDomainPtr domain, virStreamPtr stream, unsigned int screen, unsigned int flags); typedef char * (*virDrvDomainGetXMLDesc)(virDomainPtr dom, unsigned int flags); typedef char * (*virDrvConnectDomainXMLFromNative)(virConnectPtr conn, const char *nativeFormat, const char *nativeConfig, unsigned int flags); typedef char * (*virDrvConnectDomainXMLToNative)(virConnectPtr conn, const char *nativeFormat, const char *domainXml, unsigned int flags); typedef int (*virDrvConnectListDefinedDomains)(virConnectPtr conn, char **const names, int maxnames); typedef int (*virDrvConnectListAllDomains)(virConnectPtr conn, virDomainPtr **domains, unsigned int flags); typedef int (*virDrvConnectNumOfDefinedDomains)(virConnectPtr conn); typedef int (*virDrvDomainCreate)(virDomainPtr dom); typedef int (*virDrvDomainCreateWithFlags)(virDomainPtr dom, unsigned int flags); typedef int (*virDrvDomainCreateWithFiles)(virDomainPtr dom, unsigned int nfiles, int *files, unsigned int flags); typedef virDomainPtr (*virDrvDomainDefineXML)(virConnectPtr conn, const char *xml); typedef virDomainPtr (*virDrvDomainDefineXMLFlags)(virConnectPtr conn, const char *xml, unsigned int flags); typedef int (*virDrvDomainUndefine)(virDomainPtr dom); typedef int (*virDrvDomainUndefineFlags)(virDomainPtr dom, unsigned int flags); typedef int (*virDrvDomainSetVcpus)(virDomainPtr domain, unsigned int nvcpus); typedef int (*virDrvDomainSetVcpusFlags)(virDomainPtr domain, unsigned int nvcpus, unsigned int flags); typedef int (*virDrvDomainGetVcpusFlags)(virDomainPtr domain, unsigned int flags); typedef int (*virDrvDomainPinVcpu)(virDomainPtr domain, unsigned int vcpu, unsigned char *cpumap, int maplen); typedef int (*virDrvDomainPinVcpuFlags)(virDomainPtr domain, unsigned int vcpu, unsigned char *cpumap, int maplen, unsigned int flags); typedef int (*virDrvDomainGetVcpuPinInfo)(virDomainPtr domain, int ncpumaps, unsigned char *cpumaps, int maplen, unsigned int flags); typedef int (*virDrvDomainPinEmulator)(virDomainPtr domain, unsigned char *cpumap, int maplen, unsigned int flags); typedef int (*virDrvDomainGetEmulatorPinInfo)(virDomainPtr domain, unsigned char *cpumaps, int maplen, unsigned int flags); typedef int (*virDrvDomainGetVcpus)(virDomainPtr domain, virVcpuInfoPtr info, int maxinfo, unsigned char *cpumaps, int maplen); typedef int (*virDrvDomainGetMaxVcpus)(virDomainPtr domain); typedef int (*virDrvDomainGetIOThreadInfo)(virDomainPtr domain, virDomainIOThreadInfoPtr **info, unsigned int flags); typedef int (*virDrvDomainPinIOThread)(virDomainPtr domain, unsigned int iothread_id, unsigned char *cpumap, int maplen, unsigned int flags); typedef int (*virDrvDomainAddIOThread)(virDomainPtr domain, unsigned int iothread_id, unsigned int flags); typedef int (*virDrvDomainDelIOThread)(virDomainPtr domain, unsigned int iothread_id, unsigned int flags); typedef int (*virDrvDomainGetSecurityLabel)(virDomainPtr domain, virSecurityLabelPtr seclabel); typedef int (*virDrvDomainGetSecurityLabelList)(virDomainPtr domain, virSecurityLabelPtr* seclabels); typedef int (*virDrvNodeGetSecurityModel)(virConnectPtr conn, virSecurityModelPtr secmodel); typedef int (*virDrvDomainAttachDevice)(virDomainPtr domain, const char *xml); typedef int (*virDrvDomainAttachDeviceFlags)(virDomainPtr domain, const char *xml, unsigned int flags); typedef int (*virDrvDomainDetachDevice)(virDomainPtr domain, const char *xml); typedef int (*virDrvDomainDetachDeviceFlags)(virDomainPtr domain, const char *xml, unsigned int flags); typedef int (*virDrvDomainUpdateDeviceFlags)(virDomainPtr domain, const char *xml, unsigned int flags); typedef int (*virDrvDomainGetAutostart)(virDomainPtr domain, int *autostart); typedef int (*virDrvDomainSetAutostart)(virDomainPtr domain, int autostart); typedef char * (*virDrvDomainGetSchedulerType)(virDomainPtr domain, int *nparams); typedef int (*virDrvDomainGetSchedulerParameters)(virDomainPtr domain, virTypedParameterPtr params, int *nparams); typedef int (*virDrvDomainGetSchedulerParametersFlags)(virDomainPtr domain, virTypedParameterPtr params, int *nparams, unsigned int flags); typedef int (*virDrvDomainSetSchedulerParameters)(virDomainPtr domain, virTypedParameterPtr params, int nparams); typedef int (*virDrvDomainSetSchedulerParametersFlags)(virDomainPtr domain, virTypedParameterPtr params, int nparams, unsigned int flags); typedef int (*virDrvDomainBlockStats)(virDomainPtr domain, const char *path, virDomainBlockStatsPtr stats); typedef int (*virDrvDomainBlockStatsFlags)(virDomainPtr domain, const char *path, virTypedParameterPtr params, int *nparams, unsigned int flags); typedef int (*virDrvDomainInterfaceStats)(virDomainPtr domain, const char *path, virDomainInterfaceStatsPtr stats); typedef int (*virDrvDomainSetInterfaceParameters)(virDomainPtr dom, const char *device, virTypedParameterPtr params, int nparams, unsigned int flags); typedef int (*virDrvDomainGetInterfaceParameters)(virDomainPtr dom, const char *device, virTypedParameterPtr params, int *nparams, unsigned int flags); typedef int (*virDrvDomainMemoryStats)(virDomainPtr domain, virDomainMemoryStatPtr stats, unsigned int nr_stats, unsigned int flags); typedef int (*virDrvDomainBlockPeek)(virDomainPtr domain, const char *path, unsigned long long offset, size_t size, void *buffer, unsigned int flags); typedef int (*virDrvDomainBlockResize)(virDomainPtr domain, const char *path, unsigned long long size, unsigned int flags); typedef int (*virDrvDomainMemoryPeek)(virDomainPtr domain, unsigned long long start, size_t size, void *buffer, unsigned int flags); typedef int (*virDrvDomainGetBlockInfo)(virDomainPtr domain, const char *path, virDomainBlockInfoPtr info, unsigned int flags); typedef int (*virDrvDomainMigratePrepare)(virConnectPtr dconn, char **cookie, int *cookielen, const char *uri_in, char **uri_out, unsigned long flags, const char *dname, unsigned long resource); typedef int (*virDrvDomainMigratePerform)(virDomainPtr domain, const char *cookie, int cookielen, const char *uri, unsigned long flags, const char *dname, unsigned long resource); typedef virDomainPtr (*virDrvDomainMigrateFinish)(virConnectPtr dconn, const char *dname, const char *cookie, int cookielen, const char *uri, unsigned long flags); typedef int (*virDrvNodeGetCPUStats)(virConnectPtr conn, int cpuNum, virNodeCPUStatsPtr params, int *nparams, unsigned int flags); typedef int (*virDrvNodeGetMemoryStats)(virConnectPtr conn, int cellNum, virNodeMemoryStatsPtr params, int *nparams, unsigned int flags); typedef int (*virDrvNodeGetCacheStats)(virConnectPtr conn, virNodeCacheStatsPtr params, int *nparams, unsigned int flags); typedef int (*virDrvNodeGetCellsFreeMemory)(virConnectPtr conn, unsigned long long *freeMems, int startCell, int maxCells); typedef unsigned long long (*virDrvNodeGetFreeMemory)(virConnectPtr conn); typedef int (*virDrvConnectDomainEventRegister)(virConnectPtr conn, virConnectDomainEventCallback cb, void *opaque, virFreeCallback freecb); typedef int (*virDrvConnectDomainEventDeregister)(virConnectPtr conn, virConnectDomainEventCallback cb); typedef int (*virDrvDomainMigratePrepare2)(virConnectPtr dconn, char **cookie, int *cookielen, const char *uri_in, char **uri_out, unsigned long flags, const char *dname, unsigned long resource, const char *dom_xml); typedef virDomainPtr (*virDrvDomainMigrateFinish2)(virConnectPtr dconn, const char *dname, const char *cookie, int cookielen, const char *uri, unsigned long flags, int retcode); typedef int (*virDrvNodeDeviceDettach)(virNodeDevicePtr dev); typedef int (*virDrvNodeDeviceDetachFlags)(virNodeDevicePtr dev, const char *driverName, unsigned int flags); typedef int (*virDrvNodeDeviceReAttach)(virNodeDevicePtr dev); typedef int (*virDrvNodeDeviceReset)(virNodeDevicePtr dev); typedef int (*virDrvDomainMigratePrepareTunnel)(virConnectPtr dconn, virStreamPtr st, unsigned long flags, const char *dname, unsigned long resource, const char *dom_xml); typedef int (*virDrvDomainMigrateStartPostCopy)(virDomainPtr domain, unsigned int flags); typedef int (*virDrvConnectIsEncrypted)(virConnectPtr conn); typedef int (*virDrvConnectIsSecure)(virConnectPtr conn); typedef int (*virDrvConnectIsAlive)(virConnectPtr conn); typedef int (*virDrvDomainIsActive)(virDomainPtr dom); typedef int (*virDrvDomainRename)(virDomainPtr dom, const char *new_name, unsigned int flags); typedef int (*virDrvDomainIsPersistent)(virDomainPtr dom); typedef int (*virDrvDomainIsUpdated)(virDomainPtr dom); typedef int (*virDrvConnectCompareCPU)(virConnectPtr conn, const char *cpu, unsigned int flags); typedef char * (*virDrvConnectBaselineCPU)(virConnectPtr conn, const char **xmlCPUs, unsigned int ncpus, unsigned int flags); typedef int (*virDrvConnectGetCPUModelNames)(virConnectPtr conn, const char *archName, char ***models, unsigned int flags); typedef int (*virDrvDomainGetJobInfo)(virDomainPtr domain, virDomainJobInfoPtr info); typedef int (*virDrvDomainGetJobStats)(virDomainPtr domain, int *type, virTypedParameterPtr *params, int *nparams, unsigned int flags); typedef int (*virDrvDomainAbortJob)(virDomainPtr domain); typedef int (*virDrvDomainMigrateSetMaxDowntime)(virDomainPtr domain, unsigned long long downtime, unsigned int flags); typedef int (*virDrvDomainMigrateGetCompressionCache)(virDomainPtr domain, unsigned long long *cacheSize, unsigned int flags); typedef int (*virDrvDomainMigrateSetCompressionCache)(virDomainPtr domain, unsigned long long cacheSize, unsigned int flags); typedef int (*virDrvDomainMigrateSetMaxSpeed)(virDomainPtr domain, unsigned long bandwidth, unsigned int flags); typedef int (*virDrvDomainMigrateGetMaxSpeed)(virDomainPtr domain, unsigned long *bandwidth, unsigned int flags); typedef int (*virDrvConnectDomainEventRegisterAny)(virConnectPtr conn, virDomainPtr dom, int eventID, virConnectDomainEventGenericCallback cb, void *opaque, virFreeCallback freecb); typedef int (*virDrvConnectDomainEventDeregisterAny)(virConnectPtr conn, int callbackID); typedef int (*virDrvDomainManagedSave)(virDomainPtr domain, unsigned int flags); typedef int (*virDrvDomainHasManagedSaveImage)(virDomainPtr domain, unsigned int flags); typedef int (*virDrvDomainManagedSaveRemove)(virDomainPtr domain, unsigned int flags); typedef virDomainSnapshotPtr (*virDrvDomainSnapshotCreateXML)(virDomainPtr domain, const char *xmlDesc, unsigned int flags); typedef char * (*virDrvDomainSnapshotGetXMLDesc)(virDomainSnapshotPtr snapshot, unsigned int flags); typedef int (*virDrvDomainSnapshotNum)(virDomainPtr domain, unsigned int flags); typedef int (*virDrvDomainSnapshotListNames)(virDomainPtr domain, char **names, int nameslen, unsigned int flags); typedef int (*virDrvDomainListAllSnapshots)(virDomainPtr domain, virDomainSnapshotPtr **snaps, unsigned int flags); typedef int (*virDrvDomainSnapshotNumChildren)(virDomainSnapshotPtr snapshot, unsigned int flags); typedef int (*virDrvDomainSnapshotListChildrenNames)(virDomainSnapshotPtr snapshot, char **names, int nameslen, unsigned int flags); typedef int (*virDrvDomainSnapshotListAllChildren)(virDomainSnapshotPtr snapshot, virDomainSnapshotPtr **snaps, unsigned int flags); typedef virDomainSnapshotPtr (*virDrvDomainSnapshotLookupByName)(virDomainPtr domain, const char *name, unsigned int flags); typedef int (*virDrvDomainHasCurrentSnapshot)(virDomainPtr domain, unsigned int flags); typedef virDomainSnapshotPtr (*virDrvDomainSnapshotGetParent)(virDomainSnapshotPtr snapshot, unsigned int flags); typedef virDomainSnapshotPtr (*virDrvDomainSnapshotCurrent)(virDomainPtr domain, unsigned int flags); typedef int (*virDrvDomainSnapshotIsCurrent)(virDomainSnapshotPtr snapshot, unsigned int flags); typedef int (*virDrvDomainSnapshotHasMetadata)(virDomainSnapshotPtr snapshot, unsigned int flags); typedef int (*virDrvDomainRevertToSnapshot)(virDomainSnapshotPtr snapshot, unsigned int flags); typedef int (*virDrvDomainSnapshotDelete)(virDomainSnapshotPtr snapshot, unsigned int flags); typedef int (*virDrvDomainQemuMonitorCommand)(virDomainPtr domain, const char *cmd, char **result, unsigned int flags); typedef char * (*virDrvDomainQemuAgentCommand)(virDomainPtr domain, const char *cmd, int timeout, unsigned int flags); /* Choice of unsigned int rather than pid_t is intentional. */ typedef virDomainPtr (*virDrvDomainQemuAttach)(virConnectPtr conn, unsigned int pid_value, unsigned int flags); typedef int (*virDrvConnectDomainQemuMonitorEventRegister)(virConnectPtr conn, virDomainPtr dom, const char *event, virConnectDomainQemuMonitorEventCallback cb, void *opaque, virFreeCallback freecb, unsigned int flags); typedef int (*virDrvConnectDomainQemuMonitorEventDeregister)(virConnectPtr conn, int callbackID); typedef int (*virDrvDomainOpenConsole)(virDomainPtr dom, const char *dev_name, virStreamPtr st, unsigned int flags); typedef int (*virDrvDomainOpenChannel)(virDomainPtr dom, const char *name, virStreamPtr st, unsigned int flags); typedef int (*virDrvDomainOpenGraphics)(virDomainPtr dom, unsigned int idx, int fd, unsigned int flags); typedef int (*virDrvDomainOpenGraphicsFD)(virDomainPtr dom, unsigned int idx, unsigned int flags); typedef int (*virDrvDomainInjectNMI)(virDomainPtr dom, unsigned int flags); typedef int (*virDrvDomainSendKey)(virDomainPtr dom, unsigned int codeset, unsigned int holdtime, unsigned int *keycodes, int nkeycodes, unsigned int flags); typedef int (*virDrvDomainSendProcessSignal)(virDomainPtr dom, long long pid_value, unsigned int signum, unsigned int flags); typedef char * (*virDrvDomainMigrateBegin3)(virDomainPtr domain, const char *xmlin, char **cookieout, int *cookieoutlen, unsigned long flags, const char *dname, unsigned long resource); typedef int (*virDrvDomainMigratePrepare3)(virConnectPtr dconn, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, const char *uri_in, char **uri_out, unsigned long flags, const char *dname, unsigned long resource, const char *dom_xml); typedef int (*virDrvDomainMigratePrepareTunnel3)(virConnectPtr dconn, virStreamPtr st, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned long flags, const char *dname, unsigned long resource, const char *dom_xml); typedef int (*virDrvDomainMigratePerform3)(virDomainPtr dom, const char *xmlin, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, const char *dconnuri, const char *uri, unsigned long flags, const char *dname, unsigned long resource); typedef virDomainPtr (*virDrvDomainMigrateFinish3)(virConnectPtr dconn, const char *dname, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, const char *dconnuri, const char *uri, unsigned long flags, int cancelled); typedef int (*virDrvDomainMigrateConfirm3)(virDomainPtr domain, const char *cookiein, int cookieinlen, unsigned long flags, int cancelled); typedef int (*virDrvNodeSuspendForDuration)(virConnectPtr conn, unsigned int target, unsigned long long duration, unsigned int flags); typedef int (*virDrvDomainGetPerfEvents)(virDomainPtr dom, virTypedParameterPtr *params, int *nparams, unsigned int flags); typedef int (*virDrvDomainSetPerfEvents)(virDomainPtr dom, virTypedParameterPtr params, int nparams, unsigned int flags); typedef int (*virDrvDomainBlockJobAbort)(virDomainPtr dom, const char *path, unsigned int flags); typedef int (*virDrvDomainGetBlockJobInfo)(virDomainPtr dom, const char *path, virDomainBlockJobInfoPtr info, unsigned int flags); typedef int (*virDrvDomainBlockJobSetSpeed)(virDomainPtr dom, const char *path, unsigned long bandwidth, unsigned int flags); typedef int (*virDrvDomainBlockPull)(virDomainPtr dom, const char *path, unsigned long bandwidth, unsigned int flags); typedef int (*virDrvDomainBlockRebase)(virDomainPtr dom, const char *path, const char *base, unsigned long bandwidth, unsigned int flags); typedef int (*virDrvDomainBlockCopy)(virDomainPtr dom, const char *path, const char *destxml, virTypedParameterPtr params, int nparams, unsigned int flags); typedef int (*virDrvDomainBlockCommit)(virDomainPtr dom, const char *disk, const char *base, const char *top, unsigned long bandwidth, unsigned int flags); typedef int (*virDrvConnectSetKeepAlive)(virConnectPtr conn, int interval, unsigned int count); typedef int (*virDrvDomainSetBlockIoTune)(virDomainPtr dom, const char *disk, virTypedParameterPtr params, int nparams, unsigned int flags); typedef int (*virDrvDomainGetBlockIoTune)(virDomainPtr dom, const char *disk, virTypedParameterPtr params, int *nparams, unsigned int flags); typedef int (*virDrvDomainShutdownFlags)(virDomainPtr domain, unsigned int flags); typedef int (*virDrvDomainGetCPUStats)(virDomainPtr domain, virTypedParameterPtr params, unsigned int nparams, int start_cpu, unsigned int ncpus, unsigned int flags); typedef int (*virDrvDomainGetDiskErrors)(virDomainPtr dom, virDomainDiskErrorPtr errors, unsigned int maxerrors, unsigned int flags); typedef int (*virDrvDomainSetMetadata)(virDomainPtr dom, int type, const char *metadata, const char *key, const char *uri, unsigned int flags); typedef char * (*virDrvDomainGetMetadata)(virDomainPtr dom, int type, const char *uri, unsigned int flags); typedef int (*virDrvNodeGetMemoryParameters)(virConnectPtr conn, virTypedParameterPtr params, int *nparams, unsigned int flags); typedef int (*virDrvNodeSetMemoryParameters)(virConnectPtr conn, virTypedParameterPtr params, int nparams, unsigned int flags); typedef int (*virDrvNodeGetCPUMap)(virConnectPtr conn, unsigned char **cpumap, unsigned int *online, unsigned int flags); typedef int (*virDrvDomainFSTrim)(virDomainPtr dom, const char *mountPoint, unsigned long long minimum, unsigned int flags); typedef int (*virDrvDomainGetTime)(virDomainPtr dom, long long *seconds, unsigned int *nseconds, unsigned int flags); typedef int (*virDrvDomainSetTime)(virDomainPtr dom, long long seconds, unsigned int nseconds, unsigned int flags); typedef int (*virDrvDomainLxcOpenNamespace)(virDomainPtr dom, int **fdlist, unsigned int flags); typedef char * (*virDrvDomainMigrateBegin3Params)(virDomainPtr domain, virTypedParameterPtr params, int nparams, char **cookieout, int *cookieoutlen, unsigned int flags); typedef int (*virDrvDomainMigratePrepare3Params)(virConnectPtr dconn, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, char **uri_out, unsigned int flags); typedef int (*virDrvDomainMigratePrepareTunnel3Params)(virConnectPtr dconn, virStreamPtr st, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned int flags); typedef int (*virDrvDomainMigratePerform3Params)(virDomainPtr dom, const char *dconnuri, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned int flags); typedef virDomainPtr (*virDrvDomainMigrateFinish3Params)(virConnectPtr dconn, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, char **cookieout, int *cookieoutlen, unsigned int flags, int cancelled); typedef int (*virDrvDomainMigrateConfirm3Params)(virDomainPtr domain, virTypedParameterPtr params, int nparams, const char *cookiein, int cookieinlen, unsigned int flags, int cancelled); typedef int (*virDrvDomainFSFreeze)(virDomainPtr dom, const char **mountpoints, unsigned int nmountpoints, unsigned int flags); typedef int (*virDrvDomainFSThaw)(virDomainPtr dom, const char **mountpoints, unsigned int nmountpoints, unsigned int flags); typedef int (*virDrvDomainGetFSInfo)(virDomainPtr dom, virDomainFSInfoPtr **info, unsigned int flags); typedef int (*virDrvNodeGetFreePages)(virConnectPtr conn, unsigned int npages, unsigned int *pages, int startCell, unsigned int cellCount, unsigned long long *counts, unsigned int flags); typedef int (*virDrvConnectGetAllDomainStats)(virConnectPtr conn, virDomainPtr *doms, unsigned int ndoms, unsigned int stats, virDomainStatsRecordPtr **retStats, unsigned int flags); typedef int (*virDrvNodeAllocPages)(virConnectPtr conn, unsigned int npages, unsigned int *pageSizes, unsigned long long *pageCounts, int startCell, unsigned int cellCount, unsigned int flags); typedef int (*virDrvDomainInterfaceAddresses)(virDomainPtr dom, virDomainInterfacePtr **ifaces, unsigned int source, unsigned int flags); typedef int (*virDrvDomainSetUserPassword)(virDomainPtr dom, const char *user, const char *password, unsigned int flags); typedef int (*virDrvConnectRegisterCloseCallback)(virConnectPtr conn, virConnectCloseFunc cb, void *opaque, virFreeCallback freecb); typedef int (*virDrvConnectUnregisterCloseCallback)(virConnectPtr conn, virConnectCloseFunc cb); typedef int (*virDrvDomainGetGuestVcpus)(virDomainPtr domain, virTypedParameterPtr *params, unsigned int *nparams, unsigned int flags); typedef int (*virDrvDomainSetGuestVcpus)(virDomainPtr domain, const char *cpumap, int state, unsigned int flags); typedef int (*virDrvDomainSetVcpu)(virDomainPtr domain, const char *cpumap, int state, unsigned int flags); typedef struct _virHypervisorDriver virHypervisorDriver; typedef virHypervisorDriver *virHypervisorDriverPtr; /** * _virHypervisorDriver: * * Structure associated to a virtualization driver, defining the various * entry points for it. * * All drivers must support the following fields/methods: * - name * - open * - close */ struct _virHypervisorDriver { const char *name; /* the name of the driver */ virDrvConnectOpen connectOpen; virDrvConnectClose connectClose; virDrvConnectSupportsFeature connectSupportsFeature; virDrvConnectGetType connectGetType; virDrvConnectGetVersion connectGetVersion; virDrvConnectGetLibVersion connectGetLibVersion; virDrvConnectGetHostname connectGetHostname; virDrvConnectGetSysinfo connectGetSysinfo; virDrvConnectGetMaxVcpus connectGetMaxVcpus; virDrvNodeGetInfo nodeGetInfo; virDrvConnectGetCapabilities connectGetCapabilities; virDrvConnectListDomains connectListDomains; virDrvConnectNumOfDomains connectNumOfDomains; virDrvConnectListAllDomains connectListAllDomains; virDrvDomainCreateXML domainCreateXML; virDrvDomainCreateXMLWithFiles domainCreateXMLWithFiles; virDrvDomainLookupByID domainLookupByID; virDrvDomainLookupByUUID domainLookupByUUID; virDrvDomainLookupByName domainLookupByName; virDrvDomainSuspend domainSuspend; virDrvDomainResume domainResume; virDrvDomainPMSuspendForDuration domainPMSuspendForDuration; virDrvDomainPMWakeup domainPMWakeup; virDrvDomainShutdown domainShutdown; virDrvDomainShutdownFlags domainShutdownFlags; virDrvDomainReboot domainReboot; virDrvDomainReset domainReset; virDrvDomainDestroy domainDestroy; virDrvDomainDestroyFlags domainDestroyFlags; virDrvDomainGetOSType domainGetOSType; virDrvDomainGetHostname domainGetHostname; virDrvDomainGetMaxMemory domainGetMaxMemory; virDrvDomainSetMaxMemory domainSetMaxMemory; virDrvDomainSetMemory domainSetMemory; virDrvDomainSetMemoryFlags domainSetMemoryFlags; virDrvDomainSetMemoryStatsPeriod domainSetMemoryStatsPeriod; virDrvDomainSetMemoryParameters domainSetMemoryParameters; virDrvDomainGetMemoryParameters domainGetMemoryParameters; virDrvDomainSetNumaParameters domainSetNumaParameters; virDrvDomainGetNumaParameters domainGetNumaParameters; virDrvDomainSetBlkioParameters domainSetBlkioParameters; virDrvDomainGetBlkioParameters domainGetBlkioParameters; virDrvDomainGetInfo domainGetInfo; virDrvDomainGetState domainGetState; virDrvDomainGetControlInfo domainGetControlInfo; virDrvDomainSave domainSave; virDrvDomainSaveFlags domainSaveFlags; virDrvDomainRestore domainRestore; virDrvDomainRestoreFlags domainRestoreFlags; virDrvDomainSaveImageGetXMLDesc domainSaveImageGetXMLDesc; virDrvDomainSaveImageDefineXML domainSaveImageDefineXML; virDrvDomainCoreDump domainCoreDump; virDrvDomainCoreDumpWithFormat domainCoreDumpWithFormat; virDrvDomainScreenshot domainScreenshot; virDrvDomainSetVcpus domainSetVcpus; virDrvDomainSetVcpusFlags domainSetVcpusFlags; virDrvDomainGetVcpusFlags domainGetVcpusFlags; virDrvDomainPinVcpu domainPinVcpu; virDrvDomainPinVcpuFlags domainPinVcpuFlags; virDrvDomainGetVcpuPinInfo domainGetVcpuPinInfo; virDrvDomainPinEmulator domainPinEmulator; virDrvDomainGetEmulatorPinInfo domainGetEmulatorPinInfo; virDrvDomainGetVcpus domainGetVcpus; virDrvDomainGetMaxVcpus domainGetMaxVcpus; virDrvDomainGetIOThreadInfo domainGetIOThreadInfo; virDrvDomainPinIOThread domainPinIOThread; virDrvDomainAddIOThread domainAddIOThread; virDrvDomainDelIOThread domainDelIOThread; virDrvDomainGetSecurityLabel domainGetSecurityLabel; virDrvDomainGetSecurityLabelList domainGetSecurityLabelList; virDrvNodeGetSecurityModel nodeGetSecurityModel; virDrvDomainGetXMLDesc domainGetXMLDesc; virDrvConnectDomainXMLFromNative connectDomainXMLFromNative; virDrvConnectDomainXMLToNative connectDomainXMLToNative; virDrvConnectListDefinedDomains connectListDefinedDomains; virDrvConnectNumOfDefinedDomains connectNumOfDefinedDomains; virDrvDomainCreate domainCreate; virDrvDomainCreateWithFlags domainCreateWithFlags; virDrvDomainCreateWithFiles domainCreateWithFiles; virDrvDomainDefineXML domainDefineXML; virDrvDomainDefineXMLFlags domainDefineXMLFlags; virDrvDomainUndefine domainUndefine; virDrvDomainUndefineFlags domainUndefineFlags; virDrvDomainAttachDevice domainAttachDevice; virDrvDomainAttachDeviceFlags domainAttachDeviceFlags; virDrvDomainDetachDevice domainDetachDevice; virDrvDomainDetachDeviceFlags domainDetachDeviceFlags; virDrvDomainUpdateDeviceFlags domainUpdateDeviceFlags; virDrvDomainGetAutostart domainGetAutostart; virDrvDomainSetAutostart domainSetAutostart; virDrvDomainGetSchedulerType domainGetSchedulerType; virDrvDomainGetSchedulerParameters domainGetSchedulerParameters; virDrvDomainGetSchedulerParametersFlags domainGetSchedulerParametersFlags; virDrvDomainSetSchedulerParameters domainSetSchedulerParameters; virDrvDomainSetSchedulerParametersFlags domainSetSchedulerParametersFlags; virDrvDomainMigratePrepare domainMigratePrepare; virDrvDomainMigratePerform domainMigratePerform; virDrvDomainMigrateFinish domainMigrateFinish; virDrvDomainBlockResize domainBlockResize; virDrvDomainBlockStats domainBlockStats; virDrvDomainBlockStatsFlags domainBlockStatsFlags; virDrvDomainInterfaceStats domainInterfaceStats; virDrvDomainSetInterfaceParameters domainSetInterfaceParameters; virDrvDomainGetInterfaceParameters domainGetInterfaceParameters; virDrvDomainMemoryStats domainMemoryStats; virDrvDomainBlockPeek domainBlockPeek; virDrvDomainMemoryPeek domainMemoryPeek; virDrvDomainGetBlockInfo domainGetBlockInfo; virDrvNodeGetCPUStats nodeGetCPUStats; virDrvNodeGetMemoryStats nodeGetMemoryStats; virDrvNodeGetCellsFreeMemory nodeGetCellsFreeMemory; virDrvNodeGetFreeMemory nodeGetFreeMemory; virDrvConnectDomainEventRegister connectDomainEventRegister; virDrvConnectDomainEventDeregister connectDomainEventDeregister; virDrvDomainMigratePrepare2 domainMigratePrepare2; virDrvDomainMigrateFinish2 domainMigrateFinish2; virDrvNodeDeviceDettach nodeDeviceDettach; virDrvNodeDeviceDetachFlags nodeDeviceDetachFlags; virDrvNodeDeviceReAttach nodeDeviceReAttach; virDrvNodeDeviceReset nodeDeviceReset; virDrvDomainMigratePrepareTunnel domainMigratePrepareTunnel; virDrvConnectIsEncrypted connectIsEncrypted; virDrvConnectIsSecure connectIsSecure; virDrvDomainIsActive domainIsActive; virDrvDomainRename domainRename; virDrvDomainIsPersistent domainIsPersistent; virDrvDomainIsUpdated domainIsUpdated; virDrvConnectCompareCPU connectCompareCPU; virDrvConnectBaselineCPU connectBaselineCPU; virDrvDomainGetJobInfo domainGetJobInfo; virDrvDomainGetJobStats domainGetJobStats; virDrvDomainAbortJob domainAbortJob; virDrvDomainMigrateSetMaxDowntime domainMigrateSetMaxDowntime; virDrvDomainMigrateGetCompressionCache domainMigrateGetCompressionCache; virDrvDomainMigrateSetCompressionCache domainMigrateSetCompressionCache; virDrvDomainMigrateGetMaxSpeed domainMigrateGetMaxSpeed; virDrvDomainMigrateSetMaxSpeed domainMigrateSetMaxSpeed; virDrvConnectDomainEventRegisterAny connectDomainEventRegisterAny; virDrvConnectDomainEventDeregisterAny connectDomainEventDeregisterAny; virDrvDomainManagedSave domainManagedSave; virDrvDomainHasManagedSaveImage domainHasManagedSaveImage; virDrvDomainManagedSaveRemove domainManagedSaveRemove; virDrvDomainSnapshotCreateXML domainSnapshotCreateXML; virDrvDomainSnapshotGetXMLDesc domainSnapshotGetXMLDesc; virDrvDomainSnapshotNum domainSnapshotNum; virDrvDomainSnapshotListNames domainSnapshotListNames; virDrvDomainListAllSnapshots domainListAllSnapshots; virDrvDomainSnapshotNumChildren domainSnapshotNumChildren; virDrvDomainSnapshotListChildrenNames domainSnapshotListChildrenNames; virDrvDomainSnapshotListAllChildren domainSnapshotListAllChildren; virDrvDomainSnapshotLookupByName domainSnapshotLookupByName; virDrvDomainHasCurrentSnapshot domainHasCurrentSnapshot; virDrvDomainSnapshotGetParent domainSnapshotGetParent; virDrvDomainSnapshotCurrent domainSnapshotCurrent; virDrvDomainSnapshotIsCurrent domainSnapshotIsCurrent; virDrvDomainSnapshotHasMetadata domainSnapshotHasMetadata; virDrvDomainRevertToSnapshot domainRevertToSnapshot; virDrvDomainSnapshotDelete domainSnapshotDelete; virDrvDomainQemuMonitorCommand domainQemuMonitorCommand; virDrvDomainQemuAttach domainQemuAttach; virDrvDomainQemuAgentCommand domainQemuAgentCommand; virDrvConnectDomainQemuMonitorEventRegister connectDomainQemuMonitorEventRegister; virDrvConnectDomainQemuMonitorEventDeregister connectDomainQemuMonitorEventDeregister; virDrvDomainOpenConsole domainOpenConsole; virDrvDomainOpenChannel domainOpenChannel; virDrvDomainOpenGraphics domainOpenGraphics; virDrvDomainOpenGraphicsFD domainOpenGraphicsFD; virDrvDomainInjectNMI domainInjectNMI; virDrvDomainMigrateBegin3 domainMigrateBegin3; virDrvDomainMigratePrepare3 domainMigratePrepare3; virDrvDomainMigratePrepareTunnel3 domainMigratePrepareTunnel3; virDrvDomainMigratePerform3 domainMigratePerform3; virDrvDomainMigrateFinish3 domainMigrateFinish3; virDrvDomainMigrateConfirm3 domainMigrateConfirm3; virDrvDomainSendKey domainSendKey; virDrvDomainBlockJobAbort domainBlockJobAbort; virDrvDomainGetBlockJobInfo domainGetBlockJobInfo; virDrvDomainBlockJobSetSpeed domainBlockJobSetSpeed; virDrvDomainBlockPull domainBlockPull; virDrvDomainBlockRebase domainBlockRebase; virDrvDomainBlockCopy domainBlockCopy; virDrvDomainBlockCommit domainBlockCommit; virDrvConnectSetKeepAlive connectSetKeepAlive; virDrvConnectIsAlive connectIsAlive; virDrvNodeSuspendForDuration nodeSuspendForDuration; virDrvNodeGetCacheStats nodeGetCacheStats; virDrvDomainGetPerfEvents domainGetPerfEvents; virDrvDomainSetPerfEvents domainSetPerfEvents; virDrvDomainSetBlockIoTune domainSetBlockIoTune; virDrvDomainGetBlockIoTune domainGetBlockIoTune; virDrvDomainGetCPUStats domainGetCPUStats; virDrvDomainGetDiskErrors domainGetDiskErrors; virDrvDomainSetMetadata domainSetMetadata; virDrvDomainGetMetadata domainGetMetadata; virDrvNodeGetMemoryParameters nodeGetMemoryParameters; virDrvNodeSetMemoryParameters nodeSetMemoryParameters; virDrvNodeGetCPUMap nodeGetCPUMap; virDrvDomainFSTrim domainFSTrim; virDrvDomainSendProcessSignal domainSendProcessSignal; virDrvDomainLxcOpenNamespace domainLxcOpenNamespace; virDrvDomainMigrateBegin3Params domainMigrateBegin3Params; virDrvDomainMigratePrepare3Params domainMigratePrepare3Params; virDrvDomainMigratePrepareTunnel3Params domainMigratePrepareTunnel3Params; virDrvDomainMigratePerform3Params domainMigratePerform3Params; virDrvDomainMigrateFinish3Params domainMigrateFinish3Params; virDrvDomainMigrateConfirm3Params domainMigrateConfirm3Params; virDrvConnectGetCPUModelNames connectGetCPUModelNames; virDrvDomainFSFreeze domainFSFreeze; virDrvDomainFSThaw domainFSThaw; virDrvDomainGetTime domainGetTime; virDrvDomainSetTime domainSetTime; virDrvNodeGetFreePages nodeGetFreePages; virDrvConnectGetDomainCapabilities connectGetDomainCapabilities; virDrvConnectGetAllDomainStats connectGetAllDomainStats; virDrvNodeAllocPages nodeAllocPages; virDrvDomainGetFSInfo domainGetFSInfo; virDrvDomainInterfaceAddresses domainInterfaceAddresses; virDrvDomainSetUserPassword domainSetUserPassword; virDrvConnectRegisterCloseCallback connectRegisterCloseCallback; virDrvConnectUnregisterCloseCallback connectUnregisterCloseCallback; virDrvDomainMigrateStartPostCopy domainMigrateStartPostCopy; virDrvDomainGetGuestVcpus domainGetGuestVcpus; virDrvDomainSetGuestVcpus domainSetGuestVcpus; virDrvDomainSetVcpu domainSetVcpu; }; #endif /* __VIR_DRIVER_HYPERVISOR_H__ */
taget/libvirt
src/driver-hypervisor.h
C
lgpl-2.1
57,010
/* This library 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. * <p/> * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.rzo.yajsw.app; import java.io.IOException; import java.lang.reflect.Method; // TODO: Auto-generated Javadoc /** * The Class WrapperMain. */ public class WrapperJVMMain extends AbstractWrapperJVMMain { /** * The main method. * * @param args * the args * @throws IOException * * @throws IllegalAccessException * * @throws InstantiationException */ public static void main(String[] args) throws IOException { preExecute(args); executeMain(); postExecute(); } protected static void executeMain() { final Method mainMethod = WRAPPER_MANAGER.getMainMethod(); if (mainMethod == null) { System.out.println("no java main method found -> aborting"); System.exit(999); } Object[] mainMethodArgs = WRAPPER_MANAGER.getMainMethodArgs(); try { mainMethod.invoke(null, new Object[] { mainMethodArgs }); } catch (Throwable e) { e.printStackTrace(); exception = e; } } }
xien777/yajsw
yajsw/wrapper-app/src/main/java/org/rzo/yajsw/app/WrapperJVMMain.java
Java
lgpl-2.1
1,488
# fMBT, free Model Based Testing tool # Copyright (c) 2012 Intel Corporation. # # This program is free software; you can redistribute it and/or modify it # under the terms and conditions of the GNU Lesser General Public License, # version 2.1, as published by the Free Software Foundation. # # This program is distributed in the hope 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., # 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. # Import this to test step implementations written in Python # in order to enable logging. # fmbtlog writes given message to the fmbt log (XML) # messages can be viewed using format $al of # fmbt-log -f '$al' logfile # # adapterlog writes given message to the adapter log (plain text) # written by remote_python or remote_pyaal, for instance. # Log function implementations are provided by the adapter # component such as remote_python or remote_pyaal. import datetime import inspect import os import sys import time import urllib _g_fmbt_adapterlogtimeformat="%s.%f" _g_actionName = "undefined" _g_testStep = -1 _g_simulated_actions = [] def _fmbt_call_helper(func,param = ""): if simulated(): return "" sys.stdout.write("fmbt_call %s.%s\n" % (func,param)) sys.stdout.flush() response = sys.stdin.readline().rstrip() magic,code = response.split(" ") if magic == "fmbt_call": if code[0] == "1": return urllib.unquote(code[1:]) return "" def formatTime(timeformat="%s", timestamp=None): if timestamp == None: timestamp = datetime.datetime.now() # strftime on Windows does not support conversion to epoch (%s). # Calculate it here, if needed. if os.name == "nt": if "%s" in timeformat: epoch_time = time.mktime(timestamp.timetuple()) timeformat = timeformat.replace("%s", str(int(epoch_time))) if "%F" in timeformat: timeformat = timeformat.replace("%F", "%Y-%m-%d") if "%T" in timeformat: timeformat = timeformat.replace("%T", "%H:%M:%S") return timestamp.strftime(timeformat) def heuristic(): return _fmbt_call_helper("heuristic.get") def setHeuristic(heuristic): return _fmbt_call_helper("heuristic.set",heuristic) def coverage(): return _fmbt_call_helper("coverage.get") def setCoverage(coverage): return _fmbt_call_helper("coverage.set",coverage) def coverageValue(): return _fmbt_call_helper("coverage.getValue") def fmbtlog(msg, flush=True): try: file("/tmp/fmbt.fmbtlog", "a").write("%s\n" % (msg,)) except: pass def adapterlog(msg, flush=True): try: _adapterlogWriter(file("/tmp/fmbt.adapterlog", "a"), formatAdapterLogMessage(msg,)) except: pass def setAdapterLogWriter(func): """ Override low-level adapter log writer with the given function. The function should take two parameters: a file-like object and a log message. The message is formatted and ready to be written to the file. The default is lambda fileObj, formattedMsg: fileObj.write(formattedMsg) """ global _adapterlogWriter _adapterlogWriter = func def adapterLogWriter(): """ Return current low-level adapter log writer function. """ global _adapterlogWriter return _adapterlogWriter def reportOutput(msg): try: file("/tmp/fmbt.reportOutput", "a").write("%s\n" % (msg,)) except: pass def setAdapterLogTimeFormat(strftime_format): """ Use given time format string in timestamping adapterlog messages """ global _g_fmbt_adapterlogtimeformat _g_fmbt_adapterlogtimeformat = strftime_format def formatAdapterLogMessage(msg, fmt="%s %s\n"): """ Return timestamped adapter log message """ return fmt % (formatTime(_g_fmbt_adapterlogtimeformat), msg) def getActionName(): """deprecated, use actionName()""" return _g_actionName def actionName(): """ Return the name of currently executed action (input or output). """ return _g_actionName def getTestStep(): """deprecated, use testStep()""" return _g_testStep def testStep(): """ Return the number of currently executed test step. """ return _g_testStep def simulated(): """ Returns True if fMBT is simulating execution of an action (guard or body block) instead of really executing it. """ return len(_g_simulated_actions) > 0 def _adapterlogWriter(fileObj, formattedMsg): fileObj.write(formattedMsg) def funcSpec(func): """ Return function name and args as they could have been defined based on function object. """ argspec = inspect.getargspec(func) if argspec.defaults: kwarg_count = len(argspec.defaults) else: kwarg_count = 0 arg_count = len(argspec.args) - kwarg_count arglist = [str(arg) for arg in argspec.args[:arg_count]] kwargs = argspec.args[arg_count:] for index, kwarg in enumerate(kwargs): arglist.append("%s=%s" % (kwarg, repr(argspec.defaults[index]))) if argspec.varargs: arglist.append("*%s" % (argspec.varargs,)) if argspec.keywords: arglist.append("**%s" % (argspec.keywords,)) try: funcspec = "%s(%s)" % (func.func_name, ", ".join(arglist)) except: funcspec = "%s(fmbt.funcSpec error)" % (func.func_name,) return funcspec _g_debug_socket = None _g_debug_conn = None def debug(session=0): """ Start debugging with fmbt-debug from the point where this function was called. Execution will stop until connection to fmbt-debug [session] has been established. Parameters: session (integer, optional): debug session that identifies which fmbt-debug should connect to this process. The default is 0. Example: - execute on command line "fmbt-debug 42" - add fmbt.debug(42) in your Python code - run the Python code so that it will call fmbt.debug(42) - when done the debugging on the fmbt-debug prompt, enter "c" for continue. """ import bdb import inspect import pdb import socket global _g_debug_conn, _g_debug_socket if not _g_debug_socket: PORTBASE = 0xf4bd # 62653, fMBD host = "127.0.0.1" # accept local host only, by default port = PORTBASE + session _g_debug_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: _g_debug_socket.bind((host, port)) _g_debug_socket.listen(1) while True: (_g_debug_conn, addr) = _g_debug_socket.accept() _g_debug_conn.sendall("fmbt.debug\n") msg = _g_debug_conn.recv(len("fmbt-debug\n")) if msg.startswith("fmbt-debug"): break _g_debug_conn.close() except socket.error: # already in use, perhaps fmbt-debug is already listening to # the socket and waiting for this process to connect try: _g_debug_socket.connect((host, port)) _g_debug_conn = _g_debug_socket whos_there = _g_debug_conn.recv(len("fmbt-debug\n")) if not whos_there.startswith("fmbt-debug"): _g_debug_conn.close() _g_debug_socket = None _g_debug_conn = None raise ValueError( 'unexpected answer "%s", fmbt-debug expected' % (whos_there.strip(),)) _g_debug_conn.sendall("fmbt.debug\n") except socket.error: raise ValueError('debugger cannot listen or connect to %s:%s' % (host, port)) if not _g_debug_conn: fmbtlog("debugger waiting for connection at %s:%s" % (host, port)) # socket.makefile does not work due to buffering issues # therefore, use our own socket-to-file converter class SocketToFile(object): def __init__(self, socket_conn): self._conn = socket_conn def read(self, bytes=-1): msg = [] rv = "" try: c = self._conn.recv(1) except KeyboardInterrupt: self._conn.close() raise while c and not rv: msg.append(c) if c == "\r": rv = "".join(msg) elif c == "\n": rv = "".join(msg) elif len(msg) == bytes: rv = "".join(msg) else: c = self._conn.recv(1) return rv def readline(self): return self.read() def write(self, msg): self._conn.sendall(msg) def flush(self): pass connfile = SocketToFile(_g_debug_conn) debugger = pdb.Pdb(stdin=connfile, stdout=connfile) debugger.set_trace(inspect.currentframe().f_back)
pombreda/fMBT
utils/fmbt.py
Python
lgpl-2.1
9,267
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.impl.osdependent; import java.awt.*; import java.io.*; import java.lang.reflect.*; import java.net.*; import net.java.sip.communicator.util.Logger; import org.jdesktop.jdic.desktop.*; import org.jitsi.util.*; /** * The <tt>Desktop</tt> class handles desktop operations through the default * desktop implementation. It choose which implementation to use depending on * what is currently available (java 6 or Jdic). * * @author Yana Stamcheva */ public class Desktop { private static final Logger logger = Logger.getLogger(SystemTray.class); private static Desktop defaultDesktop; /** * Returns the default <tt>Desktop</tt> instance depending on the operating * system and java version availability. * * @return the default <tt>Desktop</tt> instance * @throws UnsupportedOperationException if the operation is not supported * @throws HeadlessException * @throws SecurityException */ public static Desktop getDefaultDesktop() throws UnsupportedOperationException, HeadlessException, SecurityException { if (defaultDesktop != null) return defaultDesktop; Class<?> awtDesktopClass = null; try { awtDesktopClass = Class.forName("java.awt.Desktop"); } catch (ClassNotFoundException ex) { // We'll try org.jdesktop.jdic.desktop then. } DesktopPeer peer = null; if (awtDesktopClass != null) try { peer = new AWTDesktopPeer(awtDesktopClass); } catch (Exception ex) { logger.error( "Failed to initialize the java.awt.SystemTray implementation.", ex); // We'll try org.jdesktop.jdic.desktop then. } if (peer == null) try { peer = new JdicDesktopPeer(); } catch (Exception ex) { logger.error( "Failed to initialize the org.jdesktop.jdic.tray implementation.", ex); } return (defaultDesktop = new Desktop(peer)); } private final DesktopPeer peer; /** * Creates a Desktop instance by specifying the underlying <tt>peer</tt> to * use for the implementation. * * @param peer the implementation peer */ private Desktop(DesktopPeer peer) { this.peer = peer; } /** * Returns the currently used peer. * * @return the currently used peer */ DesktopPeer getPeer() { return peer; } /** * The <tt>DesktopPeer</tt> interface provides abstraction for operating * system related desktop operations like open(file), print(file), etc. */ static interface DesktopPeer { public void open(File file) throws NullPointerException, IllegalArgumentException, UnsupportedOperationException, IOException, SecurityException; public void print(File file) throws NullPointerException, IllegalArgumentException, UnsupportedOperationException, IOException, SecurityException; public void edit(File file) throws NullPointerException, IllegalArgumentException, UnsupportedOperationException, IOException, SecurityException; public void browse(URI uri) throws NullPointerException, IllegalArgumentException, UnsupportedOperationException, IOException, SecurityException; } /** * A <tt>DesktopPeer</tt> implementation based on the java.awt.Desktop class * provided in java 1.6+ */ private static class AWTDesktopPeer implements DesktopPeer { private final Object impl; private final Method open; private final Method print; private final Method edit; private final Method browse; public AWTDesktopPeer(Class<?> clazz) throws UnsupportedOperationException, HeadlessException, SecurityException { Method getDefaultDesktop; try { getDefaultDesktop = clazz.getMethod("getDesktop", (Class<?>[]) null); open = clazz.getMethod("open", new Class<?>[]{ File.class }); print = clazz.getMethod("print", new Class<?>[]{ File.class }); edit = clazz.getMethod("edit", new Class<?>[]{ File.class }); browse = clazz.getMethod("browse", new Class<?>[]{ URI.class }); } catch (NoSuchMethodException ex) { throw new UnsupportedOperationException(ex); } try { impl = getDefaultDesktop.invoke(null, (Object[]) null); } catch (IllegalAccessException ex) { throw new UnsupportedOperationException(ex); } catch (InvocationTargetException ex) { throw new UnsupportedOperationException(ex); } } /** * Opens a file. */ public void open(File file) throws IOException { try { open.invoke(impl, new Object[]{file}); } catch (IllegalAccessException ex) { throw new UndeclaredThrowableException(ex); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); if (cause == null) throw new UndeclaredThrowableException(ex); else if (cause instanceof NullPointerException) throw (NullPointerException) cause; else if (cause instanceof IllegalArgumentException) throw (IllegalArgumentException) cause; else if (cause instanceof UnsupportedOperationException) throw (UnsupportedOperationException) cause; else if (cause instanceof IOException) throw (IOException) cause; else if (cause instanceof SecurityException) throw (SecurityException) cause; else throw new UndeclaredThrowableException(cause); } } /** * Prints a file. */ public void print(File file) throws IOException { try { print.invoke(impl, new Object[]{file}); } catch (IllegalAccessException ex) { throw new UndeclaredThrowableException(ex); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); if (cause == null) throw new UndeclaredThrowableException(ex); else if (cause instanceof NullPointerException) throw (NullPointerException) cause; else if (cause instanceof IllegalArgumentException) throw (IllegalArgumentException) cause; else if (cause instanceof UnsupportedOperationException) throw (UnsupportedOperationException) cause; else if (cause instanceof IOException) throw (IOException) cause; else if (cause instanceof SecurityException) throw (SecurityException) cause; else throw new UndeclaredThrowableException(cause); } } /** * Edits a file. */ public void edit(File file) throws IOException { try { edit.invoke(impl, new Object[]{file}); } catch (IllegalAccessException ex) { throw new UndeclaredThrowableException(ex); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); if (cause == null) throw new UndeclaredThrowableException(ex); else if (cause instanceof NullPointerException) throw (NullPointerException) cause; else if (cause instanceof IllegalArgumentException) throw (IllegalArgumentException) cause; else if (cause instanceof UnsupportedOperationException) throw (UnsupportedOperationException) cause; else if (cause instanceof IOException) throw (IOException) cause; else if (cause instanceof SecurityException) throw (SecurityException) cause; else throw new UndeclaredThrowableException(cause); } } /** * Browses a file. */ public void browse(URI uri) throws IOException { try { browse.invoke(impl, new Object[]{uri}); } catch (IllegalAccessException ex) { throw new UndeclaredThrowableException(ex); } catch (InvocationTargetException ex) { Throwable cause = ex.getCause(); if (cause == null) throw new UndeclaredThrowableException(ex); else if (cause instanceof NullPointerException) throw (NullPointerException) cause; else if (cause instanceof IllegalArgumentException) throw (IllegalArgumentException) cause; else if (cause instanceof UnsupportedOperationException) throw (UnsupportedOperationException) cause; else if (cause instanceof IOException) throw (IOException) cause; else if (cause instanceof SecurityException) throw (SecurityException) cause; else throw new UndeclaredThrowableException(cause); } } } /** * An implementation of <tt>DesktopPeer</tt> based on the Jdic library * Desktop class. */ private static class JdicDesktopPeer implements DesktopPeer { /** * Opens a file. */ public void open(final File file) throws IOException { try { // Use browse(URL) instead of open(file) if we're on Mac OS, // because of a Java VM crash when open(file) is invoked. if (!OSUtils.IS_MAC) org.jdesktop.jdic.desktop.Desktop.open(file); else if (!file.isDirectory()) org.jdesktop.jdic.desktop.Desktop.browse( file.toURI().toURL()); else Runtime.getRuntime().exec( "open " + file.getCanonicalPath()); } catch (DesktopException ex) { ex.printStackTrace(); Throwable cause = ex.getCause(); if (cause == null) throw new UndeclaredThrowableException(ex); else if (cause instanceof NullPointerException) throw (NullPointerException) cause; else if (cause instanceof IllegalArgumentException) throw (IllegalArgumentException) cause; else if (cause instanceof UnsupportedOperationException) throw (UnsupportedOperationException) cause; else if (cause instanceof IOException) throw (IOException) cause; else if (cause instanceof SecurityException) throw (SecurityException) cause; else throw new UndeclaredThrowableException(cause); } } /** * Prints a file. */ public void print(File file) throws IOException { try { org.jdesktop.jdic.desktop.Desktop.print(file); } catch (org.jdesktop.jdic.desktop.DesktopException ex) { Throwable cause = ex.getCause(); if (cause == null) throw new UndeclaredThrowableException(ex); else if (cause instanceof NullPointerException) throw (NullPointerException) cause; else if (cause instanceof IllegalArgumentException) throw (IllegalArgumentException) cause; else if (cause instanceof UnsupportedOperationException) throw (UnsupportedOperationException) cause; else if (cause instanceof IOException) throw (IOException) cause; else if (cause instanceof SecurityException) throw (SecurityException) cause; else throw new UndeclaredThrowableException(cause); } } /** * Edits the given file. */ public void edit(File file) throws IOException { try { org.jdesktop.jdic.desktop.Desktop.edit(file); } catch (org.jdesktop.jdic.desktop.DesktopException ex) { Throwable cause = ex.getCause(); if (cause == null) throw new UndeclaredThrowableException(ex); else if (cause instanceof NullPointerException) throw (NullPointerException) cause; else if (cause instanceof IllegalArgumentException) throw (IllegalArgumentException) cause; else if (cause instanceof UnsupportedOperationException) throw (UnsupportedOperationException) cause; else if (cause instanceof IOException) throw (IOException) cause; else if (cause instanceof SecurityException) throw (SecurityException) cause; else throw new UndeclaredThrowableException(cause); } } /** * Opens a browser with given uri. */ public void browse(URI uri) throws IOException { try { org.jdesktop.jdic.desktop.Desktop.browse(uri.toURL()); } catch (org.jdesktop.jdic.desktop.DesktopException ex) { Throwable cause = ex.getCause(); if (cause == null) throw new UndeclaredThrowableException(ex); else if (cause instanceof NullPointerException) throw (NullPointerException) cause; else if (cause instanceof IllegalArgumentException) throw (IllegalArgumentException) cause; else if (cause instanceof UnsupportedOperationException) throw (UnsupportedOperationException) cause; else if (cause instanceof IOException) throw (IOException) cause; else if (cause instanceof SecurityException) throw (SecurityException) cause; else throw new UndeclaredThrowableException(cause); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } } }
Metaswitch/jitsi
src/net/java/sip/communicator/impl/osdependent/Desktop.java
Java
lgpl-2.1
16,657
/* Copyright (C) 2011 Samsung Electronics This library 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 library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef WebKitDOM_EventTarget_Private_h #define WebKitDOM_EventTarget_Private_h #include "EventTarget.h" #ifdef __cplusplus extern "C" { #endif WebCore::EventTarget* _to_webcore_eventtarget(WebKitDOM_EventTarget* kitObj); WebKitDOM_EventTarget* _to_webkit_eventtarget(WebCore::EventTarget* coreObj, WebKitDOM_EventTarget* ret); #ifdef __cplusplus } #endif #endif
youfoh/webkit-efl
Source/WebCore/bindings/ewk/WebKitDOM_EventTarget_Private.h
C
lgpl-2.1
1,167
Ext.define('MyDesktop.modules.pages.view.Pages', { extend: 'Ext.window.Window', requires: [ 'Ext.data.ArrayStore', 'Ext.util.Format', 'Ext.grid.Panel', 'Ext.grid.RowNumberer' ], width:900, height:480, animCollapse:false, constrainHeader:true, layout: 'border', initComponent: function() { this.items = [ Ext.create('MyDesktop.modules.pages.view.PagesTree', { title: D.t('Pages tree'), region: 'center' //width: 400, }), this.buildForm() ] this.callParent(); } ,buildForm: function() { var me = this; return { border: false, title: D.t('Page editor'), xtype: 'panel', region: 'east', width:400, split: true, collapsible: true, layout: 'border', items: [ Ext.create('MyDesktop.modules.pages.view.PageEditForm', { region: 'center' }), Ext.create('MyDesktop.modules.pages.view.PageEditBlocks', { region: 'south', collapsible: true, height: 200, split: true }) ] } } })
Kolbaskin/yode-server
static/admin/modules/pages/view/Pages.js
JavaScript
lgpl-2.1
1,547
/* * Copyright (C) 2015 Eistec AB * 2016 Freie Universität Berlin * * This file is subject to the terms and conditions of the GNU Lesser * General Public License v2.1. See the file LICENSE in the top level * directory for more details. */ /** * @ingroup drivers_lis3dh * @{ * * @file * @brief Implementation of LIS3DH SPI driver * * @author Joakim Nohlgård <joakim.nohlgard@eistec.se> * @author Hauke Petersen <hauke.petersen@fu-berlin.de> */ #include <stddef.h> #include <stdint.h> #include "periph/spi.h" #include "lis3dh.h" #define ENABLE_DEBUG 0 #include "debug.h" #define SPI_MODE SPI_MODE_3 #define DEV_SPI (dev->params.spi) #define DEV_CS (dev->params.cs) #define DEV_CLK (dev->params.clk) #define DEV_SCALE (dev->params.scale) static inline int lis3dh_write_bits(const lis3dh_t *dev, const uint8_t reg, const uint8_t mask, const uint8_t values); static int lis3dh_write_reg(const lis3dh_t *dev, const uint8_t reg, const uint8_t value); static int lis3dh_read_regs(const lis3dh_t *dev, const uint8_t reg, const uint8_t len, uint8_t *buf); int lis3dh_init(lis3dh_t *dev, const lis3dh_params_t *params) { dev->params = *params; uint8_t test; /* initialize the chip select line */ if (spi_init_cs(DEV_SPI, DEV_CS) != SPI_OK) { DEBUG("[lis3dh] error while initializing CS pin\n"); return -1; } /* test connection to the device */ lis3dh_read_regs(dev, LIS3DH_REG_WHO_AM_I, 1, &test); if (test != LIS3DH_WHO_AM_I_RESPONSE) { /* chip is not responding correctly */ DEBUG("[lis3dh] error reading the who am i reg [0x%02x]\n", (int)test); return -1; } /* Clear all settings */ lis3dh_write_reg(dev, LIS3DH_REG_CTRL_REG1, LIS3DH_CTRL_REG1_XYZEN_MASK); /* Disable HP filter */ lis3dh_write_reg(dev, LIS3DH_REG_CTRL_REG2, 0); /* Disable INT1 interrupt sources */ lis3dh_write_reg(dev, LIS3DH_REG_CTRL_REG3, 0); /* Set block data update and little endian, set Normal mode (LP=0, HR=1) */ lis3dh_write_reg(dev, LIS3DH_REG_CTRL_REG4, (LIS3DH_CTRL_REG4_BDU_ENABLE | LIS3DH_CTRL_REG4_BLE_LITTLE_ENDIAN | LIS3DH_CTRL_REG4_HR_MASK)); /* Disable FIFO */ lis3dh_write_reg(dev, LIS3DH_REG_CTRL_REG5, 0); /* Reset INT2 settings */ lis3dh_write_reg(dev, LIS3DH_REG_CTRL_REG6, 0); /* Configure scale */ lis3dh_set_scale(dev, DEV_SCALE); return 0; } int lis3dh_read_xyz(const lis3dh_t *dev, lis3dh_data_t *acc_data) { uint8_t i; /* Set READ MULTIPLE mode */ static const uint8_t addr = (LIS3DH_REG_OUT_X_L | LIS3DH_SPI_READ_MASK | LIS3DH_SPI_MULTI_MASK); /* Acquire exclusive access to the bus. */ spi_acquire(DEV_SPI, DEV_CS, SPI_MODE, DEV_CLK); /* Perform the transaction */ spi_transfer_regs(DEV_SPI, DEV_CS, addr, NULL, acc_data, sizeof(lis3dh_data_t)); /* Release the bus for other threads. */ spi_release(DEV_SPI); /* Scale to milli-G */ for (i = 0; i < 3; ++i) { int32_t tmp = (int32_t)(((int16_t *)acc_data)[i]); tmp *= dev->scale; tmp /= 32768; (((int16_t *)acc_data)[i]) = (int16_t)tmp; } return 0; } int lis3dh_read_aux_adc1(const lis3dh_t *dev, int16_t *out) { return lis3dh_read_regs(dev, LIS3DH_REG_OUT_AUX_ADC1_L, LIS3DH_ADC_DATA_SIZE, (uint8_t *)out); } int lis3dh_read_aux_adc2(const lis3dh_t *dev, int16_t *out) { return lis3dh_read_regs(dev, LIS3DH_REG_OUT_AUX_ADC2_L, LIS3DH_ADC_DATA_SIZE, (uint8_t *)out); } int lis3dh_read_aux_adc3(const lis3dh_t *dev, int16_t *out) { return lis3dh_read_regs(dev, LIS3DH_REG_OUT_AUX_ADC3_L, LIS3DH_ADC_DATA_SIZE, (uint8_t *)out); } int lis3dh_set_aux_adc(const lis3dh_t *dev, const uint8_t enable, const uint8_t temperature) { return lis3dh_write_bits(dev, LIS3DH_REG_TEMP_CFG_REG, LIS3DH_TEMP_CFG_REG_ADC_PD_MASK | LIS3DH_TEMP_CFG_REG_TEMP_EN_MASK, (enable ? LIS3DH_TEMP_CFG_REG_ADC_PD_MASK : 0) | (temperature ? LIS3DH_TEMP_CFG_REG_TEMP_EN_MASK : 0)); } int lis3dh_set_axes(const lis3dh_t *dev, const uint8_t axes) { return lis3dh_write_bits(dev, LIS3DH_REG_CTRL_REG1, LIS3DH_CTRL_REG1_XYZEN_MASK, axes); } int lis3dh_set_fifo(const lis3dh_t *dev, const uint8_t mode, const uint8_t watermark) { int status; uint8_t reg; reg = (watermark << LIS3DH_FIFO_CTRL_REG_FTH_SHIFT) & LIS3DH_FIFO_CTRL_REG_FTH_MASK; reg |= mode; status = lis3dh_write_reg(dev, LIS3DH_REG_FIFO_CTRL_REG, reg); if (status < 0) { /* communication error */ return status; } if (mode != 0x00) { status = lis3dh_write_bits(dev, LIS3DH_REG_CTRL_REG5, LIS3DH_CTRL_REG5_FIFO_EN_MASK, LIS3DH_CTRL_REG5_FIFO_EN_MASK); } else { status = lis3dh_write_bits(dev, LIS3DH_REG_CTRL_REG5, LIS3DH_CTRL_REG5_FIFO_EN_MASK, 0); } return status; } int lis3dh_set_odr(const lis3dh_t *dev, const uint8_t odr) { return lis3dh_write_bits(dev, LIS3DH_REG_CTRL_REG1, LIS3DH_CTRL_REG1_ODR_MASK, odr); } int lis3dh_set_scale(lis3dh_t *dev, const uint8_t scale) { uint8_t scale_reg; /* Sensor full range is -32768 -- +32767 (measurements are left adjusted) */ /* => Scale factor is scale/32768 */ switch (scale) { case 2: dev->scale = 2000; scale_reg = LIS3DH_CTRL_REG4_SCALE_2G; break; case 4: dev->scale = 4000; scale_reg = LIS3DH_CTRL_REG4_SCALE_4G; break; case 8: dev->scale = 8000; scale_reg = LIS3DH_CTRL_REG4_SCALE_8G; break; case 16: dev->scale = 16000; scale_reg = LIS3DH_CTRL_REG4_SCALE_16G; break; default: return -1; } return lis3dh_write_bits(dev, LIS3DH_REG_CTRL_REG4, LIS3DH_CTRL_REG4_FS_MASK, scale_reg); } int lis3dh_set_int1(const lis3dh_t *dev, const uint8_t mode) { return lis3dh_write_reg(dev, LIS3DH_REG_CTRL_REG3, mode); } int lis3dh_get_fifo_level(const lis3dh_t *dev) { uint8_t reg; int level; if (lis3dh_read_regs(dev, LIS3DH_REG_FIFO_SRC_REG, 1, &reg) != 0) { return -1; } level = (reg & LIS3DH_FIFO_SRC_REG_FSS_MASK) >> LIS3DH_FIFO_SRC_REG_FSS_SHIFT; return level; } /** * @brief Read sequential registers from the LIS3DH. * * @param[in] dev Device descriptor * @param[in] reg The source register starting address * @param[in] len Number of bytes to read * @param[out] buf The values of the source registers will be written * here * * @return 0 on success * @return -1 on error */ static int lis3dh_read_regs(const lis3dh_t *dev, const uint8_t reg, const uint8_t len, uint8_t *buf) { /* Set READ MULTIPLE mode */ uint8_t addr = (reg & LIS3DH_SPI_ADDRESS_MASK) | LIS3DH_SPI_READ_MASK | LIS3DH_SPI_MULTI_MASK; /* Acquire exclusive access to the bus. */ spi_acquire(DEV_SPI, DEV_CS, SPI_MODE, DEV_CLK); /* Perform the transaction */ spi_transfer_regs(DEV_SPI, DEV_CS, addr, NULL, buf, (size_t)len); /* Release the bus for other threads. */ spi_release(DEV_SPI); return 0; } /** * @brief Write a value to an 8 bit register in the LIS3DH. * * @param[in] reg The target register. * @param[in] value The value to write. * * @return 0 on success * @return -1 on error */ static int lis3dh_write_reg(const lis3dh_t *dev, const uint8_t reg, const uint8_t value) { /* Set WRITE SINGLE mode */ uint8_t addr = ((reg & LIS3DH_SPI_ADDRESS_MASK) | LIS3DH_SPI_WRITE_MASK | LIS3DH_SPI_SINGLE_MASK); /* Acquire exclusive access to the bus. */ spi_acquire(DEV_SPI, DEV_CS, SPI_MODE, DEV_CLK); /* Perform the transaction */ spi_transfer_reg(DEV_SPI, DEV_CS, addr, value); /* Release the bus for other threads. */ spi_release(DEV_SPI); return 0; } /** * @brief Write (both set and clear) bits of an 8-bit register on the LIS3DH. * * @param[in] addr Register address on the LIS3DH. * @param[in] mask Bitmask for the bits to modify. * @param[in] values The values to write to the masked bits. * * @return 0 on success * @return -1 on error */ static inline int lis3dh_write_bits(const lis3dh_t *dev, const uint8_t reg, const uint8_t mask, const uint8_t values) { uint8_t tmp; if (lis3dh_read_regs(dev, reg, 1, &tmp) < 0) { /* Communication error */ return -1; } tmp &= ~mask; tmp |= (values & mask); if (lis3dh_write_reg(dev, reg, tmp) < 0) { /* Communication error */ return -1; } return 0; } /** @} */
OTAkeys/RIOT
drivers/lis3dh/lis3dh.c
C
lgpl-2.1
9,413
# Copyright (C) 2013-2017 Chris Lalancette <clalancette@gmail.com> # Copyright (C) 2013 Ian McLeod <imcleod@redhat.com> # This library 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; # version 2.1 of the License. # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """ RHEL-7 installation """ import os import oz.ozutil import oz.RedHat import oz.OzException class RHEL7Guest(oz.RedHat.RedHatLinuxCDYumGuest): """ Class for RHEL-7 installation """ def __init__(self, tdl, config, auto, output_disk=None, netdev=None, diskbus=None, macaddress=None): oz.RedHat.RedHatLinuxCDYumGuest.__init__(self, tdl, config, auto, output_disk, netdev, diskbus, True, True, "cpio", macaddress, True) self.virtio_channel_name = 'org.fedoraproject.anaconda.log.0' def _modify_iso(self): """ Method to modify the ISO for autoinstallation. """ self._copy_kickstart(os.path.join(self.iso_contents, "ks.cfg")) initrdline = " append initrd=initrd.img ks=cdrom:/dev/cdrom:/ks.cfg" if self.tdl.installtype == "url": initrdline += " repo=" + self.url + "\n" else: # RHEL6 dropped this command line directive due to an Anaconda bug # that has since been fixed. Note that this used to be "method=" # but that has been deprecated for some time. initrdline += " repo=cdrom:/dev/cdrom" self._modify_isolinux(initrdline) def get_auto_path(self): """ Method to create the correct path to the RHEL 7 kickstart file. """ return oz.ozutil.generate_full_auto_path("RHEL7.auto") def get_class(tdl, config, auto, output_disk=None, netdev=None, diskbus=None, macaddress=None): """ Factory method for RHEL-7 installs. """ if tdl.update.isdigit(): if netdev is None: netdev = 'virtio' if diskbus is None: diskbus = 'virtio' return RHEL7Guest(tdl, config, auto, output_disk, netdev, diskbus, macaddress) def get_supported_string(): """ Return supported versions as a string. """ return "RHEL 7"
imcleod/oz
oz/RHEL_7.py
Python
lgpl-2.1
2,885
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2012 Artem Pavlenko * * This library 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 library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //mapnik #include <mapnik/text_placements/list.hpp> #include <mapnik/xml_node.hpp> //boost #include <boost/make_shared.hpp> #include <boost/property_tree/ptree.hpp> namespace mapnik { bool text_placement_info_list::next() { if (state == 0) { properties = parent_->defaults; } else { if (state-1 >= parent_->list_.size()) return false; properties = parent_->list_[state-1]; } state++; return true; } text_symbolizer_properties & text_placements_list::add() { if (list_.size()) { text_symbolizer_properties &last = list_.back(); list_.push_back(last); //Preinitialize with old values } else { list_.push_back(defaults); } return list_.back(); } text_symbolizer_properties & text_placements_list::get(unsigned i) { return list_[i]; } /***************************************************************************/ text_placement_info_ptr text_placements_list::get_placement_info(double scale_factor) const { return boost::make_shared<text_placement_info_list>(this, scale_factor); } text_placements_list::text_placements_list() : text_placements(), list_(0) { } void text_placements_list::add_expressions(expression_set &output) { defaults.add_expressions(output); std::vector<text_symbolizer_properties>::const_iterator it; for (it=list_.begin(); it != list_.end(); it++) { it->add_expressions(output); } } unsigned text_placements_list::size() const { return list_.size(); } text_placements_ptr text_placements_list::from_xml(xml_node const &xml, fontset_map const & fontsets) { using boost::property_tree::ptree; text_placements_list *list = new text_placements_list; text_placements_ptr ptr = text_placements_ptr(list); list->defaults.from_xml(xml, fontsets); xml_node::const_iterator itr = xml.begin(); xml_node::const_iterator end = xml.end(); for( ;itr != end; ++itr) { if (itr->is_text() || !itr->is("Placement")) continue; text_symbolizer_properties &p = list->add(); p.from_xml(*itr, fontsets); //TODO: if (strict_ && // !p.format.fontset.size()) // ensure_font_face(p.format.face_name); } return ptr; } } //ns mapnik
kapouer/mapnik
src/text_placements/list.cpp
C++
lgpl-2.1
3,259
import telepathy from telepathy.interfaces import CONN_MGR_INTERFACE import dbus def parse_account(s): lines = s.splitlines() pairs = [] manager = None protocol = None for line in lines: if not line.strip(): continue k, v = line.split(':', 1) k = k.strip() v = v.strip() if k == 'manager': manager = v elif k == 'protocol': protocol = v else: if k not in ("account", "password"): if v.lower() == "false": v = False elif v.lower() == "true": v = True else: try: v = dbus.UInt32(int(v)) except: pass pairs.append((k, v)) assert manager assert protocol return manager, protocol, dict(pairs) def read_account(path): return parse_account(file(path).read()) def connect(manager, protocol, account, ready_handler=None): reg = telepathy.client.ManagerRegistry() reg.LoadManagers() mgr = reg.GetManager(manager) conn_bus_name, conn_object_path = \ mgr[CONN_MGR_INTERFACE].RequestConnection(protocol, account) return telepathy.client.Connection(conn_bus_name, conn_object_path, ready_handler=ready_handler) def connection_from_file(path, ready_handler=None): manager, protocol, account = read_account(path) return connect(manager, protocol, account, ready_handler=ready_handler)
epage/telepathy-python
examples/account.py
Python
lgpl-2.1
1,551
/* * This program source code file is part of KiCad, a free EDA CAD application. * * Copyright (C) 2004 Jean-Pierre Charras, jaen-pierre.charras@gipsa-lab.inpg.com * Copyright (C) 2008-2011 Wayne Stambaugh <stambaughw@verizon.net> * Copyright (C) 2004-2011 KiCad Developers, see change_log.txt for 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 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, you may find one here: * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * or you may search the http://www.gnu.org website for the version 2 license, * or you may write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ /** * @file tool_sch.cpp */ #include <fctsys.h> #include <class_drawpanel.h> #include <wxEeschemaStruct.h> #include <general.h> #include <hotkeys.h> #include <eeschema_id.h> #include <help_common_strings.h> /* Create the main Horizontal Toolbar for the schematic editor */ void SCH_EDIT_FRAME::ReCreateHToolbar() { if( m_mainToolBar != NULL ) return; wxString msg; m_mainToolBar = new wxAuiToolBar( this, ID_H_TOOLBAR, wxDefaultPosition, wxDefaultSize, wxAUI_TB_DEFAULT_STYLE | wxAUI_TB_HORZ_LAYOUT ); // Set up toolbar m_mainToolBar->AddTool( ID_NEW_PROJECT, wxEmptyString, KiBitmap( new_xpm ), _( "New schematic project" ) ); m_mainToolBar->AddTool( ID_LOAD_PROJECT, wxEmptyString, KiBitmap( open_document_xpm ), _( "Open schematic project" ) ); m_mainToolBar->AddTool( ID_SAVE_PROJECT, wxEmptyString, KiBitmap( save_project_xpm ), _( "Save schematic project" ) ); m_mainToolBar->AddSeparator(); m_mainToolBar->AddTool( ID_SHEET_SET, wxEmptyString, KiBitmap( sheetset_xpm ), _( "Page settings" ) ); m_mainToolBar->AddSeparator(); m_mainToolBar->AddTool( wxID_PRINT, wxEmptyString, KiBitmap( print_button_xpm ), _( "Print schematic" ) ); m_mainToolBar->AddSeparator(); m_mainToolBar->AddTool( wxID_CUT, wxEmptyString, KiBitmap( cut_button_xpm ), _( "Cut selected item" ) ); m_mainToolBar->AddTool( wxID_COPY, wxEmptyString, KiBitmap( copy_button_xpm ), _( "Copy selected item" ) ); m_mainToolBar->AddTool( wxID_PASTE, wxEmptyString, KiBitmap( paste_xpm ), _( "Paste" ) ); m_mainToolBar->AddSeparator(); msg = AddHotkeyName( HELP_UNDO, s_Schematic_Hokeys_Descr, HK_UNDO, IS_COMMENT ); m_mainToolBar->AddTool( wxID_UNDO, wxEmptyString, KiBitmap( undo_xpm ), msg ); msg = AddHotkeyName( HELP_REDO, s_Schematic_Hokeys_Descr, HK_REDO, IS_COMMENT ); m_mainToolBar->AddTool( wxID_REDO, wxEmptyString, KiBitmap( redo_xpm ), msg ); m_mainToolBar->AddSeparator(); msg = AddHotkeyName( HELP_FIND, s_Schematic_Hokeys_Descr, HK_FIND_ITEM, IS_COMMENT ); m_mainToolBar->AddTool( ID_FIND_ITEMS, wxEmptyString, KiBitmap( find_xpm ), msg ); m_mainToolBar->AddTool( wxID_REPLACE, wxEmptyString, KiBitmap( find_replace_xpm ), wxNullBitmap, wxITEM_NORMAL, _( "Find and replace text" ), HELP_REPLACE, NULL ); m_mainToolBar->AddSeparator(); msg = AddHotkeyName( HELP_ZOOM_IN, s_Schematic_Hokeys_Descr, HK_ZOOM_IN, IS_COMMENT ); m_mainToolBar->AddTool( ID_ZOOM_IN, wxEmptyString, KiBitmap( zoom_in_xpm ), msg ); msg = AddHotkeyName( HELP_ZOOM_OUT, s_Schematic_Hokeys_Descr, HK_ZOOM_OUT, IS_COMMENT ); m_mainToolBar->AddTool( ID_ZOOM_OUT, wxEmptyString, KiBitmap( zoom_out_xpm ), msg ); msg = AddHotkeyName( HELP_ZOOM_REDRAW, s_Schematic_Hokeys_Descr, HK_ZOOM_REDRAW, IS_COMMENT ); m_mainToolBar->AddTool( ID_ZOOM_REDRAW, wxEmptyString, KiBitmap( zoom_redraw_xpm ), msg ); msg = AddHotkeyName( HELP_ZOOM_FIT, s_Schematic_Hokeys_Descr, HK_ZOOM_AUTO, IS_COMMENT ); m_mainToolBar->AddTool( ID_ZOOM_PAGE, wxEmptyString, KiBitmap( zoom_fit_in_page_xpm ), msg ); m_mainToolBar->AddSeparator(); m_mainToolBar->AddTool( ID_HIERARCHY, wxEmptyString, KiBitmap( hierarchy_nav_xpm ), _( "Navigate schematic hierarchy" ) ); m_mainToolBar->AddSeparator(); m_mainToolBar->AddTool( ID_TO_LIBRARY, wxEmptyString, KiBitmap( libedit_xpm ), HELP_RUN_LIB_EDITOR ); m_mainToolBar->AddTool( ID_TO_LIBVIEW, wxEmptyString, KiBitmap( library_browse_xpm ), HELP_RUN_LIB_VIEWER ); m_mainToolBar->AddSeparator(); m_mainToolBar->AddTool( ID_GET_ANNOTATE, wxEmptyString, KiBitmap( annotate_xpm ), HELP_ANNOTATE ); m_mainToolBar->AddTool( ID_GET_ERC, wxEmptyString, KiBitmap( erc_xpm ), _( "Perform electric rules check" ) ); m_mainToolBar->AddTool( ID_GET_NETLIST, wxEmptyString, KiBitmap( netlist_xpm ), _( "Generate netlist" ) ); m_mainToolBar->AddTool( ID_GET_TOOLS, wxEmptyString, KiBitmap( bom_xpm ), HELP_GENERATE_BOM ); m_mainToolBar->AddSeparator(); m_mainToolBar->AddTool( ID_TO_CVPCB, wxEmptyString, KiBitmap( cvpcb_xpm ), _( "Run CvPcb to associate components and footprints" ) ); m_mainToolBar->AddTool( ID_TO_PCB, wxEmptyString, KiBitmap( pcbnew_xpm ), _( "Run Pcbnew to layout printed circuit board" ) ); m_mainToolBar->AddTool( ID_BACKANNO_ITEMS, wxEmptyString, KiBitmap( import_footprint_names_xpm ), HELP_IMPORT_FOOTPRINTS ); // set icon paddings m_mainToolBar->SetToolBorderPadding(3); // padding m_mainToolBar->SetToolSeparation(0); //m_mainToolBar->SetMargins(0,1); // margins width and height // after adding the tools to the toolbar, must call Realize() to reflect the changes m_mainToolBar->Realize(); } /* Create Vertical Right Toolbar */ void SCH_EDIT_FRAME::ReCreateVToolbar() { if( m_drawToolBar ) return; m_drawToolBar = new wxAuiToolBar( this, ID_V_TOOLBAR, wxDefaultPosition, wxDefaultSize, wxAUI_TB_DEFAULT_STYLE | wxAUI_TB_VERTICAL ); // Set up toolbar m_drawToolBar->AddTool( ID_NO_TOOL_SELECTED, wxEmptyString, KiBitmap( cursor_xpm ), wxEmptyString, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_HIERARCHY_PUSH_POP_BUTT, wxEmptyString, KiBitmap( hierarchy_cursor_xpm ), _( "Ascend or descend hierarchy" ), wxITEM_CHECK ); m_drawToolBar->AddTool( ID_SCH_PLACE_COMPONENT, wxEmptyString, KiBitmap( add_component_xpm ), HELP_PLACE_COMPONENTS, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_PLACE_POWER_BUTT, wxEmptyString, KiBitmap( add_power_xpm ), HELP_PLACE_POWERPORT, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_WIRE_BUTT, wxEmptyString, KiBitmap( add_line_xpm ), HELP_PLACE_WIRE, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_BUS_BUTT, wxEmptyString, KiBitmap( add_bus_xpm ), HELP_PLACE_BUS, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_WIRETOBUS_ENTRY_BUTT, wxEmptyString, KiBitmap( add_line2bus_xpm ), HELP_PLACE_WIRE2BUS_ENTRY, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_BUSTOBUS_ENTRY_BUTT, wxEmptyString, KiBitmap( add_bus2bus_xpm ), HELP_PLACE_BUS2BUS_ENTRY, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_NOCONN_BUTT, wxEmptyString, KiBitmap( noconn_xpm ), HELP_PLACE_NC_FLAG, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_JUNCTION_BUTT, wxEmptyString, KiBitmap( add_junction_xpm ), HELP_PLACE_JUNCTION, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_LABEL_BUTT, wxEmptyString, KiBitmap( add_line_label_xpm ), HELP_PLACE_NETLABEL, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_GLABEL_BUTT, wxEmptyString, KiBitmap( add_glabel_xpm ), HELP_PLACE_GLOBALLABEL, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_HIERLABEL_BUTT, wxEmptyString, KiBitmap( add_hierarchical_label_xpm ), HELP_PLACE_HIER_LABEL, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_SHEET_SYMBOL_BUTT, wxEmptyString, KiBitmap( add_hierarchical_subsheet_xpm ), HELP_PLACE_SHEET, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_IMPORT_HLABEL_BUTT, wxEmptyString, KiBitmap( import_hierarchical_label_xpm ), HELP_IMPORT_SHEETPIN, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_SHEET_PIN_BUTT, wxEmptyString, KiBitmap( add_hierar_pin_xpm ), HELP_PLACE_SHEETPIN, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_LINE_COMMENT_BUTT, wxEmptyString, KiBitmap( add_dashed_line_xpm ), HELP_PLACE_GRAPHICLINES, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_TEXT_COMMENT_BUTT, wxEmptyString, KiBitmap( add_text_xpm ), HELP_PLACE_GRAPHICTEXTS, wxITEM_CHECK ); m_drawToolBar->AddTool( ID_ADD_IMAGE_BUTT, wxEmptyString, KiBitmap( image_xpm ), _("Add a bitmap image"), wxITEM_CHECK ); m_drawToolBar->AddTool( ID_SCHEMATIC_DELETE_ITEM_BUTT, wxEmptyString, KiBitmap( delete_xpm ), HELP_DELETE_ITEMS, wxITEM_CHECK ); // set icon paddings m_drawToolBar->SetToolBorderPadding(2); // padding m_drawToolBar->SetToolSeparation(0); //m_drawToolBar->SetMargins(1,0); // margins width and height m_drawToolBar->Realize(); } /* Create Vertical Left Toolbar (Option Toolbar) */ void SCH_EDIT_FRAME::ReCreateOptToolbar() { if( m_optionsToolBar ) return; m_optionsToolBar = new wxAuiToolBar( this, ID_OPT_TOOLBAR, wxDefaultPosition, wxDefaultSize, wxAUI_TB_DEFAULT_STYLE | wxAUI_TB_VERTICAL ); m_optionsToolBar->AddTool( ID_TB_OPTIONS_SHOW_GRID, wxEmptyString, KiBitmap( grid_xpm ), _( "Turn grid off" ), wxITEM_CHECK ); m_optionsToolBar->AddTool( ID_TB_OPTIONS_SELECT_UNIT_INCH, wxEmptyString, KiBitmap( unit_inch_xpm ), _( "Units in inches" ), wxITEM_CHECK ); m_optionsToolBar->AddTool( ID_TB_OPTIONS_SELECT_UNIT_MM, wxEmptyString, KiBitmap( unit_mm_xpm ), _( "Units in millimeters" ), wxITEM_CHECK ); m_optionsToolBar->AddTool( ID_TB_OPTIONS_SELECT_CURSOR, wxEmptyString, KiBitmap( cursor_shape_xpm ), _( "Change cursor shape" ), wxITEM_CHECK ); //m_optionsToolBar->AddSeparator(); m_optionsToolBar->AddTool( ID_TB_OPTIONS_HIDDEN_PINS, wxEmptyString, KiBitmap( hidden_pin_xpm ), _( "Show hidden pins" ), wxITEM_CHECK ); //m_optionsToolBar->AddSeparator(); m_optionsToolBar->AddTool( ID_TB_OPTIONS_BUS_WIRES_ORIENT, wxEmptyString, KiBitmap( lines90_xpm ), _( "HV orientation for wires and bus" ), wxITEM_CHECK ); // set icon paddings m_optionsToolBar->SetToolBorderPadding(2); // padding m_optionsToolBar->SetToolSeparation(0); //m_optionsToolBar->SetMargins(4,0); // margins width and height m_optionsToolBar->Realize(); } void SCH_EDIT_FRAME::OnSelectOptionToolbar( wxCommandEvent& event ) { if( m_canvas == NULL ) return; int id = event.GetId(); switch( id ) { case ID_TB_OPTIONS_HIDDEN_PINS: m_showAllPins = m_optionsToolBar->GetToolToggled( id ); m_canvas->Refresh(); break; case ID_TB_OPTIONS_BUS_WIRES_ORIENT: g_HVLines = m_optionsToolBar->GetToolToggled( id ); break; default: wxFAIL_MSG( wxT( "Unexpected select option tool bar ID." ) ); break; } }
hellamps/kicad
eeschema/tool_sch.cpp
C++
lgpl-2.1
13,018
/****************************************************************************** * THIS FILE IS GENERATED - ANY EDITS WILL BE OVERWRITTEN */ #pragma once #include "jobs/basejob.h" #include "events/eventloader.h" #include "converters.h" namespace QMatrixClient { // Operations /// Get a list of events for this room /// /// This API returns a list of message and state events for a room. It uses /// pagination query parameters to paginate history in the room. class GetRoomEventsJob : public BaseJob { public: /*! Get a list of events for this room * \param roomId * The room to get events from. * \param from * The token to start returning events from. This token can be obtained * from a ``prev_batch`` token returned for each room by the sync API, * or from a ``start`` or ``end`` token returned by a previous request * to this endpoint. * \param dir * The direction to return events from. * \param to * The token to stop returning events at. This token can be obtained from * a ``prev_batch`` token returned for each room by the sync endpoint, * or from a ``start`` or ``end`` token returned by a previous request to * this endpoint. * \param limit * The maximum number of events to return. Default: 10. * \param filter * A JSON RoomEventFilter to filter returned events with. */ explicit GetRoomEventsJob(const QString& roomId, const QString& from, const QString& dir, const QString& to = {}, Omittable<int> limit = none, const QString& filter = {}); /*! Construct a URL without creating a full-fledged job object * * This function can be used when a URL for * GetRoomEventsJob is necessary but the job * itself isn't. */ static QUrl makeRequestUrl(QUrl baseUrl, const QString& roomId, const QString& from, const QString& dir, const QString& to = {}, Omittable<int> limit = none, const QString& filter = {}); ~GetRoomEventsJob() override; // Result properties /// The token the pagination starts from. If ``dir=b`` this will be /// the token supplied in ``from``. const QString& begin() const; /// The token the pagination ends at. If ``dir=b`` this token should /// be used again to request even earlier events. const QString& end() const; /// A list of room events. RoomEvents&& chunk(); protected: Status parseJson(const QJsonDocument& data) override; private: class Private; QScopedPointer<Private> d; }; } // namespace QMatrixClient
Fxrh/libqmatrixclient
lib/csapi/message_pagination.h
C
lgpl-2.1
2,951
import * as Behaviour from './Behaviour'; import * as ComposeApis from '../../behaviour/composing/ComposeApis'; import { ComposeSchema } from '../../behaviour/composing/ComposeSchema'; import { ComposingBehaviour } from '../../behaviour/composing/ComposingTypes'; const Composing = Behaviour.create({ fields: ComposeSchema, name: 'composing', apis: ComposeApis }) as ComposingBehaviour; export { Composing };
FernCreek/tinymce
modules/alloy/src/main/ts/ephox/alloy/api/behaviour/Composing.ts
TypeScript
lgpl-2.1
418
/* This file is part of the KDE project Copyright (C) 2006 Matthias Kretz <kretz@kde.org> This library 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) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Nokia Corporation (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library. If not, see <http://www.gnu.org/licenses/>. */ #ifndef Phonon_FAKE_BYTESTREAM_H #define Phonon_FAKE_BYTESTREAM_H #include "mediaproducer.h" #include <phonon/bytestreaminterface.h> class QTimer; namespace Phonon { namespace Fake { class ByteStream : public MediaProducer, public Phonon::ByteStreamInterface { Q_OBJECT Q_INTERFACES(Phonon::ByteStreamInterface) public: ByteStream(QObject *parent); ~ByteStream(); qint64 currentTime() const; qint64 totalTime() const; Q_INVOKABLE qint32 aboutToFinishTime() const; Q_INVOKABLE qint64 streamSize() const; Q_INVOKABLE bool streamSeekable() const; bool isSeekable() const; Q_INVOKABLE void setStreamSeekable(bool); void writeData(const QByteArray &data); Q_INVOKABLE void setStreamSize(qint64); void endOfData(); Q_INVOKABLE void setAboutToFinishTime(qint32); void play(); void pause(); void seek(qint64 time); public Q_SLOTS: virtual void stop(); Q_SIGNALS: void finished(); void aboutToFinish(qint32); void length(qint64); void needData(); void enoughData(); void seekStream(qint64); private Q_SLOTS: void consumeStream(); private: qint64 m_aboutToFinishBytes; qint64 m_streamSize; qint64 m_bufferSize; qint64 m_streamPosition; bool m_streamSeekable; bool m_eof; bool m_aboutToFinishEmitted; QTimer *m_streamConsumeTimer; }; }} //namespace Phonon::Fake // vim: sw=4 ts=4 tw=80 #endif // Phonon_FAKE_BYTESTREAM_H
sandsmark/phonon-visualization-gsoc
phonon/tests/fakebackend/bytestream.h
C
lgpl-2.1
2,831
/* * $Id$ * Copyright (c) 2001 Stephane Conversy, Jean-Daniel Fekete and Ecole des Mines de Nantes. All rights reserved. This software is proprietary information of Stephane Conversy, Jean-Daniel Fekete and Ecole des Mines de Nantes. You shall use it only in accordance with the terms of the license agreement you accepted when downloading this software. The license is available in the file license.txt and at the following URL: http://www.emn.fr/info/image/Themes/Indigo/licence.html */ #ifndef __svg_String__ #define __svg_String__ #include <svgl/config.hpp> #include <w3c/dom/string.hpp> namespace svg { typedef dom::string String; } #endif // __svg_String__
rev22/svgl
src/w3c/svg/String.hpp
C++
lgpl-2.1
676
using Octopus.Client; using Octopus.Client.Model; using OctopusStore.Config; namespace OctopusStore.Octopus { public class CommandBase { private readonly IConfiguration _config; private readonly OctopusRepository _repo; public CommandBase(IConfiguration config) { _config = config; var factory = new OctopusClientFactory(); var client = factory.CreateClient(new OctopusServerEndpoint(_config.OctopusHost + "api", _config.OctopusApiKey)); _repo = new OctopusRepository(client); } protected VariableSetResource GetVariableSet() { var libararySet = _repo.LibraryVariableSets.FindOne(vs => vs.Name == _config.VariableSetName); return _repo.VariableSets.Get(libararySet.VariableSetId); } protected void Modify(VariableSetResource variableSet) { _repo.VariableSets.Modify(variableSet); } } }
Pondidum/OctopusStore
OctopusStore/Octopus/CommandBase.cs
C#
lgpl-2.1
838
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>value</title> <!-- <script src="http://use.edgefonts.net/source-sans-pro;source-code-pro.js"></script> --> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic|Source+Code+Pro:300,400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="../assets/css/bootstrap.css"> <link rel="stylesheet" href="../assets/css/jquery.bonsai.css"> <link rel="stylesheet" href="../assets/css/main.css"> <link rel="stylesheet" href="../assets/css/icons.css"> <script type="text/javascript" src="../assets/js/jquery-2.1.0.min.js"></script> <script type="text/javascript" src="../assets/js/bootstrap.js"></script> <script type="text/javascript" src="../assets/js/jquery.bonsai.js"></script> <!-- <script type="text/javascript" src="../assets/js/main.js"></script> --> </head> <body> <div> <!-- Name Title --> <h1>value</h1> <!-- Type and Stereotype --> <section style="margin-top: .5em;"> <span class="alert alert-info"> <span class="node-icon _icon-UMLParameter"></span> UMLParameter </span> </section> <!-- Path --> <section style="margin-top: 10px"> <span class="label label-info"><a href='cf9c8b720f3815adeccaf3ef6e48c6c4.html'><span class='node-icon _icon-Project'></span>Untitled</a></span> <span>::</span> <span class="label label-info"><a href='6550300e57d7fc770bd2e9afbcdb3ecb.html'><span class='node-icon _icon-UMLModel'></span>JavaReverse</a></span> <span>::</span> <span class="label label-info"><a href='7ff2d96ca3eb7f62f48c1a30b3c7c990.html'><span class='node-icon _icon-UMLPackage'></span>net</a></span> <span>::</span> <span class="label label-info"><a href='7adc4be4f2e4859086f068fc27512d85.html'><span class='node-icon _icon-UMLPackage'></span>gleamynode</a></span> <span>::</span> <span class="label label-info"><a href='bb15307bdbbaf31bfef4f71be74150ae.html'><span class='node-icon _icon-UMLPackage'></span>netty</a></span> <span>::</span> <span class="label label-info"><a href='bb10d55a00efdc33adcaaa9c230beeec.html'><span class='node-icon _icon-UMLPackage'></span>util</a></span> <span>::</span> <span class="label label-info"><a href='cc3f7cc2c8ca7adf30a60343866b88f7.html'><span class='node-icon _icon-UMLClass'></span>ConvertUtil</a></span> <span>::</span> <span class="label label-info"><a href='feb23f442bb3f756dd5499ec83b8c135.html'><span class='node-icon _icon-UMLOperation'></span>toBoolean</a></span> <span>::</span> <span class="label label-info"><a href='773c29172b66ffb6e84585ebd02b077c.html'><span class='node-icon _icon-UMLParameter'></span>value</a></span> </section> <!-- Diagram --> <!-- Description --> <section> <h3>Description</h3> <div> <span class="label label-info">none</span> </div> </section> <!-- Specification --> <!-- Directed Relationship --> <!-- Undirected Relationship --> <!-- Classifier --> <!-- Interface --> <!-- Component --> <!-- Node --> <!-- Actor --> <!-- Use Case --> <!-- Template Parameters --> <!-- Literals --> <!-- Attributes --> <!-- Operations --> <!-- Receptions --> <!-- Extension Points --> <!-- Parameters --> <!-- Diagrams --> <!-- Behavior --> <!-- Action --> <!-- Interaction --> <!-- CombinedFragment --> <!-- Activity --> <!-- State Machine --> <!-- State Machine --> <!-- State --> <!-- Vertex --> <!-- Transition --> <!-- Properties --> <section> <h3>Properties</h3> <table class="table table-striped table-bordered"> <tr> <th width="50%">Name</th> <th width="50%">Value</th> </tr> <tr> <td>name</td> <td>value</td> </tr> <tr> <td>stereotype</td> <td><span class='label label-info'>null</span></td> </tr> <tr> <td>visibility</td> <td>public</td> </tr> <tr> <td>isStatic</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>isLeaf</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>type</td> <td><a href='52af50a5b0f2ed4d23d445d13bc072ee.html'><span class='node-icon _icon-UMLClass'></span>Object</a></td> </tr> <tr> <td>multiplicity</td> <td></td> </tr> <tr> <td>isReadOnly</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>isOrdered</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>isUnique</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>defaultValue</td> <td></td> </tr> <tr> <td>direction</td> <td>in</td> </tr> </table> </section> <!-- Tags --> <!-- Constraints, Dependencies, Dependants --> <!-- Relationships --> <!-- Owned Elements --> </div> </body> </html>
jiangbo212/netty-init
html-docs/contents/773c29172b66ffb6e84585ebd02b077c.html
HTML
lgpl-2.1
7,272
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>length</title> <!-- <script src="http://use.edgefonts.net/source-sans-pro;source-code-pro.js"></script> --> <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,700,300italic,400italic,700italic|Source+Code+Pro:300,400,700' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="../assets/css/bootstrap.css"> <link rel="stylesheet" href="../assets/css/jquery.bonsai.css"> <link rel="stylesheet" href="../assets/css/main.css"> <link rel="stylesheet" href="../assets/css/icons.css"> <script type="text/javascript" src="../assets/js/jquery-2.1.0.min.js"></script> <script type="text/javascript" src="../assets/js/bootstrap.js"></script> <script type="text/javascript" src="../assets/js/jquery.bonsai.js"></script> <!-- <script type="text/javascript" src="../assets/js/main.js"></script> --> </head> <body> <div> <!-- Name Title --> <h1>length</h1> <!-- Type and Stereotype --> <section style="margin-top: .5em;"> <span class="alert alert-info"> <span class="node-icon _icon-UMLParameter"></span> UMLParameter </span> </section> <!-- Path --> <section style="margin-top: 10px"> <span class="label label-info"><a href='cf9c8b720f3815adeccaf3ef6e48c6c4.html'><span class='node-icon _icon-Project'></span>Untitled</a></span> <span>::</span> <span class="label label-info"><a href='6550300e57d7fc770bd2e9afbcdb3ecb.html'><span class='node-icon _icon-UMLModel'></span>JavaReverse</a></span> <span>::</span> <span class="label label-info"><a href='7ff2d96ca3eb7f62f48c1a30b3c7c990.html'><span class='node-icon _icon-UMLPackage'></span>net</a></span> <span>::</span> <span class="label label-info"><a href='7adc4be4f2e4859086f068fc27512d85.html'><span class='node-icon _icon-UMLPackage'></span>gleamynode</a></span> <span>::</span> <span class="label label-info"><a href='bb15307bdbbaf31bfef4f71be74150ae.html'><span class='node-icon _icon-UMLPackage'></span>netty</a></span> <span>::</span> <span class="label label-info"><a href='13ebeea6c90c35d72f303d2d478d584e.html'><span class='node-icon _icon-UMLPackage'></span>buffer</a></span> <span>::</span> <span class="label label-info"><a href='ff1fa8e2f38aee078493a030c63f8c29.html'><span class='node-icon _icon-UMLClass'></span>SlicedChannelBuffer</a></span> <span>::</span> <span class="label label-info"><a href='36d826f33e205689e1576135016be694.html'><span class='node-icon _icon-UMLOperation'></span>getBytes</a></span> <span>::</span> <span class="label label-info"><a href='a4add5ac9e5fffd1580cd482e55d136d.html'><span class='node-icon _icon-UMLParameter'></span>length</a></span> </section> <!-- Diagram --> <!-- Description --> <section> <h3>Description</h3> <div> <span class="label label-info">none</span> </div> </section> <!-- Specification --> <!-- Directed Relationship --> <!-- Undirected Relationship --> <!-- Classifier --> <!-- Interface --> <!-- Component --> <!-- Node --> <!-- Actor --> <!-- Use Case --> <!-- Template Parameters --> <!-- Literals --> <!-- Attributes --> <!-- Operations --> <!-- Receptions --> <!-- Extension Points --> <!-- Parameters --> <!-- Diagrams --> <!-- Behavior --> <!-- Action --> <!-- Interaction --> <!-- CombinedFragment --> <!-- Activity --> <!-- State Machine --> <!-- State Machine --> <!-- State --> <!-- Vertex --> <!-- Transition --> <!-- Properties --> <section> <h3>Properties</h3> <table class="table table-striped table-bordered"> <tr> <th width="50%">Name</th> <th width="50%">Value</th> </tr> <tr> <td>name</td> <td>length</td> </tr> <tr> <td>stereotype</td> <td><span class='label label-info'>null</span></td> </tr> <tr> <td>visibility</td> <td>public</td> </tr> <tr> <td>isStatic</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>isLeaf</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>type</td> <td>int</td> </tr> <tr> <td>multiplicity</td> <td></td> </tr> <tr> <td>isReadOnly</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>isOrdered</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>isUnique</td> <td><span class='label label-info'>false</span></td> </tr> <tr> <td>defaultValue</td> <td></td> </tr> <tr> <td>direction</td> <td>in</td> </tr> </table> </section> <!-- Tags --> <!-- Constraints, Dependencies, Dependants --> <!-- Relationships --> <!-- Owned Elements --> </div> </body> </html>
jiangbo212/netty-init
html-docs/contents/a4add5ac9e5fffd1580cd482e55d136d.html
HTML
lgpl-2.1
7,184
# # Copyright 2015-2016 Red Hat, Inc. # # 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 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Refer to the README and COPYING files for full details of the license # from __future__ import absolute_import import collections import logging import threading Callback = collections.namedtuple('Callback', ['conn', 'dom', 'body', 'opaque']) def _null_cb(*args, **kwargs): pass _NULL = Callback(None, None, _null_cb, tuple()) class Handler(object): _log = logging.getLogger('convirt.event') _null = [_NULL] def __init__(self, name=None, parent=None): self._name = id(self) if name is None else name self._parent = parent self._lock = threading.Lock() self.events = collections.defaultdict(list) def register(self, event_id, conn, dom, func, opaque=None): with self._lock: # TODO: weakrefs? cb = Callback(conn, dom, func, opaque) # TODO: debug? self._log.info('[%s] %i -> %s', self._name, event_id, cb) self.events[event_id].append(cb) def fire(self, event_id, dom, *args): for cb in self.get_callbacks(event_id): arguments = list(args) if cb.opaque is not None: arguments.append(cb.opaque) domain = cb.dom if dom is not None: domain = dom self._log.debug('firing: %s(%s, %s, %s)', cb.body, cb.conn, domain, arguments) return cb.body(cb.conn, domain, *arguments) def get_callbacks(self, event_id): with self._lock: callback = self.events.get(event_id, None) if callback is not None: return callback if self._parent is not None: self._log.warning('[%s] unknown event %r', self._name, event_id) return self._parent.get_callbacks(event_id) # TODO: debug? self._log.warning('[%s] unhandled event %r', self._name, event_id) return self._null @property def registered(self): with self._lock: return tuple(self.events.keys()) # for testing purposes def clear(self): with self._lock: self.events.clear() root = Handler(name='root') def fire(event_id, dom, *args): global root root.fire(event_id, dom, *args)
mojaves/convirt
convirt/events.py
Python
lgpl-2.1
3,067
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qsortfilterproxymodel.h" #ifndef QT_NO_SORTFILTERPROXYMODEL #include "qitemselectionmodel.h" #include <qsize.h> #include <qdebug.h> #include <qdatetime.h> #include <qpair.h> #include <qstringlist.h> #include <private/qabstractitemmodel_p.h> #include <private/qabstractproxymodel_p.h> QT_BEGIN_NAMESPACE typedef QList<QPair<QModelIndex, QPersistentModelIndex> > QModelIndexPairList; static inline QSet<int> qVectorToSet(const QVector<int> &vector) { QSet<int> set; set.reserve(vector.size()); for(int i=0; i < vector.size(); ++i) set << vector.at(i); return set; } class QSortFilterProxyModelLessThan { public: inline QSortFilterProxyModelLessThan(int column, const QModelIndex &parent, const QAbstractItemModel *source, const QSortFilterProxyModel *proxy) : sort_column(column), source_parent(parent), source_model(source), proxy_model(proxy) {} inline bool operator()(int r1, int r2) const { QModelIndex i1 = source_model->index(r1, sort_column, source_parent); QModelIndex i2 = source_model->index(r2, sort_column, source_parent); return proxy_model->lessThan(i1, i2); } private: int sort_column; QModelIndex source_parent; const QAbstractItemModel *source_model; const QSortFilterProxyModel *proxy_model; }; class QSortFilterProxyModelGreaterThan { public: inline QSortFilterProxyModelGreaterThan(int column, const QModelIndex &parent, const QAbstractItemModel *source, const QSortFilterProxyModel *proxy) : sort_column(column), source_parent(parent), source_model(source), proxy_model(proxy) {} inline bool operator()(int r1, int r2) const { QModelIndex i1 = source_model->index(r1, sort_column, source_parent); QModelIndex i2 = source_model->index(r2, sort_column, source_parent); return proxy_model->lessThan(i2, i1); } private: int sort_column; QModelIndex source_parent; const QAbstractItemModel *source_model; const QSortFilterProxyModel *proxy_model; }; //this struct is used to store what are the rows that are removed //between a call to rowsAboutToBeRemoved and rowsRemoved //it avoids readding rows to the mapping that are currently being removed struct QRowsRemoval { QRowsRemoval(const QModelIndex &parent_source, int start, int end) : parent_source(parent_source), start(start), end(end) { } QRowsRemoval() : start(-1), end(-1) { } bool contains(QModelIndex parent, int row) { do { if (parent == parent_source) return row >= start && row <= end; row = parent.row(); parent = parent.parent(); } while (row >= 0); return false; } private: QModelIndex parent_source; int start; int end; }; class QSortFilterProxyModelPrivate : public QAbstractProxyModelPrivate { Q_DECLARE_PUBLIC(QSortFilterProxyModel) public: struct Mapping { QVector<int> source_rows; QVector<int> source_columns; QVector<int> proxy_rows; QVector<int> proxy_columns; QVector<QModelIndex> mapped_children; QHash<QModelIndex, Mapping *>::const_iterator map_iter; }; mutable QHash<QModelIndex, Mapping*> source_index_mapping; int source_sort_column; int proxy_sort_column; Qt::SortOrder sort_order; Qt::CaseSensitivity sort_casesensitivity; int sort_role; bool sort_localeaware; int filter_column; QRegExp filter_regexp; int filter_role; bool dynamic_sortfilter; QRowsRemoval itemsBeingRemoved; QModelIndexPairList saved_persistent_indexes; QHash<QModelIndex, Mapping *>::const_iterator create_mapping( const QModelIndex &source_parent) const; QModelIndex proxy_to_source(const QModelIndex &proxyIndex) const; QModelIndex source_to_proxy(const QModelIndex &sourceIndex) const; bool can_create_mapping(const QModelIndex &source_parent) const; void remove_from_mapping(const QModelIndex &source_parent); inline QHash<QModelIndex, Mapping *>::const_iterator index_to_iterator( const QModelIndex &proxy_index) const { Q_ASSERT(proxy_index.isValid()); Q_ASSERT(proxy_index.model() == q_func()); const void *p = proxy_index.internalPointer(); Q_ASSERT(p); QHash<QModelIndex, Mapping *>::const_iterator it = static_cast<const Mapping*>(p)->map_iter; Q_ASSERT(it != source_index_mapping.constEnd()); Q_ASSERT(it.value()); return it; } inline QModelIndex create_index(int row, int column, QHash<QModelIndex, Mapping*>::const_iterator it) const { return q_func()->createIndex(row, column, *it); } void _q_sourceDataChanged(const QModelIndex &source_top_left, const QModelIndex &source_bottom_right); void _q_sourceHeaderDataChanged(Qt::Orientation orientation, int start, int end); void _q_sourceAboutToBeReset(); void _q_sourceReset(); void _q_sourceLayoutAboutToBeChanged(); void _q_sourceLayoutChanged(); void _q_sourceRowsAboutToBeInserted(const QModelIndex &source_parent, int start, int end); void _q_sourceRowsInserted(const QModelIndex &source_parent, int start, int end); void _q_sourceRowsAboutToBeRemoved(const QModelIndex &source_parent, int start, int end); void _q_sourceRowsRemoved(const QModelIndex &source_parent, int start, int end); void _q_sourceColumnsAboutToBeInserted(const QModelIndex &source_parent, int start, int end); void _q_sourceColumnsInserted(const QModelIndex &source_parent, int start, int end); void _q_sourceColumnsAboutToBeRemoved(const QModelIndex &source_parent, int start, int end); void _q_sourceColumnsRemoved(const QModelIndex &source_parent, int start, int end); void clear_mapping(); void sort(); bool update_source_sort_column(); void sort_source_rows(QVector<int> &source_rows, const QModelIndex &source_parent) const; QVector<QPair<int, QVector<int > > > proxy_intervals_for_source_items_to_add( const QVector<int> &proxy_to_source, const QVector<int> &source_items, const QModelIndex &source_parent, Qt::Orientation orient) const; QVector<QPair<int, int > > proxy_intervals_for_source_items( const QVector<int> &source_to_proxy, const QVector<int> &source_items) const; void insert_source_items( QVector<int> &source_to_proxy, QVector<int> &proxy_to_source, const QVector<int> &source_items, const QModelIndex &source_parent, Qt::Orientation orient, bool emit_signal = true); void remove_source_items( QVector<int> &source_to_proxy, QVector<int> &proxy_to_source, const QVector<int> &source_items, const QModelIndex &source_parent, Qt::Orientation orient, bool emit_signal = true); void remove_proxy_interval( QVector<int> &source_to_proxy, QVector<int> &proxy_to_source, int proxy_start, int proxy_end, const QModelIndex &proxy_parent, Qt::Orientation orient, bool emit_signal = true); void build_source_to_proxy_mapping( const QVector<int> &proxy_to_source, QVector<int> &source_to_proxy) const; void source_items_inserted(const QModelIndex &source_parent, int start, int end, Qt::Orientation orient); void source_items_about_to_be_removed(const QModelIndex &source_parent, int start, int end, Qt::Orientation orient); void source_items_removed(const QModelIndex &source_parent, int start, int end, Qt::Orientation orient); void proxy_item_range( const QVector<int> &source_to_proxy, const QVector<int> &source_items, int &proxy_low, int &proxy_high) const; QModelIndexPairList store_persistent_indexes(); void update_persistent_indexes(const QModelIndexPairList &source_indexes); void filter_changed(const QModelIndex &source_parent = QModelIndex()); QSet<int> handle_filter_changed( QVector<int> &source_to_proxy, QVector<int> &proxy_to_source, const QModelIndex &source_parent, Qt::Orientation orient); void updateChildrenMapping(const QModelIndex &source_parent, Mapping *parent_mapping, Qt::Orientation orient, int start, int end, int delta_item_count, bool remove); virtual void _q_sourceModelDestroyed(); }; typedef QHash<QModelIndex, QSortFilterProxyModelPrivate::Mapping *> IndexMap; void QSortFilterProxyModelPrivate::_q_sourceModelDestroyed() { QAbstractProxyModelPrivate::_q_sourceModelDestroyed(); clear_mapping(); } void QSortFilterProxyModelPrivate::remove_from_mapping(const QModelIndex &source_parent) { if (Mapping *m = source_index_mapping.take(source_parent)) { for (int i = 0; i < m->mapped_children.size(); ++i) remove_from_mapping(m->mapped_children.at(i)); delete m; } } void QSortFilterProxyModelPrivate::clear_mapping() { // store the persistent indexes QModelIndexPairList source_indexes = store_persistent_indexes(); qDeleteAll(source_index_mapping); source_index_mapping.clear(); if (dynamic_sortfilter && update_source_sort_column()) { //update_source_sort_column might have created wrong mapping so we have to clear it again qDeleteAll(source_index_mapping); source_index_mapping.clear(); } // update the persistent indexes update_persistent_indexes(source_indexes); } IndexMap::const_iterator QSortFilterProxyModelPrivate::create_mapping( const QModelIndex &source_parent) const { Q_Q(const QSortFilterProxyModel); IndexMap::const_iterator it = source_index_mapping.constFind(source_parent); if (it != source_index_mapping.constEnd()) // was mapped already return it; Mapping *m = new Mapping; int source_rows = model->rowCount(source_parent); m->source_rows.reserve(source_rows); for (int i = 0; i < source_rows; ++i) { if (q->filterAcceptsRow(i, source_parent)) m->source_rows.append(i); } int source_cols = model->columnCount(source_parent); m->source_columns.reserve(source_cols); for (int i = 0; i < source_cols; ++i) { if (q->filterAcceptsColumn(i, source_parent)) m->source_columns.append(i); } sort_source_rows(m->source_rows, source_parent); m->proxy_rows.resize(source_rows); build_source_to_proxy_mapping(m->source_rows, m->proxy_rows); m->proxy_columns.resize(source_cols); build_source_to_proxy_mapping(m->source_columns, m->proxy_columns); it = IndexMap::const_iterator(source_index_mapping.insert(source_parent, m)); m->map_iter = it; if (source_parent.isValid()) { QModelIndex source_grand_parent = source_parent.parent(); IndexMap::const_iterator it2 = create_mapping(source_grand_parent); Q_ASSERT(it2 != source_index_mapping.constEnd()); it2.value()->mapped_children.append(source_parent); } Q_ASSERT(it != source_index_mapping.constEnd()); Q_ASSERT(it.value()); return it; } QModelIndex QSortFilterProxyModelPrivate::proxy_to_source(const QModelIndex &proxy_index) const { if (!proxy_index.isValid()) return QModelIndex(); // for now; we may want to be able to set a root index later if (proxy_index.model() != q_func()) { qWarning() << "QSortFilterProxyModel: index from wrong model passed to mapToSource"; return QModelIndex(); } IndexMap::const_iterator it = index_to_iterator(proxy_index); Mapping *m = it.value(); if ((proxy_index.row() >= m->source_rows.size()) || (proxy_index.column() >= m->source_columns.size())) return QModelIndex(); int source_row = m->source_rows.at(proxy_index.row()); int source_col = m->source_columns.at(proxy_index.column()); return model->index(source_row, source_col, it.key()); } QModelIndex QSortFilterProxyModelPrivate::source_to_proxy(const QModelIndex &source_index) const { if (!source_index.isValid()) return QModelIndex(); // for now; we may want to be able to set a root index later if (source_index.model() != model) { qWarning() << "QSortFilterProxyModel: index from wrong model passed to mapFromSource"; return QModelIndex(); } QModelIndex source_parent = source_index.parent(); IndexMap::const_iterator it = create_mapping(source_parent); Mapping *m = it.value(); if ((source_index.row() >= m->proxy_rows.size()) || (source_index.column() >= m->proxy_columns.size())) return QModelIndex(); int proxy_row = m->proxy_rows.at(source_index.row()); int proxy_column = m->proxy_columns.at(source_index.column()); if (proxy_row == -1 || proxy_column == -1) return QModelIndex(); return create_index(proxy_row, proxy_column, it); } bool QSortFilterProxyModelPrivate::can_create_mapping(const QModelIndex &source_parent) const { if (source_parent.isValid()) { QModelIndex source_grand_parent = source_parent.parent(); IndexMap::const_iterator it = source_index_mapping.constFind(source_grand_parent); if (it == source_index_mapping.constEnd()) { // Don't care, since we don't have mapping for the grand parent return false; } Mapping *gm = it.value(); if (gm->proxy_rows.at(source_parent.row()) == -1 || gm->proxy_columns.at(source_parent.column()) == -1) { // Don't care, since parent is filtered return false; } } return true; } /*! \internal Sorts the existing mappings. */ void QSortFilterProxyModelPrivate::sort() { Q_Q(QSortFilterProxyModel); emit q->layoutAboutToBeChanged(); QModelIndexPairList source_indexes = store_persistent_indexes(); IndexMap::const_iterator it = source_index_mapping.constBegin(); for (; it != source_index_mapping.constEnd(); ++it) { QModelIndex source_parent = it.key(); Mapping *m = it.value(); sort_source_rows(m->source_rows, source_parent); build_source_to_proxy_mapping(m->source_rows, m->proxy_rows); } update_persistent_indexes(source_indexes); emit q->layoutChanged(); } /*! \internal update the source_sort_column according to the proxy_sort_column return true if the column was changed */ bool QSortFilterProxyModelPrivate::update_source_sort_column() { Q_Q(QSortFilterProxyModel); QModelIndex proxy_index = q->index(0, proxy_sort_column, QModelIndex()); int old_source_sort_colum = source_sort_column; source_sort_column = q->mapToSource(proxy_index).column(); return old_source_sort_colum != source_sort_column; } /*! \internal Sorts the given \a source_rows according to current sort column and order. */ void QSortFilterProxyModelPrivate::sort_source_rows( QVector<int> &source_rows, const QModelIndex &source_parent) const { Q_Q(const QSortFilterProxyModel); if (source_sort_column >= 0) { if (sort_order == Qt::AscendingOrder) { QSortFilterProxyModelLessThan lt(source_sort_column, source_parent, model, q); qStableSort(source_rows.begin(), source_rows.end(), lt); } else { QSortFilterProxyModelGreaterThan gt(source_sort_column, source_parent, model, q); qStableSort(source_rows.begin(), source_rows.end(), gt); } } else { // restore the source model order qStableSort(source_rows.begin(), source_rows.end()); } } /*! \internal Given source-to-proxy mapping \a source_to_proxy and the set of source items \a source_items (which are part of that mapping), determines the corresponding proxy item intervals that should be removed from the proxy model. The result is a vector of pairs, where each pair represents a (start, end) tuple, sorted in ascending order. */ QVector<QPair<int, int > > QSortFilterProxyModelPrivate::proxy_intervals_for_source_items( const QVector<int> &source_to_proxy, const QVector<int> &source_items) const { QVector<QPair<int, int> > proxy_intervals; if (source_items.isEmpty()) return proxy_intervals; int source_items_index = 0; while (source_items_index < source_items.size()) { int first_proxy_item = source_to_proxy.at(source_items.at(source_items_index)); Q_ASSERT(first_proxy_item != -1); int last_proxy_item = first_proxy_item; ++source_items_index; // Find end of interval while ((source_items_index < source_items.size()) && (source_to_proxy.at(source_items.at(source_items_index)) == last_proxy_item + 1)) { ++last_proxy_item; ++source_items_index; } // Add interval to result proxy_intervals.append(QPair<int, int>(first_proxy_item, last_proxy_item)); } qStableSort(proxy_intervals.begin(), proxy_intervals.end()); return proxy_intervals; } /*! \internal Given source-to-proxy mapping \a src_to_proxy and proxy-to-source mapping \a proxy_to_source, removes \a source_items from this proxy model. The corresponding proxy items are removed in intervals, so that the proper rows/columnsRemoved(start, end) signals will be generated. */ void QSortFilterProxyModelPrivate::remove_source_items( QVector<int> &source_to_proxy, QVector<int> &proxy_to_source, const QVector<int> &source_items, const QModelIndex &source_parent, Qt::Orientation orient, bool emit_signal) { Q_Q(QSortFilterProxyModel); QModelIndex proxy_parent = q->mapFromSource(source_parent); if (!proxy_parent.isValid() && source_parent.isValid()) return; // nothing to do (already removed) QVector<QPair<int, int> > proxy_intervals; proxy_intervals = proxy_intervals_for_source_items(source_to_proxy, source_items); for (int i = proxy_intervals.size()-1; i >= 0; --i) { QPair<int, int> interval = proxy_intervals.at(i); int proxy_start = interval.first; int proxy_end = interval.second; remove_proxy_interval(source_to_proxy, proxy_to_source, proxy_start, proxy_end, proxy_parent, orient, emit_signal); } } /*! \internal Given source-to-proxy mapping \a source_to_proxy and proxy-to-source mapping \a proxy_to_source, removes items from \a proxy_start to \a proxy_end (inclusive) from this proxy model. */ void QSortFilterProxyModelPrivate::remove_proxy_interval( QVector<int> &source_to_proxy, QVector<int> &proxy_to_source, int proxy_start, int proxy_end, const QModelIndex &proxy_parent, Qt::Orientation orient, bool emit_signal) { Q_Q(QSortFilterProxyModel); if (emit_signal) { if (orient == Qt::Vertical) q->beginRemoveRows(proxy_parent, proxy_start, proxy_end); else q->beginRemoveColumns(proxy_parent, proxy_start, proxy_end); } // Remove items from proxy-to-source mapping proxy_to_source.remove(proxy_start, proxy_end - proxy_start + 1); build_source_to_proxy_mapping(proxy_to_source, source_to_proxy); if (emit_signal) { if (orient == Qt::Vertical) q->endRemoveRows(); else q->endRemoveColumns(); } } /*! \internal Given proxy-to-source mapping \a proxy_to_source and a set of unmapped source items \a source_items, determines the proxy item intervals at which the subsets of source items should be inserted (but does not actually add them to the mapping). The result is a vector of pairs, each pair representing a tuple (start, items), where items is a vector containing the (sorted) source items that should be inserted at that proxy model location. */ QVector<QPair<int, QVector<int > > > QSortFilterProxyModelPrivate::proxy_intervals_for_source_items_to_add( const QVector<int> &proxy_to_source, const QVector<int> &source_items, const QModelIndex &source_parent, Qt::Orientation orient) const { Q_Q(const QSortFilterProxyModel); QVector<QPair<int, QVector<int> > > proxy_intervals; if (source_items.isEmpty()) return proxy_intervals; int proxy_low = 0; int proxy_item = 0; int source_items_index = 0; QVector<int> source_items_in_interval; bool compare = (orient == Qt::Vertical && source_sort_column >= 0 && dynamic_sortfilter); while (source_items_index < source_items.size()) { source_items_in_interval.clear(); int first_new_source_item = source_items.at(source_items_index); source_items_in_interval.append(first_new_source_item); ++source_items_index; // Find proxy item at which insertion should be started int proxy_high = proxy_to_source.size() - 1; QModelIndex i1 = compare ? model->index(first_new_source_item, source_sort_column, source_parent) : QModelIndex(); while (proxy_low <= proxy_high) { proxy_item = (proxy_low + proxy_high) / 2; if (compare) { QModelIndex i2 = model->index(proxy_to_source.at(proxy_item), source_sort_column, source_parent); if ((sort_order == Qt::AscendingOrder) ? q->lessThan(i1, i2) : q->lessThan(i2, i1)) proxy_high = proxy_item - 1; else proxy_low = proxy_item + 1; } else { if (first_new_source_item < proxy_to_source.at(proxy_item)) proxy_high = proxy_item - 1; else proxy_low = proxy_item + 1; } } proxy_item = proxy_low; // Find the sequence of new source items that should be inserted here if (proxy_item >= proxy_to_source.size()) { for ( ; source_items_index < source_items.size(); ++source_items_index) source_items_in_interval.append(source_items.at(source_items_index)); } else { i1 = compare ? model->index(proxy_to_source.at(proxy_item), source_sort_column, source_parent) : QModelIndex(); for ( ; source_items_index < source_items.size(); ++source_items_index) { int new_source_item = source_items.at(source_items_index); if (compare) { QModelIndex i2 = model->index(new_source_item, source_sort_column, source_parent); if ((sort_order == Qt::AscendingOrder) ? q->lessThan(i1, i2) : q->lessThan(i2, i1)) break; } else { if (proxy_to_source.at(proxy_item) < new_source_item) break; } source_items_in_interval.append(new_source_item); } } // Add interval to result proxy_intervals.append(QPair<int, QVector<int> >(proxy_item, source_items_in_interval)); } return proxy_intervals; } /*! \internal Given source-to-proxy mapping \a source_to_proxy and proxy-to-source mapping \a proxy_to_source, inserts the given \a source_items into this proxy model. The source items are inserted in intervals (based on some sorted order), so that the proper rows/columnsInserted(start, end) signals will be generated. */ void QSortFilterProxyModelPrivate::insert_source_items( QVector<int> &source_to_proxy, QVector<int> &proxy_to_source, const QVector<int> &source_items, const QModelIndex &source_parent, Qt::Orientation orient, bool emit_signal) { Q_Q(QSortFilterProxyModel); QModelIndex proxy_parent = q->mapFromSource(source_parent); if (!proxy_parent.isValid() && source_parent.isValid()) return; // nothing to do (source_parent is not mapped) QVector<QPair<int, QVector<int> > > proxy_intervals; proxy_intervals = proxy_intervals_for_source_items_to_add( proxy_to_source, source_items, source_parent, orient); for (int i = proxy_intervals.size()-1; i >= 0; --i) { QPair<int, QVector<int> > interval = proxy_intervals.at(i); int proxy_start = interval.first; QVector<int> source_items = interval.second; int proxy_end = proxy_start + source_items.size() - 1; if (emit_signal) { if (orient == Qt::Vertical) q->beginInsertRows(proxy_parent, proxy_start, proxy_end); else q->beginInsertColumns(proxy_parent, proxy_start, proxy_end); } for (int i = 0; i < source_items.size(); ++i) proxy_to_source.insert(proxy_start + i, source_items.at(i)); build_source_to_proxy_mapping(proxy_to_source, source_to_proxy); if (emit_signal) { if (orient == Qt::Vertical) q->endInsertRows(); else q->endInsertColumns(); } } } /*! \internal Handles source model items insertion (columnsInserted(), rowsInserted()). Determines 1) which of the inserted items to also insert into proxy model (filtering), 2) where to insert the items into the proxy model (sorting), then inserts those items. The items are inserted into the proxy model in intervals (based on sorted order), so that the proper rows/columnsInserted(start, end) signals will be generated. */ void QSortFilterProxyModelPrivate::source_items_inserted( const QModelIndex &source_parent, int start, int end, Qt::Orientation orient) { Q_Q(QSortFilterProxyModel); if ((start < 0) || (end < 0)) return; IndexMap::const_iterator it = source_index_mapping.constFind(source_parent); if (it == source_index_mapping.constEnd()) { if (!can_create_mapping(source_parent)) return; it = create_mapping(source_parent); Mapping *m = it.value(); QModelIndex proxy_parent = q->mapFromSource(source_parent); if (m->source_rows.count() > 0) { q->beginInsertRows(proxy_parent, 0, m->source_rows.count() - 1); q->endInsertRows(); } if (m->source_columns.count() > 0) { q->beginInsertColumns(proxy_parent, 0, m->source_columns.count() - 1); q->endInsertColumns(); } return; } Mapping *m = it.value(); QVector<int> &source_to_proxy = (orient == Qt::Vertical) ? m->proxy_rows : m->proxy_columns; QVector<int> &proxy_to_source = (orient == Qt::Vertical) ? m->source_rows : m->source_columns; int delta_item_count = end - start + 1; int old_item_count = source_to_proxy.size(); updateChildrenMapping(source_parent, m, orient, start, end, delta_item_count, false); // Expand source-to-proxy mapping to account for new items if (start < 0 || start > source_to_proxy.size()) { qWarning("QSortFilterProxyModel: invalid inserted rows reported by source model"); remove_from_mapping(source_parent); return; } source_to_proxy.insert(start, delta_item_count, -1); if (start < old_item_count) { // Adjust existing "stale" indexes in proxy-to-source mapping int proxy_count = proxy_to_source.size(); for (int proxy_item = 0; proxy_item < proxy_count; ++proxy_item) { int source_item = proxy_to_source.at(proxy_item); if (source_item >= start) proxy_to_source.replace(proxy_item, source_item + delta_item_count); } build_source_to_proxy_mapping(proxy_to_source, source_to_proxy); } // Figure out which items to add to mapping based on filter QVector<int> source_items; for (int i = start; i <= end; ++i) { if ((orient == Qt::Vertical) ? q->filterAcceptsRow(i, source_parent) : q->filterAcceptsColumn(i, source_parent)) { source_items.append(i); } } if (model->rowCount(source_parent) == delta_item_count) { // Items were inserted where there were none before. // If it was new rows make sure to create mappings for columns so that a // valid mapping can be retrieved later and vice-versa. QVector<int> &orthogonal_proxy_to_source = (orient == Qt::Horizontal) ? m->source_rows : m->source_columns; QVector<int> &orthogonal_source_to_proxy = (orient == Qt::Horizontal) ? m->proxy_rows : m->proxy_columns; if (orthogonal_source_to_proxy.isEmpty()) { const int ortho_end = (orient == Qt::Horizontal) ? model->rowCount(source_parent) : model->columnCount(source_parent); for (int ortho_item = 0; ortho_item < ortho_end; ++ortho_item) { if ((orient == Qt::Horizontal) ? q->filterAcceptsRow(ortho_item, source_parent) : q->filterAcceptsColumn(ortho_item, source_parent)) { orthogonal_proxy_to_source.append(ortho_item); } } orthogonal_source_to_proxy.resize(orthogonal_proxy_to_source.size()); if (orient == Qt::Horizontal) { // We're reacting to columnsInserted, but we've just inserted new rows. Sort them. sort_source_rows(orthogonal_proxy_to_source, source_parent); } build_source_to_proxy_mapping(orthogonal_proxy_to_source, orthogonal_source_to_proxy); } } // Sort and insert the items if (orient == Qt::Vertical) // Only sort rows sort_source_rows(source_items, source_parent); insert_source_items(source_to_proxy, proxy_to_source, source_items, source_parent, orient); } /*! \internal Handles source model items removal (columnsAboutToBeRemoved(), rowsAboutToBeRemoved()). */ void QSortFilterProxyModelPrivate::source_items_about_to_be_removed( const QModelIndex &source_parent, int start, int end, Qt::Orientation orient) { if ((start < 0) || (end < 0)) return; IndexMap::const_iterator it = source_index_mapping.constFind(source_parent); if (it == source_index_mapping.constEnd()) { // Don't care, since we don't have mapping for this index return; } Mapping *m = it.value(); QVector<int> &source_to_proxy = (orient == Qt::Vertical) ? m->proxy_rows : m->proxy_columns; QVector<int> &proxy_to_source = (orient == Qt::Vertical) ? m->source_rows : m->source_columns; // figure out which items to remove QVector<int> source_items_to_remove; int proxy_count = proxy_to_source.size(); for (int proxy_item = 0; proxy_item < proxy_count; ++proxy_item) { int source_item = proxy_to_source.at(proxy_item); if ((source_item >= start) && (source_item <= end)) source_items_to_remove.append(source_item); } remove_source_items(source_to_proxy, proxy_to_source, source_items_to_remove, source_parent, orient); } /*! \internal Handles source model items removal (columnsRemoved(), rowsRemoved()). */ void QSortFilterProxyModelPrivate::source_items_removed( const QModelIndex &source_parent, int start, int end, Qt::Orientation orient) { if ((start < 0) || (end < 0)) return; IndexMap::const_iterator it = source_index_mapping.constFind(source_parent); if (it == source_index_mapping.constEnd()) { // Don't care, since we don't have mapping for this index return; } Mapping *m = it.value(); QVector<int> &source_to_proxy = (orient == Qt::Vertical) ? m->proxy_rows : m->proxy_columns; QVector<int> &proxy_to_source = (orient == Qt::Vertical) ? m->source_rows : m->source_columns; if (end >= source_to_proxy.size()) end = source_to_proxy.size() - 1; // Shrink the source-to-proxy mapping to reflect the new item count int delta_item_count = end - start + 1; source_to_proxy.remove(start, delta_item_count); int proxy_count = proxy_to_source.size(); if (proxy_count > source_to_proxy.size()) { // mapping is in an inconsistent state -- redo the whole mapping qWarning("QSortFilterProxyModel: inconsistent changes reported by source model"); remove_from_mapping(source_parent); Q_Q(QSortFilterProxyModel); q->reset(); return; } // Adjust "stale" indexes in proxy-to-source mapping for (int proxy_item = 0; proxy_item < proxy_count; ++proxy_item) { int source_item = proxy_to_source.at(proxy_item); if (source_item >= start) { Q_ASSERT(source_item - delta_item_count >= 0); proxy_to_source.replace(proxy_item, source_item - delta_item_count); } } build_source_to_proxy_mapping(proxy_to_source, source_to_proxy); updateChildrenMapping(source_parent, m, orient, start, end, delta_item_count, true); } /*! \internal updates the mapping of the children when inserting or removing items */ void QSortFilterProxyModelPrivate::updateChildrenMapping(const QModelIndex &source_parent, Mapping *parent_mapping, Qt::Orientation orient, int start, int end, int delta_item_count, bool remove) { // see if any mapped children should be (re)moved QVector<QPair<QModelIndex, Mapping*> > moved_source_index_mappings; QVector<QModelIndex>::iterator it2 = parent_mapping->mapped_children.begin(); for ( ; it2 != parent_mapping->mapped_children.end();) { const QModelIndex source_child_index = *it2; const int pos = (orient == Qt::Vertical) ? source_child_index.row() : source_child_index.column(); if (pos < start) { // not affected ++it2; } else if (remove && pos <= end) { // in the removed interval it2 = parent_mapping->mapped_children.erase(it2); remove_from_mapping(source_child_index); } else { // below the removed items -- recompute the index QModelIndex new_index; const int newpos = remove ? pos - delta_item_count : pos + delta_item_count; if (orient == Qt::Vertical) { new_index = model->index(newpos, source_child_index.column(), source_parent); } else { new_index = model->index(source_child_index.row(), newpos, source_parent); } *it2 = new_index; ++it2; // update mapping Mapping *cm = source_index_mapping.take(source_child_index); Q_ASSERT(cm); // we do not reinsert right away, because the new index might be identical with another, old index moved_source_index_mappings.append(QPair<QModelIndex, Mapping*>(new_index, cm)); } } // reinsert moved, mapped indexes QVector<QPair<QModelIndex, Mapping*> >::iterator it = moved_source_index_mappings.begin(); for (; it != moved_source_index_mappings.end(); ++it) { #ifdef QT_STRICT_ITERATORS source_index_mapping.insert((*it).first, (*it).second); (*it).second->map_iter = source_index_mapping.constFind((*it).first); #else (*it).second->map_iter = source_index_mapping.insert((*it).first, (*it).second); #endif } } /*! \internal */ void QSortFilterProxyModelPrivate::proxy_item_range( const QVector<int> &source_to_proxy, const QVector<int> &source_items, int &proxy_low, int &proxy_high) const { proxy_low = INT_MAX; proxy_high = INT_MIN; for (int i = 0; i < source_items.count(); ++i) { int proxy_item = source_to_proxy.at(source_items.at(i)); Q_ASSERT(proxy_item != -1); if (proxy_item < proxy_low) proxy_low = proxy_item; if (proxy_item > proxy_high) proxy_high = proxy_item; } } /*! \internal */ void QSortFilterProxyModelPrivate::build_source_to_proxy_mapping( const QVector<int> &proxy_to_source, QVector<int> &source_to_proxy) const { source_to_proxy.fill(-1); int proxy_count = proxy_to_source.size(); for (int i = 0; i < proxy_count; ++i) source_to_proxy[proxy_to_source.at(i)] = i; } /*! \internal Maps the persistent proxy indexes to source indexes and returns the list of source indexes. */ QModelIndexPairList QSortFilterProxyModelPrivate::store_persistent_indexes() { Q_Q(QSortFilterProxyModel); QModelIndexPairList source_indexes; foreach (QPersistentModelIndexData *data, persistent.indexes) { QModelIndex proxy_index = data->index; QModelIndex source_index = q->mapToSource(proxy_index); source_indexes.append(qMakePair(proxy_index, QPersistentModelIndex(source_index))); } return source_indexes; } /*! \internal Maps \a source_indexes to proxy indexes and stores those as persistent indexes. */ void QSortFilterProxyModelPrivate::update_persistent_indexes( const QModelIndexPairList &source_indexes) { Q_Q(QSortFilterProxyModel); QModelIndexList from, to; for (int i = 0; i < source_indexes.count(); ++i) { QModelIndex source_index = source_indexes.at(i).second; QModelIndex old_proxy_index = source_indexes.at(i).first; create_mapping(source_index.parent()); QModelIndex proxy_index = q->mapFromSource(source_index); from << old_proxy_index; to << proxy_index; } q->changePersistentIndexList(from, to); } /*! \internal Updates the proxy model (adds/removes rows) based on the new filter. */ void QSortFilterProxyModelPrivate::filter_changed(const QModelIndex &source_parent) { IndexMap::const_iterator it = source_index_mapping.constFind(source_parent); if (it == source_index_mapping.constEnd()) return; Mapping *m = it.value(); QSet<int> rows_removed = handle_filter_changed(m->proxy_rows, m->source_rows, source_parent, Qt::Vertical); QSet<int> columns_removed = handle_filter_changed(m->proxy_columns, m->source_columns, source_parent, Qt::Horizontal); QVector<QModelIndex>::iterator it2 = m->mapped_children.end(); while (it2 != m->mapped_children.begin()) { --it2; const QModelIndex source_child_index = *it2; if (rows_removed.contains(source_child_index.row()) || columns_removed.contains(source_child_index.column())) { it2 = m->mapped_children.erase(it2); remove_from_mapping(source_child_index); } else { filter_changed(source_child_index); } } } /*! \internal returns the removed items indexes */ QSet<int> QSortFilterProxyModelPrivate::handle_filter_changed( QVector<int> &source_to_proxy, QVector<int> &proxy_to_source, const QModelIndex &source_parent, Qt::Orientation orient) { Q_Q(QSortFilterProxyModel); // Figure out which mapped items to remove QVector<int> source_items_remove; for (int i = 0; i < proxy_to_source.count(); ++i) { const int source_item = proxy_to_source.at(i); if ((orient == Qt::Vertical) ? !q->filterAcceptsRow(source_item, source_parent) : !q->filterAcceptsColumn(source_item, source_parent)) { // This source item does not satisfy the filter, so it must be removed source_items_remove.append(source_item); } } // Figure out which non-mapped items to insert QVector<int> source_items_insert; int source_count = source_to_proxy.size(); for (int source_item = 0; source_item < source_count; ++source_item) { if (source_to_proxy.at(source_item) == -1) { if ((orient == Qt::Vertical) ? q->filterAcceptsRow(source_item, source_parent) : q->filterAcceptsColumn(source_item, source_parent)) { // This source item satisfies the filter, so it must be added source_items_insert.append(source_item); } } } if (!source_items_remove.isEmpty() || !source_items_insert.isEmpty()) { // Do item removal and insertion remove_source_items(source_to_proxy, proxy_to_source, source_items_remove, source_parent, orient); if (orient == Qt::Vertical) sort_source_rows(source_items_insert, source_parent); insert_source_items(source_to_proxy, proxy_to_source, source_items_insert, source_parent, orient); } return qVectorToSet(source_items_remove); } void QSortFilterProxyModelPrivate::_q_sourceDataChanged(const QModelIndex &source_top_left, const QModelIndex &source_bottom_right) { Q_Q(QSortFilterProxyModel); if (!source_top_left.isValid() || !source_bottom_right.isValid()) return; QModelIndex source_parent = source_top_left.parent(); IndexMap::const_iterator it = source_index_mapping.find(source_parent); if (it == source_index_mapping.constEnd()) { // Don't care, since we don't have mapping for this index return; } Mapping *m = it.value(); // Figure out how the source changes affect us QVector<int> source_rows_remove; QVector<int> source_rows_insert; QVector<int> source_rows_change; QVector<int> source_rows_resort; int end = qMin(source_bottom_right.row(), m->proxy_rows.count() - 1); for (int source_row = source_top_left.row(); source_row <= end; ++source_row) { if (dynamic_sortfilter) { if (m->proxy_rows.at(source_row) != -1) { if (!q->filterAcceptsRow(source_row, source_parent)) { // This source row no longer satisfies the filter, so it must be removed source_rows_remove.append(source_row); } else if (source_sort_column >= source_top_left.column() && source_sort_column <= source_bottom_right.column()) { // This source row has changed in a way that may affect sorted order source_rows_resort.append(source_row); } else { // This row has simply changed, without affecting filtering nor sorting source_rows_change.append(source_row); } } else { if (!itemsBeingRemoved.contains(source_parent, source_row) && q->filterAcceptsRow(source_row, source_parent)) { // This source row now satisfies the filter, so it must be added source_rows_insert.append(source_row); } } } else { if (m->proxy_rows.at(source_row) != -1) source_rows_change.append(source_row); } } if (!source_rows_remove.isEmpty()) { remove_source_items(m->proxy_rows, m->source_rows, source_rows_remove, source_parent, Qt::Vertical); QSet<int> source_rows_remove_set = qVectorToSet(source_rows_remove); QVector<QModelIndex>::iterator it = m->mapped_children.end(); while (it != m->mapped_children.begin()) { --it; const QModelIndex source_child_index = *it; if (source_rows_remove_set.contains(source_child_index.row())) { it = m->mapped_children.erase(it); remove_from_mapping(source_child_index); } } } if (!source_rows_resort.isEmpty()) { // Re-sort the rows emit q->layoutAboutToBeChanged(); QModelIndexPairList source_indexes = store_persistent_indexes(); remove_source_items(m->proxy_rows, m->source_rows, source_rows_resort, source_parent, Qt::Vertical, false); sort_source_rows(source_rows_resort, source_parent); insert_source_items(m->proxy_rows, m->source_rows, source_rows_resort, source_parent, Qt::Vertical, false); update_persistent_indexes(source_indexes); emit q->layoutChanged(); // Make sure we also emit dataChanged for the rows source_rows_change += source_rows_resort; } if (!source_rows_change.isEmpty()) { // Find the proxy row range int proxy_start_row; int proxy_end_row; proxy_item_range(m->proxy_rows, source_rows_change, proxy_start_row, proxy_end_row); // ### Find the proxy column range also if (proxy_end_row >= 0) { // the row was accepted, but some columns might still be filtered out int source_left_column = source_top_left.column(); while (source_left_column < source_bottom_right.column() && m->proxy_columns.at(source_left_column) == -1) ++source_left_column; const QModelIndex proxy_top_left = create_index( proxy_start_row, m->proxy_columns.at(source_left_column), it); int source_right_column = source_bottom_right.column(); while (source_right_column > source_top_left.column() && m->proxy_columns.at(source_right_column) == -1) --source_right_column; const QModelIndex proxy_bottom_right = create_index( proxy_end_row, m->proxy_columns.at(source_right_column), it); emit q->dataChanged(proxy_top_left, proxy_bottom_right); } } if (!source_rows_insert.isEmpty()) { sort_source_rows(source_rows_insert, source_parent); insert_source_items(m->proxy_rows, m->source_rows, source_rows_insert, source_parent, Qt::Vertical); } } void QSortFilterProxyModelPrivate::_q_sourceHeaderDataChanged(Qt::Orientation orientation, int start, int end) { Q_Q(QSortFilterProxyModel); Mapping *m = create_mapping(QModelIndex()).value(); int proxy_start = (orientation == Qt::Vertical ? m->proxy_rows.at(start) : m->proxy_columns.at(start)); int proxy_end = (orientation == Qt::Vertical ? m->proxy_rows.at(end) : m->proxy_columns.at(end)); emit q->headerDataChanged(orientation, proxy_start, proxy_end); } void QSortFilterProxyModelPrivate::_q_sourceAboutToBeReset() { Q_Q(QSortFilterProxyModel); q->beginResetModel(); } void QSortFilterProxyModelPrivate::_q_sourceReset() { Q_Q(QSortFilterProxyModel); invalidatePersistentIndexes(); clear_mapping(); // All internal structures are deleted in clear() q->endResetModel(); update_source_sort_column(); if (dynamic_sortfilter) sort(); } void QSortFilterProxyModelPrivate::_q_sourceLayoutAboutToBeChanged() { Q_Q(QSortFilterProxyModel); saved_persistent_indexes.clear(); emit q->layoutAboutToBeChanged(); if (persistent.indexes.isEmpty()) return; saved_persistent_indexes = store_persistent_indexes(); } void QSortFilterProxyModelPrivate::_q_sourceLayoutChanged() { Q_Q(QSortFilterProxyModel); qDeleteAll(source_index_mapping); source_index_mapping.clear(); update_persistent_indexes(saved_persistent_indexes); saved_persistent_indexes.clear(); if (dynamic_sortfilter && update_source_sort_column()) { //update_source_sort_column might have created wrong mapping so we have to clear it again qDeleteAll(source_index_mapping); source_index_mapping.clear(); } emit q->layoutChanged(); } void QSortFilterProxyModelPrivate::_q_sourceRowsAboutToBeInserted( const QModelIndex &source_parent, int start, int end) { Q_UNUSED(start); Q_UNUSED(end); //Force the creation of a mapping now, even if its empty. //We need it because the proxy can be acessed at the moment it emits rowsAboutToBeInserted in insert_source_items if (can_create_mapping(source_parent)) create_mapping(source_parent); } void QSortFilterProxyModelPrivate::_q_sourceRowsInserted( const QModelIndex &source_parent, int start, int end) { source_items_inserted(source_parent, start, end, Qt::Vertical); if (update_source_sort_column() && dynamic_sortfilter) //previous call to update_source_sort_column may fail if the model has no column. sort(); // now it should succeed so we need to make sure to sort again } void QSortFilterProxyModelPrivate::_q_sourceRowsAboutToBeRemoved( const QModelIndex &source_parent, int start, int end) { itemsBeingRemoved = QRowsRemoval(source_parent, start, end); source_items_about_to_be_removed(source_parent, start, end, Qt::Vertical); } void QSortFilterProxyModelPrivate::_q_sourceRowsRemoved( const QModelIndex &source_parent, int start, int end) { itemsBeingRemoved = QRowsRemoval(); source_items_removed(source_parent, start, end, Qt::Vertical); } void QSortFilterProxyModelPrivate::_q_sourceColumnsAboutToBeInserted( const QModelIndex &source_parent, int start, int end) { Q_UNUSED(start); Q_UNUSED(end); //Force the creation of a mapping now, even if its empty. //We need it because the proxy can be acessed at the moment it emits columnsAboutToBeInserted in insert_source_items if (can_create_mapping(source_parent)) create_mapping(source_parent); } void QSortFilterProxyModelPrivate::_q_sourceColumnsInserted( const QModelIndex &source_parent, int start, int end) { Q_Q(const QSortFilterProxyModel); source_items_inserted(source_parent, start, end, Qt::Horizontal); if (source_parent.isValid()) return; //we sort according to the root column only if (source_sort_column == -1) { //we update the source_sort_column depending on the proxy_sort_column if (update_source_sort_column() && dynamic_sortfilter) sort(); } else { if (start <= source_sort_column) source_sort_column += end - start + 1; proxy_sort_column = q->mapFromSource(model->index(0,source_sort_column, source_parent)).column(); } } void QSortFilterProxyModelPrivate::_q_sourceColumnsAboutToBeRemoved( const QModelIndex &source_parent, int start, int end) { source_items_about_to_be_removed(source_parent, start, end, Qt::Horizontal); } void QSortFilterProxyModelPrivate::_q_sourceColumnsRemoved( const QModelIndex &source_parent, int start, int end) { Q_Q(const QSortFilterProxyModel); source_items_removed(source_parent, start, end, Qt::Horizontal); if (source_parent.isValid()) return; //we sort according to the root column only if (start <= source_sort_column) { if (end < source_sort_column) source_sort_column -= end - start + 1; else source_sort_column = -1; } proxy_sort_column = q->mapFromSource(model->index(0,source_sort_column, source_parent)).column(); } /*! \since 4.1 \class QSortFilterProxyModel \brief The QSortFilterProxyModel class provides support for sorting and filtering data passed between another model and a view. \ingroup model-view QSortFilterProxyModel can be used for sorting items, filtering out items, or both. The model transforms the structure of a source model by mapping the model indexes it supplies to new indexes, corresponding to different locations, for views to use. This approach allows a given source model to be restructured as far as views are concerned without requiring any transformations on the underlying data, and without duplicating the data in memory. Let's assume that we want to sort and filter the items provided by a custom model. The code to set up the model and the view, \e without sorting and filtering, would look like this: \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 1 To add sorting and filtering support to \c MyItemModel, we need to create a QSortFilterProxyModel, call setSourceModel() with the \c MyItemModel as argument, and install the QSortFilterProxyModel on the view: \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 0 \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 2 At this point, neither sorting nor filtering is enabled; the original data is displayed in the view. Any changes made through the QSortFilterProxyModel are applied to the original model. The QSortFilterProxyModel acts as a wrapper for the original model. If you need to convert source \l{QModelIndex}es to sorted/filtered model indexes or vice versa, use mapToSource(), mapFromSource(), mapSelectionToSource(), and mapSelectionFromSource(). \note By default, the model does not dynamically re-sort and re-filter data whenever the original model changes. This behavior can be changed by setting the \l{QSortFilterProxyModel::dynamicSortFilter}{dynamicSortFilter} property. The \l{itemviews/basicsortfiltermodel}{Basic Sort/Filter Model} and \l{itemviews/customsortfiltermodel}{Custom Sort/Filter Model} examples illustrate how to use QSortFilterProxyModel to perform basic sorting and filtering and how to subclass it to implement custom behavior. \section1 Sorting QTableView and QTreeView have a \l{QTreeView::sortingEnabled}{sortingEnabled} property that controls whether the user can sort the view by clicking the view's horizontal header. For example: \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 3 When this feature is on (the default is off), clicking on a header section sorts the items according to that column. By clicking repeatedly, the user can alternate between ascending and descending order. \image qsortfilterproxymodel-sorting.png A sorted QTreeView Behind the scene, the view calls the sort() virtual function on the model to reorder the data in the model. To make your data sortable, you can either implement sort() in your model, or use a QSortFilterProxyModel to wrap your model -- QSortFilterProxyModel provides a generic sort() reimplementation that operates on the sortRole() (Qt::DisplayRole by default) of the items and that understands several data types, including \c int, QString, and QDateTime. For hierarchical models, sorting is applied recursively to all child items. String comparisons are case sensitive by default; this can be changed by setting the \l{QSortFilterProxyModel::} {sortCaseSensitivity} property. Custom sorting behavior is achieved by subclassing QSortFilterProxyModel and reimplementing lessThan(), which is used to compare items. For example: \snippet examples/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp 5 (This code snippet comes from the \l{itemviews/customsortfiltermodel}{Custom Sort/Filter Model} example.) An alternative approach to sorting is to disable sorting on the view and to impose a certain order to the user. This is done by explicitly calling sort() with the desired column and order as arguments on the QSortFilterProxyModel (or on the original model if it implements sort()). For example: \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 4 QSortFilterProxyModel can be sorted by column -1, in which case it returns to the sort order of the underlying source model. \section1 Filtering In addition to sorting, QSortFilterProxyModel can be used to hide items that do not match a certain filter. The filter is specified using a QRegExp object and is applied to the filterRole() (Qt::DisplayRole by default) of each item, for a given column. The QRegExp object can be used to match a regular expression, a wildcard pattern, or a fixed string. For example: \snippet doc/src/snippets/qsortfilterproxymodel-details/main.cpp 5 For hierarchical models, the filter is applied recursively to all children. If a parent item doesn't match the filter, none of its children will be shown. A common use case is to let the user specify the filter regexp, wildcard pattern, or fixed string in a QLineEdit and to connect the \l{QLineEdit::textChanged()}{textChanged()} signal to setFilterRegExp(), setFilterWildcard(), or setFilterFixedString() to reapply the filter. Custom filtering behavior can be achieved by reimplementing the filterAcceptsRow() and filterAcceptsColumn() functions. For example (from the \l{itemviews/customsortfiltermodel} {Custom Sort/Filter Model} example), the following implementation ignores the \l{QSortFilterProxyModel::filterKeyColumn}{filterKeyColumn} property and performs filtering on columns 0, 1, and 2: \snippet examples/itemviews/customsortfiltermodel/mysortfilterproxymodel.cpp 3 (This code snippet comes from the \l{itemviews/customsortfiltermodel}{Custom Sort/Filter Model} example.) If you are working with large amounts of filtering and have to invoke invalidateFilter() repeatedly, using reset() may be more efficient, depending on the implementation of your model. However, reset() returns the proxy model to its original state, losing selection information, and will cause the proxy model to be repopulated. \section1 Subclassing Since QAbstractProxyModel and its subclasses are derived from QAbstractItemModel, much of the same advice about subclassing normal models also applies to proxy models. In addition, it is worth noting that many of the default implementations of functions in this class are written so that they call the equivalent functions in the relevant source model. This simple proxying mechanism may need to be overridden for source models with more complex behavior; for example, if the source model provides a custom hasChildren() implementation, you should also provide one in the proxy model. \note Some general guidelines for subclassing models are available in the \l{Model Subclassing Reference}. \sa QAbstractProxyModel, QAbstractItemModel, {Model/View Programming}, {Basic Sort/Filter Model Example}, {Custom Sort/Filter Model Example} */ /*! Constructs a sorting filter model with the given \a parent. */ QSortFilterProxyModel::QSortFilterProxyModel(QObject *parent) : QAbstractProxyModel(*new QSortFilterProxyModelPrivate, parent) { Q_D(QSortFilterProxyModel); d->proxy_sort_column = d->source_sort_column = -1; d->sort_order = Qt::AscendingOrder; d->sort_casesensitivity = Qt::CaseSensitive; d->sort_role = Qt::DisplayRole; d->sort_localeaware = false; d->filter_column = 0; d->filter_role = Qt::DisplayRole; d->dynamic_sortfilter = false; } /*! Destroys this sorting filter model. */ QSortFilterProxyModel::~QSortFilterProxyModel() { Q_D(QSortFilterProxyModel); qDeleteAll(d->source_index_mapping); d->source_index_mapping.clear(); } /*! \reimp */ void QSortFilterProxyModel::setSourceModel(QAbstractItemModel *sourceModel) { Q_D(QSortFilterProxyModel); beginResetModel(); disconnect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(_q_sourceDataChanged(QModelIndex,QModelIndex))); disconnect(d->model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)), this, SLOT(_q_sourceHeaderDataChanged(Qt::Orientation,int,int))); disconnect(d->model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), this, SLOT(_q_sourceRowsAboutToBeInserted(QModelIndex,int,int))); disconnect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(_q_sourceRowsInserted(QModelIndex,int,int))); disconnect(d->model, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)), this, SLOT(_q_sourceColumnsAboutToBeInserted(QModelIndex,int,int))); disconnect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)), this, SLOT(_q_sourceColumnsInserted(QModelIndex,int,int))); disconnect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(_q_sourceRowsAboutToBeRemoved(QModelIndex,int,int))); disconnect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(_q_sourceRowsRemoved(QModelIndex,int,int))); disconnect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(_q_sourceColumnsAboutToBeRemoved(QModelIndex,int,int))); disconnect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)), this, SLOT(_q_sourceColumnsRemoved(QModelIndex,int,int))); disconnect(d->model, SIGNAL(layoutAboutToBeChanged()), this, SLOT(_q_sourceLayoutAboutToBeChanged())); disconnect(d->model, SIGNAL(layoutChanged()), this, SLOT(_q_sourceLayoutChanged())); disconnect(d->model, SIGNAL(modelAboutToBeReset()), this, SLOT(_q_sourceAboutToBeReset())); disconnect(d->model, SIGNAL(modelReset()), this, SLOT(_q_sourceReset())); QAbstractProxyModel::setSourceModel(sourceModel); connect(d->model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(_q_sourceDataChanged(QModelIndex,QModelIndex))); connect(d->model, SIGNAL(headerDataChanged(Qt::Orientation,int,int)), this, SLOT(_q_sourceHeaderDataChanged(Qt::Orientation,int,int))); connect(d->model, SIGNAL(rowsAboutToBeInserted(QModelIndex,int,int)), this, SLOT(_q_sourceRowsAboutToBeInserted(QModelIndex,int,int))); connect(d->model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(_q_sourceRowsInserted(QModelIndex,int,int))); connect(d->model, SIGNAL(columnsAboutToBeInserted(QModelIndex,int,int)), this, SLOT(_q_sourceColumnsAboutToBeInserted(QModelIndex,int,int))); connect(d->model, SIGNAL(columnsInserted(QModelIndex,int,int)), this, SLOT(_q_sourceColumnsInserted(QModelIndex,int,int))); connect(d->model, SIGNAL(rowsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(_q_sourceRowsAboutToBeRemoved(QModelIndex,int,int))); connect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(_q_sourceRowsRemoved(QModelIndex,int,int))); connect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)), this, SLOT(_q_sourceColumnsAboutToBeRemoved(QModelIndex,int,int))); connect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)), this, SLOT(_q_sourceColumnsRemoved(QModelIndex,int,int))); connect(d->model, SIGNAL(layoutAboutToBeChanged()), this, SLOT(_q_sourceLayoutAboutToBeChanged())); connect(d->model, SIGNAL(layoutChanged()), this, SLOT(_q_sourceLayoutChanged())); connect(d->model, SIGNAL(modelAboutToBeReset()), this, SLOT(_q_sourceAboutToBeReset())); connect(d->model, SIGNAL(modelReset()), this, SLOT(_q_sourceReset())); d->clear_mapping(); endResetModel(); if (d->update_source_sort_column() && d->dynamic_sortfilter) d->sort(); } /*! \reimp */ QModelIndex QSortFilterProxyModel::index(int row, int column, const QModelIndex &parent) const { Q_D(const QSortFilterProxyModel); if (row < 0 || column < 0) return QModelIndex(); QModelIndex source_parent = mapToSource(parent); // parent is already mapped at this point IndexMap::const_iterator it = d->create_mapping(source_parent); // but make sure that the children are mapped if (it.value()->source_rows.count() <= row || it.value()->source_columns.count() <= column) return QModelIndex(); return d->create_index(row, column, it); } /*! \reimp */ QModelIndex QSortFilterProxyModel::parent(const QModelIndex &child) const { Q_D(const QSortFilterProxyModel); if (!d->indexValid(child)) return QModelIndex(); IndexMap::const_iterator it = d->index_to_iterator(child); Q_ASSERT(it != d->source_index_mapping.constEnd()); QModelIndex source_parent = it.key(); QModelIndex proxy_parent = mapFromSource(source_parent); return proxy_parent; } /*! \reimp */ int QSortFilterProxyModel::rowCount(const QModelIndex &parent) const { Q_D(const QSortFilterProxyModel); QModelIndex source_parent = mapToSource(parent); if (parent.isValid() && !source_parent.isValid()) return 0; IndexMap::const_iterator it = d->create_mapping(source_parent); return it.value()->source_rows.count(); } /*! \reimp */ int QSortFilterProxyModel::columnCount(const QModelIndex &parent) const { Q_D(const QSortFilterProxyModel); QModelIndex source_parent = mapToSource(parent); if (parent.isValid() && !source_parent.isValid()) return 0; IndexMap::const_iterator it = d->create_mapping(source_parent); return it.value()->source_columns.count(); } /*! \reimp */ bool QSortFilterProxyModel::hasChildren(const QModelIndex &parent) const { Q_D(const QSortFilterProxyModel); QModelIndex source_parent = mapToSource(parent); if (parent.isValid() && !source_parent.isValid()) return false; if (!d->model->hasChildren(source_parent)) return false; if (d->model->canFetchMore(source_parent)) return true; //we assume we might have children that can be fetched QSortFilterProxyModelPrivate::Mapping *m = d->create_mapping(source_parent).value(); return m->source_rows.count() != 0 && m->source_columns.count() != 0; } /*! \reimp */ QVariant QSortFilterProxyModel::data(const QModelIndex &index, int role) const { Q_D(const QSortFilterProxyModel); QModelIndex source_index = mapToSource(index); if (index.isValid() && !source_index.isValid()) return QVariant(); return d->model->data(source_index, role); } /*! \reimp */ bool QSortFilterProxyModel::setData(const QModelIndex &index, const QVariant &value, int role) { Q_D(QSortFilterProxyModel); QModelIndex source_index = mapToSource(index); if (index.isValid() && !source_index.isValid()) return false; return d->model->setData(source_index, value, role); } /*! \reimp */ QVariant QSortFilterProxyModel::headerData(int section, Qt::Orientation orientation, int role) const { Q_D(const QSortFilterProxyModel); IndexMap::const_iterator it = d->create_mapping(QModelIndex()); if (it.value()->source_rows.count() * it.value()->source_columns.count() > 0) return QAbstractProxyModel::headerData(section, orientation, role); int source_section; if (orientation == Qt::Vertical) { if (section < 0 || section >= it.value()->source_rows.count()) return QVariant(); source_section = it.value()->source_rows.at(section); } else { if (section < 0 || section >= it.value()->source_columns.count()) return QVariant(); source_section = it.value()->source_columns.at(section); } return d->model->headerData(source_section, orientation, role); } /*! \reimp */ bool QSortFilterProxyModel::setHeaderData(int section, Qt::Orientation orientation, const QVariant &value, int role) { Q_D(QSortFilterProxyModel); IndexMap::const_iterator it = d->create_mapping(QModelIndex()); if (it.value()->source_rows.count() * it.value()->source_columns.count() > 0) return QAbstractProxyModel::setHeaderData(section, orientation, value, role); int source_section; if (orientation == Qt::Vertical) { if (section < 0 || section >= it.value()->source_rows.count()) return false; source_section = it.value()->source_rows.at(section); } else { if (section < 0 || section >= it.value()->source_columns.count()) return false; source_section = it.value()->source_columns.at(section); } return d->model->setHeaderData(source_section, orientation, value, role); } /*! \reimp */ QMimeData *QSortFilterProxyModel::mimeData(const QModelIndexList &indexes) const { Q_D(const QSortFilterProxyModel); QModelIndexList source_indexes; for (int i = 0; i < indexes.count(); ++i) source_indexes << mapToSource(indexes.at(i)); return d->model->mimeData(source_indexes); } /*! \reimp */ QStringList QSortFilterProxyModel::mimeTypes() const { Q_D(const QSortFilterProxyModel); return d->model->mimeTypes(); } /*! \reimp */ Qt::DropActions QSortFilterProxyModel::supportedDropActions() const { Q_D(const QSortFilterProxyModel); return d->model->supportedDropActions(); } /*! \reimp */ bool QSortFilterProxyModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { Q_D(QSortFilterProxyModel); if ((row == -1) && (column == -1)) return d->model->dropMimeData(data, action, -1, -1, mapToSource(parent)); int source_destination_row = -1; int source_destination_column = -1; QModelIndex source_parent; if (row == rowCount(parent)) { source_parent = mapToSource(parent); source_destination_row = d->model->rowCount(source_parent); } else { QModelIndex proxy_index = index(row, column, parent); QModelIndex source_index = mapToSource(proxy_index); source_destination_row = source_index.row(); source_destination_column = source_index.column(); source_parent = source_index.parent(); } return d->model->dropMimeData(data, action, source_destination_row, source_destination_column, source_parent); } /*! \reimp */ bool QSortFilterProxyModel::insertRows(int row, int count, const QModelIndex &parent) { Q_D(QSortFilterProxyModel); if (row < 0 || count <= 0) return false; QModelIndex source_parent = mapToSource(parent); if (parent.isValid() && !source_parent.isValid()) return false; QSortFilterProxyModelPrivate::Mapping *m = d->create_mapping(source_parent).value(); if (row > m->source_rows.count()) return false; int source_row = (row >= m->source_rows.count() ? m->source_rows.count() : m->source_rows.at(row)); return d->model->insertRows(source_row, count, source_parent); } /*! \reimp */ bool QSortFilterProxyModel::insertColumns(int column, int count, const QModelIndex &parent) { Q_D(QSortFilterProxyModel); if (column < 0|| count <= 0) return false; QModelIndex source_parent = mapToSource(parent); if (parent.isValid() && !source_parent.isValid()) return false; QSortFilterProxyModelPrivate::Mapping *m = d->create_mapping(source_parent).value(); if (column > m->source_columns.count()) return false; int source_column = (column >= m->source_columns.count() ? m->source_columns.count() : m->source_columns.at(column)); return d->model->insertColumns(source_column, count, source_parent); } /*! \reimp */ bool QSortFilterProxyModel::removeRows(int row, int count, const QModelIndex &parent) { Q_D(QSortFilterProxyModel); if (row < 0 || count <= 0) return false; QModelIndex source_parent = mapToSource(parent); if (parent.isValid() && !source_parent.isValid()) return false; QSortFilterProxyModelPrivate::Mapping *m = d->create_mapping(source_parent).value(); if (row + count > m->source_rows.count()) return false; if ((count == 1) || ((d->source_sort_column < 0) && (m->proxy_rows.count() == m->source_rows.count()))) { int source_row = m->source_rows.at(row); return d->model->removeRows(source_row, count, source_parent); } // remove corresponding source intervals // ### if this proves to be slow, we can switch to single-row removal QVector<int> rows; for (int i = row; i < row + count; ++i) rows.append(m->source_rows.at(i)); qSort(rows.begin(), rows.end()); int pos = rows.count() - 1; bool ok = true; while (pos >= 0) { const int source_end = rows.at(pos--); int source_start = source_end; while ((pos >= 0) && (rows.at(pos) == (source_start - 1))) { --source_start; --pos; } ok = ok && d->model->removeRows(source_start, source_end - source_start + 1, source_parent); } return ok; } /*! \reimp */ bool QSortFilterProxyModel::removeColumns(int column, int count, const QModelIndex &parent) { Q_D(QSortFilterProxyModel); if (column < 0 || count <= 0) return false; QModelIndex source_parent = mapToSource(parent); if (parent.isValid() && !source_parent.isValid()) return false; QSortFilterProxyModelPrivate::Mapping *m = d->create_mapping(source_parent).value(); if (column + count > m->source_columns.count()) return false; if ((count == 1) || (m->proxy_columns.count() == m->source_columns.count())) { int source_column = m->source_columns.at(column); return d->model->removeColumns(source_column, count, source_parent); } // remove corresponding source intervals QVector<int> columns; for (int i = column; i < column + count; ++i) columns.append(m->source_columns.at(i)); int pos = columns.count() - 1; bool ok = true; while (pos >= 0) { const int source_end = columns.at(pos--); int source_start = source_end; while ((pos >= 0) && (columns.at(pos) == (source_start - 1))) { --source_start; --pos; } ok = ok && d->model->removeColumns(source_start, source_end - source_start + 1, source_parent); } return ok; } /*! \reimp */ void QSortFilterProxyModel::fetchMore(const QModelIndex &parent) { Q_D(QSortFilterProxyModel); QModelIndex source_parent; if (d->indexValid(parent)) source_parent = mapToSource(parent); d->model->fetchMore(source_parent); } /*! \reimp */ bool QSortFilterProxyModel::canFetchMore(const QModelIndex &parent) const { Q_D(const QSortFilterProxyModel); QModelIndex source_parent; if (d->indexValid(parent)) source_parent = mapToSource(parent); return d->model->canFetchMore(source_parent); } /*! \reimp */ Qt::ItemFlags QSortFilterProxyModel::flags(const QModelIndex &index) const { Q_D(const QSortFilterProxyModel); QModelIndex source_index; if (d->indexValid(index)) source_index = mapToSource(index); return d->model->flags(source_index); } /*! \reimp */ QModelIndex QSortFilterProxyModel::buddy(const QModelIndex &index) const { Q_D(const QSortFilterProxyModel); if (!d->indexValid(index)) return QModelIndex(); QModelIndex source_index = mapToSource(index); QModelIndex source_buddy = d->model->buddy(source_index); if (source_index == source_buddy) return index; return mapFromSource(source_buddy); } /*! \reimp */ QModelIndexList QSortFilterProxyModel::match(const QModelIndex &start, int role, const QVariant &value, int hits, Qt::MatchFlags flags) const { return QAbstractProxyModel::match(start, role, value, hits, flags); } /*! \reimp */ QSize QSortFilterProxyModel::span(const QModelIndex &index) const { Q_D(const QSortFilterProxyModel); QModelIndex source_index = mapToSource(index); if (index.isValid() && !source_index.isValid()) return QSize(); return d->model->span(source_index); } /*! \reimp */ void QSortFilterProxyModel::sort(int column, Qt::SortOrder order) { Q_D(QSortFilterProxyModel); if (d->dynamic_sortfilter && d->proxy_sort_column == column && d->sort_order == order) return; d->sort_order = order; d->proxy_sort_column = column; d->update_source_sort_column(); d->sort(); } /*! \since 4.5 \brief the column currently used for sorting This returns the most recently used sort column. */ int QSortFilterProxyModel::sortColumn() const { Q_D(const QSortFilterProxyModel); return d->proxy_sort_column; } /*! \since 4.5 \brief the order currently used for sorting This returns the most recently used sort order. */ Qt::SortOrder QSortFilterProxyModel::sortOrder() const { Q_D(const QSortFilterProxyModel); return d->sort_order; } /*! \property QSortFilterProxyModel::filterRegExp \brief the QRegExp used to filter the contents of the source model Setting this property overwrites the current \l{QSortFilterProxyModel::filterCaseSensitivity}{filterCaseSensitivity}. By default, the QRegExp is an empty string matching all contents. If no QRegExp or an empty string is set, everything in the source model will be accepted. \sa filterCaseSensitivity, setFilterWildcard(), setFilterFixedString() */ QRegExp QSortFilterProxyModel::filterRegExp() const { Q_D(const QSortFilterProxyModel); return d->filter_regexp; } void QSortFilterProxyModel::setFilterRegExp(const QRegExp &regExp) { Q_D(QSortFilterProxyModel); d->filter_regexp = regExp; d->filter_changed(); } /*! \property QSortFilterProxyModel::filterKeyColumn \brief the column where the key used to filter the contents of the source model is read from. The default value is 0. If the value is -1, the keys will be read from all columns. */ int QSortFilterProxyModel::filterKeyColumn() const { Q_D(const QSortFilterProxyModel); return d->filter_column; } void QSortFilterProxyModel::setFilterKeyColumn(int column) { Q_D(QSortFilterProxyModel); d->filter_column = column; d->filter_changed(); } /*! \property QSortFilterProxyModel::filterCaseSensitivity \brief the case sensitivity of the QRegExp pattern used to filter the contents of the source model By default, the filter is case sensitive. \sa filterRegExp, sortCaseSensitivity */ Qt::CaseSensitivity QSortFilterProxyModel::filterCaseSensitivity() const { Q_D(const QSortFilterProxyModel); return d->filter_regexp.caseSensitivity(); } void QSortFilterProxyModel::setFilterCaseSensitivity(Qt::CaseSensitivity cs) { Q_D(QSortFilterProxyModel); if (cs == d->filter_regexp.caseSensitivity()) return; d->filter_regexp.setCaseSensitivity(cs); d->filter_changed(); } /*! \since 4.2 \property QSortFilterProxyModel::sortCaseSensitivity \brief the case sensitivity setting used for comparing strings when sorting By default, sorting is case sensitive. \sa filterCaseSensitivity, lessThan() */ Qt::CaseSensitivity QSortFilterProxyModel::sortCaseSensitivity() const { Q_D(const QSortFilterProxyModel); return d->sort_casesensitivity; } void QSortFilterProxyModel::setSortCaseSensitivity(Qt::CaseSensitivity cs) { Q_D(QSortFilterProxyModel); if (d->sort_casesensitivity == cs) return; d->sort_casesensitivity = cs; d->sort(); } /*! \since 4.3 \property QSortFilterProxyModel::isSortLocaleAware \brief the local aware setting used for comparing strings when sorting By default, sorting is not local aware. \sa sortCaseSensitivity, lessThan() */ bool QSortFilterProxyModel::isSortLocaleAware() const { Q_D(const QSortFilterProxyModel); return d->sort_localeaware; } void QSortFilterProxyModel::setSortLocaleAware(bool on) { Q_D(QSortFilterProxyModel); if (d->sort_localeaware == on) return; d->sort_localeaware = on; d->sort(); } /*! \overload Sets the regular expression used to filter the contents of the source model to \a pattern. \sa setFilterCaseSensitivity(), setFilterWildcard(), setFilterFixedString(), filterRegExp() */ void QSortFilterProxyModel::setFilterRegExp(const QString &pattern) { Q_D(QSortFilterProxyModel); d->filter_regexp.setPatternSyntax(QRegExp::RegExp); d->filter_regexp.setPattern(pattern); d->filter_changed(); } /*! Sets the wildcard expression used to filter the contents of the source model to the given \a pattern. \sa setFilterCaseSensitivity(), setFilterRegExp(), setFilterFixedString(), filterRegExp() */ void QSortFilterProxyModel::setFilterWildcard(const QString &pattern) { Q_D(QSortFilterProxyModel); d->filter_regexp.setPatternSyntax(QRegExp::Wildcard); d->filter_regexp.setPattern(pattern); d->filter_changed(); } /*! Sets the fixed string used to filter the contents of the source model to the given \a pattern. \sa setFilterCaseSensitivity(), setFilterRegExp(), setFilterWildcard(), filterRegExp() */ void QSortFilterProxyModel::setFilterFixedString(const QString &pattern) { Q_D(QSortFilterProxyModel); d->filter_regexp.setPatternSyntax(QRegExp::FixedString); d->filter_regexp.setPattern(pattern); d->filter_changed(); } /*! \since 4.2 \property QSortFilterProxyModel::dynamicSortFilter \brief whether the proxy model is dynamically sorted and filtered whenever the contents of the source model change Note that you should not update the source model through the proxy model when dynamicSortFilter is true. For instance, if you set the proxy model on a QComboBox, then using functions that update the model, e.g., \l{QComboBox::}{addItem()}, will not work as expected. An alternative is to set dynamicSortFilter to false and call \l{QSortFilterProxyModel::}{sort()} after adding items to the QComboBox. The default value is false. */ bool QSortFilterProxyModel::dynamicSortFilter() const { Q_D(const QSortFilterProxyModel); return d->dynamic_sortfilter; } void QSortFilterProxyModel::setDynamicSortFilter(bool enable) { Q_D(QSortFilterProxyModel); d->dynamic_sortfilter = enable; if (enable) d->sort(); } /*! \since 4.2 \property QSortFilterProxyModel::sortRole \brief the item role that is used to query the source model's data when sorting items The default value is Qt::DisplayRole. \sa lessThan() */ int QSortFilterProxyModel::sortRole() const { Q_D(const QSortFilterProxyModel); return d->sort_role; } void QSortFilterProxyModel::setSortRole(int role) { Q_D(QSortFilterProxyModel); if (d->sort_role == role) return; d->sort_role = role; d->sort(); } /*! \since 4.2 \property QSortFilterProxyModel::filterRole \brief the item role that is used to query the source model's data when filtering items The default value is Qt::DisplayRole. \sa filterAcceptsRow() */ int QSortFilterProxyModel::filterRole() const { Q_D(const QSortFilterProxyModel); return d->filter_role; } void QSortFilterProxyModel::setFilterRole(int role) { Q_D(QSortFilterProxyModel); if (d->filter_role == role) return; d->filter_role = role; d->filter_changed(); } /*! \obsolete This function is obsolete. Use invalidate() instead. */ void QSortFilterProxyModel::clear() { Q_D(QSortFilterProxyModel); emit layoutAboutToBeChanged(); d->clear_mapping(); emit layoutChanged(); } /*! \since 4.3 Invalidates the current sorting and filtering. \sa invalidateFilter() */ void QSortFilterProxyModel::invalidate() { Q_D(QSortFilterProxyModel); emit layoutAboutToBeChanged(); d->clear_mapping(); emit layoutChanged(); } /*! \obsolete This function is obsolete. Use invalidateFilter() instead. */ void QSortFilterProxyModel::filterChanged() { Q_D(QSortFilterProxyModel); d->filter_changed(); } /*! \since 4.3 Invalidates the current filtering. This function should be called if you are implementing custom filtering (e.g. filterAcceptsRow()), and your filter parameters have changed. \sa invalidate() */ void QSortFilterProxyModel::invalidateFilter() { Q_D(QSortFilterProxyModel); d->filter_changed(); } /*! Returns true if the value of the item referred to by the given index \a left is less than the value of the item referred to by the given index \a right, otherwise returns false. This function is used as the < operator when sorting, and handles the following QVariant types: \list \o QVariant::Int \o QVariant::UInt \o QVariant::LongLong \o QVariant::ULongLong \o QVariant::Double \o QVariant::Char \o QVariant::Date \o QVariant::Time \o QVariant::DateTime \o QVariant::String \endlist Any other type will be converted to a QString using QVariant::toString(). Comparison of \l{QString}s is case sensitive by default; this can be changed using the \l {QSortFilterProxyModel::sortCaseSensitivity} {sortCaseSensitivity} property. By default, the Qt::DisplayRole associated with the \l{QModelIndex}es is used for comparisons. This can be changed by setting the \l {QSortFilterProxyModel::sortRole} {sortRole} property. \note The indices passed in correspond to the source model. \sa sortRole, sortCaseSensitivity, dynamicSortFilter */ bool QSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { Q_D(const QSortFilterProxyModel); QVariant l = (left.model() ? left.model()->data(left, d->sort_role) : QVariant()); QVariant r = (right.model() ? right.model()->data(right, d->sort_role) : QVariant()); switch (l.userType()) { case QVariant::Invalid: return (r.type() != QVariant::Invalid); case QVariant::Int: return l.toInt() < r.toInt(); case QVariant::UInt: return l.toUInt() < r.toUInt(); case QVariant::LongLong: return l.toLongLong() < r.toLongLong(); case QVariant::ULongLong: return l.toULongLong() < r.toULongLong(); case QMetaType::Float: return l.toFloat() < r.toFloat(); case QVariant::Double: return l.toDouble() < r.toDouble(); case QVariant::Char: return l.toChar() < r.toChar(); case QVariant::Date: return l.toDate() < r.toDate(); case QVariant::Time: return l.toTime() < r.toTime(); case QVariant::DateTime: return l.toDateTime() < r.toDateTime(); case QVariant::String: default: if (d->sort_localeaware) return l.toString().localeAwareCompare(r.toString()) < 0; else return l.toString().compare(r.toString(), d->sort_casesensitivity) < 0; } return false; } /*! Returns true if the item in the row indicated by the given \a source_row and \a source_parent should be included in the model; otherwise returns false. The default implementation returns true if the value held by the relevant item matches the filter string, wildcard string or regular expression. \note By default, the Qt::DisplayRole is used to determine if the row should be accepted or not. This can be changed by setting the \l{QSortFilterProxyModel::filterRole}{filterRole} property. \sa filterAcceptsColumn(), setFilterFixedString(), setFilterRegExp(), setFilterWildcard() */ bool QSortFilterProxyModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { Q_D(const QSortFilterProxyModel); if (d->filter_regexp.isEmpty()) return true; if (d->filter_column == -1) { int column_count = d->model->columnCount(source_parent); for (int column = 0; column < column_count; ++column) { QModelIndex source_index = d->model->index(source_row, column, source_parent); QString key = d->model->data(source_index, d->filter_role).toString(); if (key.contains(d->filter_regexp)) return true; } return false; } QModelIndex source_index = d->model->index(source_row, d->filter_column, source_parent); if (!source_index.isValid()) // the column may not exist return true; QString key = d->model->data(source_index, d->filter_role).toString(); return key.contains(d->filter_regexp); } /*! Returns true if the item in the column indicated by the given \a source_column and \a source_parent should be included in the model; otherwise returns false. The default implementation returns true if the value held by the relevant item matches the filter string, wildcard string or regular expression. \note By default, the Qt::DisplayRole is used to determine if the row should be accepted or not. This can be changed by setting the \l filterRole property. \sa filterAcceptsRow(), setFilterFixedString(), setFilterRegExp(), setFilterWildcard() */ bool QSortFilterProxyModel::filterAcceptsColumn(int source_column, const QModelIndex &source_parent) const { Q_UNUSED(source_column); Q_UNUSED(source_parent); return true; } /*! Returns the source model index corresponding to the given \a proxyIndex from the sorting filter model. \sa mapFromSource() */ QModelIndex QSortFilterProxyModel::mapToSource(const QModelIndex &proxyIndex) const { Q_D(const QSortFilterProxyModel); return d->proxy_to_source(proxyIndex); } /*! Returns the model index in the QSortFilterProxyModel given the \a sourceIndex from the source model. \sa mapToSource() */ QModelIndex QSortFilterProxyModel::mapFromSource(const QModelIndex &sourceIndex) const { Q_D(const QSortFilterProxyModel); return d->source_to_proxy(sourceIndex); } /*! \reimp */ QItemSelection QSortFilterProxyModel::mapSelectionToSource(const QItemSelection &proxySelection) const { return QAbstractProxyModel::mapSelectionToSource(proxySelection); } /*! \reimp */ QItemSelection QSortFilterProxyModel::mapSelectionFromSource(const QItemSelection &sourceSelection) const { return QAbstractProxyModel::mapSelectionFromSource(sourceSelection); } /*! \fn QObject *QSortFilterProxyModel::parent() const \internal */ QT_END_NAMESPACE #include "moc_qsortfilterproxymodel.cpp" #endif // QT_NO_SORTFILTERPROXYMODEL
sunblithe/qt-everywhere-opensource-src-4.7.1
src/gui/itemviews/qsortfilterproxymodel.cpp
C++
lgpl-2.1
92,489
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 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. 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.extension.job.plan.internal; import java.util.Collection; import java.util.Collections; import java.util.concurrent.CopyOnWriteArrayList; import org.xwiki.extension.job.plan.ExtensionPlanAction; import org.xwiki.extension.job.plan.ExtensionPlanNode; import org.xwiki.extension.version.VersionConstraint; /** * A node in the extension plan tree. * * @version $Id$ * @since 4.0M1 */ public class DefaultExtensionPlanNode implements ExtensionPlanNode, Cloneable { /** * @see #getAction() */ protected ExtensionPlanAction action; /** * @see #getChildren() */ protected Collection<ExtensionPlanNode> children; /** * @see #getInitialVersionConstraint() */ protected VersionConstraint initialVersionConstraint; /** * Default constructor. */ public DefaultExtensionPlanNode() { } /** * @param node a node to copy */ public DefaultExtensionPlanNode(ExtensionPlanNode node) { this(node.getAction(), node.getChildren(), node.getInitialVersionConstraint()); } /** * @param action the action to perform for this node * @param initialVersionConstraint the initial version constraint before resolving the extension */ public DefaultExtensionPlanNode(ExtensionPlanAction action, VersionConstraint initialVersionConstraint) { this(action, null, initialVersionConstraint); } /** * @param action the action to perform for this node * @param children the children of this node * @param initialVersionConstraint the initial version constraint before resolving the extension */ public DefaultExtensionPlanNode(ExtensionPlanAction action, Collection<ExtensionPlanNode> children, VersionConstraint initialVersionConstraint) { this.action = action; if (children != null) { this.children = new CopyOnWriteArrayList<>(children); } else { this.children = Collections.emptyList(); } this.initialVersionConstraint = initialVersionConstraint; } @Override protected DefaultExtensionPlanNode clone() { try { return (DefaultExtensionPlanNode) super.clone(); } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } } @Override public ExtensionPlanAction getAction() { return this.action; } @Override public Collection<ExtensionPlanNode> getChildren() { return this.children != null ? this.children : Collections.<ExtensionPlanNode>emptyList(); } @Override public VersionConstraint getInitialVersionConstraint() { return this.initialVersionConstraint; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getAction()); builder.append(" ("); builder.append(getChildren()); if (getInitialVersionConstraint() != null) { builder.append(", "); builder.append(getInitialVersionConstraint()); } builder.append(')'); return builder.toString(); } }
xwiki/xwiki-commons
xwiki-commons-core/xwiki-commons-extension/xwiki-commons-extension-api/src/main/java/org/xwiki/extension/job/plan/internal/DefaultExtensionPlanNode.java
Java
lgpl-2.1
4,160
package org.uengine.essencia; import org.metaworks.Remover; import org.metaworks.ServiceMethodContext; import org.metaworks.ToEvent; import org.metaworks.annotation.Face; import org.metaworks.annotation.Order; import org.metaworks.annotation.ServiceMethod; import org.metaworks.widget.menu.SubMenu; import org.uengine.modeling.Canvas; public class OpacitySubMenu extends SubMenu { @Order(1) @Face(displayName="10%") @ServiceMethod(callByContent=true, target=ServiceMethodContext.TARGET_APPEND) public Object[] ten(){ return new Object[]{new Remover(ServiceMethodContext.TARGET_SELF), new ToEvent(new Canvas(), "opacity", "0.1")}; } @Order(2) @Face(displayName="20%") @ServiceMethod(callByContent=true, target=ServiceMethodContext.TARGET_APPEND) public Object[] twenty(){ return new Object[]{new Remover(ServiceMethodContext.TARGET_SELF), new ToEvent(new Canvas(), "opacity", "0.2")}; } @Order(3) @Face(displayName="30%") @ServiceMethod(callByContent=true, target=ServiceMethodContext.TARGET_APPEND) public Object[] thirty(){ return new Object[]{new Remover(ServiceMethodContext.TARGET_SELF), new ToEvent(new Canvas(), "opacity", "0.3")}; } @Order(4) @Face(displayName="40%") @ServiceMethod(callByContent=true, target=ServiceMethodContext.TARGET_APPEND) public Object[] fourty(){ return new Object[]{new Remover(ServiceMethodContext.TARGET_SELF), new ToEvent(new Canvas(), "opacity", "0.4")}; } @Order(5) @Face(displayName="50%") @ServiceMethod(callByContent=true, target=ServiceMethodContext.TARGET_APPEND) public Object[] fifty(){ return new Object[]{new Remover(ServiceMethodContext.TARGET_SELF), new ToEvent(new Canvas(), "opacity", "0.5")}; } @Order(6) @Face(displayName="60%") @ServiceMethod(callByContent=true, target=ServiceMethodContext.TARGET_APPEND) public Object[] sixty(){ return new Object[]{new Remover(ServiceMethodContext.TARGET_SELF), new ToEvent(new Canvas(), "opacity", "0.6")}; } @Order(7) @Face(displayName="70%") @ServiceMethod(callByContent=true, target=ServiceMethodContext.TARGET_APPEND) public Object[] seventy(){ return new Object[]{new Remover(ServiceMethodContext.TARGET_SELF), new ToEvent(new Canvas(), "opacity", "0.7")}; } @Order(8) @Face(displayName="80%") @ServiceMethod(callByContent=true, target=ServiceMethodContext.TARGET_APPEND) public Object[] eighty(){ return new Object[]{new Remover(ServiceMethodContext.TARGET_SELF), new ToEvent(new Canvas(), "opacity", "0.8")}; } @Order(9) @Face(displayName="90%") @ServiceMethod(callByContent=true, target=ServiceMethodContext.TARGET_APPEND) public Object[] ninety(){ return new Object[]{new Remover(ServiceMethodContext.TARGET_SELF), new ToEvent(new Canvas(), "opacity", "0.9")}; } @Order(10) @Face(displayName="100%") @ServiceMethod(callByContent=true, target=ServiceMethodContext.TARGET_APPEND) public Object[] hundred(){ return new Object[]{new Remover(ServiceMethodContext.TARGET_SELF), new ToEvent(new Canvas(), "opacity", "1")}; } }
iklim/essencia
src/main/java/org/uengine/essencia/OpacitySubMenu.java
Java
lgpl-2.1
3,011
package soot.grimp.internal; /*- * #%L * Soot - a J*va Optimization Framework * %% * Copyright (C) 1999 Patrick Lam * %% * 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 General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ import soot.AbstractValueBox; import soot.Local; import soot.Value; import soot.jimple.ConcreteRef; import soot.jimple.Constant; import soot.jimple.Expr; public class ExprBox extends AbstractValueBox { public ExprBox(Value value) { setValue(value); } public boolean canContainValue(Value value) { return value instanceof Local || value instanceof Constant || value instanceof Expr || value instanceof ConcreteRef; } }
plast-lab/soot
src/main/java/soot/grimp/internal/ExprBox.java
Java
lgpl-2.1
1,262