code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php /** * Copyright (C) 2011-2015 Visman (mio.visman@yandex.ru) * License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher */ if (!defined('PUN')) exit; if (isset($pun_config['o_fbox_files']) && !isset($http_status) && (!$pun_user['is_guest'] || !empty($pun_config['o_fbox_guest']))) { if (strpos(','.$pun_config['o_fbox_files'], ','.basename($_SERVER['PHP_SELF'])) !== false || (!empty($plugin) && strpos(','.$pun_config['o_fbox_files'], ','.$plugin) !== false)) { if (!isset($page_head)) $page_head = array(); $page_head['fancyboxcss'] = '<link rel="stylesheet" type="text/css" href="style/imports/fancybox.css" />'; if (!isset($page_js)) { $page_head['jquery'] = '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>'; $page_head['fancybox'] = '<script type="text/javascript" src="js/fancybox.js"></script>'; } else // For FluxBB by Visman { $page_js['j'] = 1; $page_js['f']['fancybox'] = 'js/fancybox.js'; } } }
MioVisman/FluxBB_by_Visman
include/fancybox.php
PHP
gpl-2.0
1,028
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using AnimationExample; namespace ProjectSneakyGame { /// <summary> /// Extension of the DrawableGameComponent class. /// Includes set-up and functions for 3D matrix movement of DrawableGameComponent types. /// </summary> public class DrawableMovableComponent : DrawableGameComponent { protected float _speed; protected Vector3 _pos; protected Matrix _trans, _rot, _scale, _main; protected Game1 _game; protected MovableBoundingBox _bBox; public float Speed { get { return _speed; } set { _speed = value; } } public Vector3 Pos { get { return _pos; } set { _pos = value; } } public Matrix TranslationM { get { return _trans; } set { _trans = value; } } public Matrix RotationM { get { return _trans; } set { _trans = value; } } public Matrix ScaleM { get { return _scale; } set { _scale = value; } } public Matrix TransformationM { get { return _main; } } public MovableBoundingBox BoundingBox { get { return _bBox; } set { _bBox = value; } } public DrawableMovableComponent(Game1 game):base(game) { _pos = Vector3.One; _main = Matrix.Identity; _trans = Matrix.Identity; _rot = Matrix.Identity; _scale = Matrix.Identity; _game = game; _speed = 0; } public DrawableMovableComponent(Game1 game, Vector3 pos) : base(game) { _pos = pos; //_trans.Translation = _pos; _trans = Matrix.CreateTranslation(pos); _rot = Matrix.Identity; _scale = Matrix.Identity; _main = Matrix.Identity; _speed = 0; _game = game; } public DrawableMovableComponent(Game1 game, Vector3 pos, float speed) : base(game) { _pos = pos; //_trans.Translation = _pos; _trans = Matrix.CreateTranslation(pos); _rot = Matrix.Identity; _scale = Matrix.Identity; _main = Matrix.Identity; _speed = speed; _game = game; } public virtual void Translate(Vector3 vec, GameTime g) { _trans *= Matrix.CreateTranslation(vec * (float)g.ElapsedGameTime.TotalSeconds); _pos += vec * (float)g.ElapsedGameTime.TotalSeconds; } public virtual void Translate(Vector3 vec) { _trans *= Matrix.CreateTranslation(vec); _pos += vec; } public virtual void Translate(float x, float y, float z, GameTime g) { Vector3 temp = new Vector3(x,y,z); _trans *= Matrix.CreateTranslation(temp * (float)g.ElapsedGameTime.TotalSeconds); _pos += temp * (float)g.ElapsedGameTime.TotalSeconds; } public virtual void Translate(float x, float y, float z) { Vector3 temp = new Vector3(x, y, z); _trans *= Matrix.CreateTranslation(temp); _pos += temp; } public virtual void RotateX(float rot, GameTime g) { _rot *= Matrix.CreateRotationX(rot * (float)g.ElapsedGameTime.TotalSeconds); _pos += _rot.Translation; } public virtual void RotateX(float rot) { _rot *= Matrix.CreateRotationX(rot); _pos += _rot.Translation; } public virtual void RotateY(float rot, GameTime g) { _rot *= Matrix.CreateRotationY(rot * (float)g.ElapsedGameTime.TotalSeconds); _pos += _rot.Translation; } public virtual void RotateY(float rot) { _rot *= Matrix.CreateRotationY(rot); _pos += _rot.Translation; } public virtual void RotateZ(float rot, GameTime g) { _rot *= Matrix.CreateRotationZ(rot * (float)g.ElapsedGameTime.TotalSeconds); _pos += _rot.Translation; } public virtual void RotateZ(float rot) { _rot *= Matrix.CreateRotationZ(rot); _pos += _rot.Translation; } public virtual void RotateOnAxis(Vector3 axis, float rot, GameTime g) { _rot *= Matrix.CreateFromAxisAngle(axis, rot * (float)g.ElapsedGameTime.TotalSeconds); _pos += _rot.Translation; } public virtual void RotateOnAxis(Vector3 axis, float rot) { _rot *= Matrix.CreateFromAxisAngle(axis, rot); _pos += _rot.Translation; } public virtual void Scale(float scale, GameTime g) { _scale *= Matrix.CreateScale(scale * (float)g.ElapsedGameTime.TotalSeconds); } public virtual void Scale(float scale) { _scale *= Matrix.CreateScale(scale); } public virtual void Scale(float x, float y, float z, GameTime g) { Vector3 temp = new Vector3(x, y, z); temp *= (float)g.ElapsedGameTime.TotalSeconds; _scale *= Matrix.CreateScale(temp); } public virtual void Scale(float x, float y, float z) { _scale *= Matrix.CreateScale(x, y, z); } public virtual void Scale(Vector3 vec, GameTime g) { _scale *= Matrix.CreateScale(vec * (float)g.ElapsedGameTime.TotalSeconds); } public virtual void Scale(Vector3 vec) { _scale *= Matrix.CreateScale(vec); } public virtual void MoveForward(GameTime g) { Translate(Vector3.Forward * _speed, g); } public virtual void MoveBackward(GameTime g) { Translate(Vector3.Backward * _speed, g); } public virtual void MoveUp(GameTime g) { Translate(Vector3.Up * _speed, g); } public virtual void MoveDown(GameTime g) { Translate(Vector3.Down * _speed, g); } public virtual void MoveLeft(GameTime g) { Translate(Vector3.Left * _speed, g); } public virtual void MoveRight(GameTime g) { Translate(Vector3.Right * _speed, g); } public virtual void Move(GameTime g, Vector3 dir) { Translate(dir * _speed, g); } /// <summary> /// Resets the GraphicsDevice states so that they are able to draw 3D objects. /// </summary> protected void SetGraphicsStatesFor3D() { _game.GraphicsDevice.RasterizerState = GraphicsDeviceStates.Rasterizer3DNormal; _game.GraphicsDevice.BlendState = GraphicsDeviceStates.Blend3DNormal; _game.GraphicsDevice.DepthStencilState = GraphicsDeviceStates.DepthStencil3DNormal; _game.GraphicsDevice.SamplerStates[0] = GraphicsDeviceStates.Sampler3DNormal; } public override void Update(GameTime gameTime) { _main = _scale * _rot * _trans; if (_bBox != null) _bBox.Transform(_trans.Translation); base.Update(gameTime); } static public implicit operator BoundingBox(DrawableMovableComponent obj) { return obj._bBox; } } }
JoshuaKlaser/ANSKLibrary
AnimationExample/AnimationExample/DrawableMovableComponent.cs
C#
gpl-2.0
7,452
<?php /** * Sources English lexicon topic * * @language en * @package modx * @subpackage lexicon */ $_lang['access'] = 'Åtkomsträttigheter'; $_lang['base_path'] = 'Bassökväg'; $_lang['base_path_relative'] = 'Relativ bassökväg?'; $_lang['base_url'] = 'Bas-URL'; $_lang['base_url_relative'] = 'Relativ bas-URL?'; $_lang['minimum_role'] = 'Minimiroll'; $_lang['path_options'] = 'Sökvägsalternativ'; $_lang['policy'] = 'Policy'; $_lang['source'] = 'Mediakälla'; $_lang['source_access_add'] = 'Lägg till användargrupp'; $_lang['source_access_remove'] = 'Ta bort tillgång'; $_lang['source_access_remove_confirm'] = 'Är du säker på att du vill ta bort tillgång till denna källa för denna användargrupp?'; $_lang['source_access_update'] = 'Uppdatera tillgång'; $_lang['source_create'] = 'Skapa ny mediakälla'; $_lang['source_description_desc'] = 'En kort beskrivning av mediakällan.'; $_lang['source_duplicate'] = 'Duplicera mediakälla'; $_lang['source_err_ae_name'] = 'Det finns redan en mediakälla med det namnet! Ange ett annat namn.'; $_lang['source_err_nf'] = 'Mediakällan kunde inte hittas!'; $_lang['source_err_nfs'] = 'Kan inte hitta mediakällan med id: [[+id]].'; $_lang['source_err_ns'] = 'Ange mediakällan.'; $_lang['source_err_ns_name'] = 'Ange ett namn för mediakällan.'; $_lang['source_name_desc'] = 'Mediakällans namn'; $_lang['source_properties.intro_msg'] = 'Hantera egenskaperna för denna källa nedan.'; $_lang['source_remove'] = 'Ta bort mediakälla'; $_lang['source_remove_confirm'] = 'Är du säker på att du vill ta bort denna mediakälla? Detta kan ha sönder mallvariabler som du har tilldelat till denna källa.'; $_lang['source_remove_multiple'] = 'Ta bort flera mediakällor'; $_lang['source_remove_multiple_confirm'] = 'Är du säker på att du vill ta bort dessa mediakällor? Detta kan ha sönder mallvariabler som du har tilldelat till dessa källor.'; $_lang['source_update'] = 'Uppdatera mediakälla'; $_lang['source_type'] = 'Källtyp'; $_lang['source_type_desc'] = 'Mediakällans typ eller drivrutin. Källan kommer att använda denna drivrutin för att ansluta när den hämtar sin data. Till exempel: Filsystem hämtar filer från filsystemet. S3 hämtar filer från en S3-hink.'; $_lang['source_type.file'] = 'Filsystem'; $_lang['source_type.file_desc'] = 'En filsystembaserad källa som navigerar bland din servers filer.'; $_lang['source_type.s3'] = 'Amazon S3'; $_lang['source_type.s3_desc'] = 'Navigerar en Amazon S3-hink.'; $_lang['source_types'] = 'Källtyper'; $_lang['source_types.intro_msg'] = 'Det här är en lista med alla de installerade typer av mediakällor som du har i denna MODX-instans.'; $_lang['source.access.intro_msg'] = 'Här kan du begränsa en mediakälla till specifika användargrupper och ange policyer för dessa användargrupper. En mediakälla som inte är ihopkopplad med några användargrupper är tillgänglig för alla användare av hanteraren.'; $_lang['sources'] = 'Mediakällor'; $_lang['sources.intro_msg'] = 'Hantera alla dina mediakällor här.'; $_lang['user_group'] = 'Användargrupp'; /* file source type */ $_lang['prop_file.allowedFileTypes_desc'] = 'Om denna aktiveras så kommer den att begränsa de filer som visas till endast de filsuffix som anges här. Skriv som en kommaseparerad lista utan punkter.'; $_lang['prop_file.basePath_desc'] = 'Den filsökväg som källan ska pekas mot.'; $_lang['prop_file.basePathRelative_desc'] = 'Om bassökvägen ovan inte är relativ till installationssökvägen för MODX, så sätter du den här till Nej.'; $_lang['prop_file.baseUrl_desc'] = 'Den URL som denna källa kan kommas åt från.'; $_lang['prop_file.baseUrlPrependCheckSlash_desc'] = 'Om denna sätts till "Ja" kommer MODX bara att lägga till baseURL i början av sökvägen om inget snedstreck (/) finns i början av URL:en när en mallvariabel ska visas. Det här är användbart om du vill ange ett värde på en mallvariabel som ligger utanför baseURL.'; $_lang['prop_file.baseUrlRelative_desc'] = 'Om inställningen för rot-URL ovan inte är relativ till MODX installations-URL sätter du denna till "Nej".'; $_lang['prop_file.imageExtensions_desc'] = 'En kommaseparerad lista med de filsuffix som ska användas som bilder. MODX kommer att försöka göra tumnaglar av filer med dessa suffix.'; $_lang['prop_file.skipFiles_desc'] = 'En kommaseparerad lista. MODX kommer att hoppa över och gömma filer och mappar som matchar någon av dessa.'; $_lang['prop_file.thumbnailQuality_desc'] = 'Kvalitén på de renderade tumnaglarna på en skala från 0-100.'; $_lang['prop_file.thumbnailType_desc'] = 'Den bildtyp som tumnaglarna ska renderas som.'; /* s3 source type */ $_lang['bucket'] = 'Hink'; $_lang['prop_s3.bucket_desc'] = 'Den S3-hink som din data ska laddas från.'; $_lang['prop_s3.key_desc'] = 'Amazons nyckel som ska användas för autentisering till hinken.'; $_lang['prop_s3.imageExtensions_desc'] = 'En kommaseparerad lista med de filsuffix som ska användas som bilder. MODX kommer att försöka göra tumnaglar av filer med dessa suffix.'; $_lang['prop_s3.secret_key_desc'] = 'Amazons hemliga nyckel som ska användas för autentisering till hinken.'; $_lang['prop_s3.skipFiles_desc'] = 'En kommaseparerad lista. MODX kommer att hoppa över och gömma filer och mappar som matchar någon av dessa.'; $_lang['prop_s3.thumbnailQuality_desc'] = 'Kvalitén på de renderade tumnaglarna på en skala från 0-100.'; $_lang['prop_s3.thumbnailType_desc'] = 'Den bildtyp som tumnaglarna ska renderas som.'; $_lang['prop_s3.url_desc'] = 'URL:en för Amazon S3-instansen.'; $_lang['s3_no_move_folder'] = 'S3-drivrutinen stödjer än så länge inte flyttning av mappar.';
svyatoslavteterin/belton.by
core/lexicon/sv/source.inc.php
PHP
gpl-2.0
5,705
/* * Copyright (C) 2008-2011 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Blades_Edge_Mountains SD%Complete: 90 SDComment: Quest support: 10503, 10504, 10556, 10609, 10682, 10821, 10980. Ogri'la->Skettis Flight. (npc_daranelle needs bit more work before consider complete) SDCategory: Blade's Edge Mountains EndScriptData */ /* ContentData mobs_bladespire_ogre mobs_nether_drake npc_daranelle npc_overseer_nuaar npc_saikkal_the_elder go_legion_obelisk EndContentData */ #include "ScriptPCH.h" //Support for quest: You're Fired! (10821) bool obelisk_one, obelisk_two, obelisk_three, obelisk_four, obelisk_five; #define LEGION_OBELISK_ONE 185193 #define LEGION_OBELISK_TWO 185195 #define LEGION_OBELISK_THREE 185196 #define LEGION_OBELISK_FOUR 185197 #define LEGION_OBELISK_FIVE 185198 /*###### ## mobs_bladespire_ogre ######*/ //TODO: add support for quest 10512 + Creature abilities class mobs_bladespire_ogre : public CreatureScript { public: mobs_bladespire_ogre() : CreatureScript("mobs_bladespire_ogre") { } CreatureAI* GetAI(Creature* pCreature) const { return new mobs_bladespire_ogreAI (pCreature); } struct mobs_bladespire_ogreAI : public ScriptedAI { mobs_bladespire_ogreAI(Creature *c) : ScriptedAI(c) {} void Reset() { } void UpdateAI(const uint32 /*uiDiff*/) { if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; }; /*###### ## mobs_nether_drake ######*/ enum eNetherdrake { SAY_NIHIL_1 = -1000169, //signed for 5955 SAY_NIHIL_2 = -1000170, //signed for 5955 SAY_NIHIL_3 = -1000171, //signed for 5955 SAY_NIHIL_4 = -1000172, //signed for 20021, used by 20021, 21817, 21820, 21821, 21823 SAY_NIHIL_INTERRUPT = -1000173, //signed for 20021, used by 20021, 21817, 21820, 21821, 21823 ENTRY_WHELP = 20021, ENTRY_PROTO = 21821, ENTRY_ADOLE = 21817, ENTRY_MATUR = 21820, ENTRY_NIHIL = 21823, SPELL_T_PHASE_MODULATOR = 37573, SPELL_ARCANE_BLAST = 38881, SPELL_MANA_BURN = 38884, SPELL_INTANGIBLE_PRESENCE = 36513 }; class mobs_nether_drake : public CreatureScript { public: mobs_nether_drake() : CreatureScript("mobs_nether_drake") { } CreatureAI* GetAI(Creature* pCreature) const { return new mobs_nether_drakeAI (pCreature); } struct mobs_nether_drakeAI : public ScriptedAI { mobs_nether_drakeAI(Creature *c) : ScriptedAI(c) {} bool IsNihil; uint32 NihilSpeech_Timer; uint32 NihilSpeech_Phase; uint32 ArcaneBlast_Timer; uint32 ManaBurn_Timer; uint32 IntangiblePresence_Timer; void Reset() { IsNihil = false; NihilSpeech_Timer = 3000; NihilSpeech_Phase = 0; ArcaneBlast_Timer = 7500; ManaBurn_Timer = 10000; IntangiblePresence_Timer = 15000; } void EnterCombat(Unit* /*who*/) {} void MoveInLineOfSight(Unit *who) { if (me->HasFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE)) return; ScriptedAI::MoveInLineOfSight(who); } //in case Creature was not summoned (not expected) void MovementInform(uint32 type, uint32 id) { if (type != POINT_MOTION_TYPE) return; if (id == 0) { me->setDeathState(JUST_DIED); me->RemoveCorpse(); me->SetHealth(0); } } void SpellHit(Unit *caster, const SpellEntry *spell) { if (spell->Id == SPELL_T_PHASE_MODULATOR && caster->GetTypeId() == TYPEID_PLAYER) { const uint32 entry_list[4] = {ENTRY_PROTO, ENTRY_ADOLE, ENTRY_MATUR, ENTRY_NIHIL}; int cid = rand()%(4-1); if (entry_list[cid] == me->GetEntry()) ++cid; //we are nihil, so say before transform if (me->GetEntry() == ENTRY_NIHIL) { DoScriptText(SAY_NIHIL_INTERRUPT, me); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); IsNihil = false; } if (me->UpdateEntry(entry_list[cid])) { if (entry_list[cid] == ENTRY_NIHIL) { EnterEvadeMode(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE); IsNihil = true; } else AttackStart(caster); } } } void UpdateAI(uint32 const diff) { if (IsNihil) { if (NihilSpeech_Timer <= diff) { switch(NihilSpeech_Phase) { case 0: DoScriptText(SAY_NIHIL_1, me); ++NihilSpeech_Phase; break; case 1: DoScriptText(SAY_NIHIL_2, me); ++NihilSpeech_Phase; break; case 2: DoScriptText(SAY_NIHIL_3, me); ++NihilSpeech_Phase; break; case 3: DoScriptText(SAY_NIHIL_4, me); ++NihilSpeech_Phase; break; case 4: me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE); //take off to location above me->GetMotionMaster()->MovePoint(0, me->GetPositionX()+50.0f, me->GetPositionY(), me->GetPositionZ()+50.0f); ++NihilSpeech_Phase; break; } NihilSpeech_Timer = 5000; } else NihilSpeech_Timer -=diff; //anything below here is not interesting for Nihil, so skip it return; } if (!UpdateVictim()) return; if (IntangiblePresence_Timer <= diff) { DoCast(me->getVictim(), SPELL_INTANGIBLE_PRESENCE); IntangiblePresence_Timer = 15000+rand()%15000; } else IntangiblePresence_Timer -= diff; if (ManaBurn_Timer <= diff) { Unit *pTarget = me->getVictim(); if (pTarget && pTarget->getPowerType() == POWER_MANA) DoCast(pTarget, SPELL_MANA_BURN); ManaBurn_Timer = 8000+rand()%8000; } else ManaBurn_Timer -= diff; if (ArcaneBlast_Timer <= diff) { DoCast(me->getVictim(), SPELL_ARCANE_BLAST); ArcaneBlast_Timer = 2500+rand()%5000; } else ArcaneBlast_Timer -= diff; DoMeleeAttackIfReady(); } }; }; /*###### ## npc_daranelle ######*/ enum eDaranelle { SAY_SPELL_INFLUENCE = -1000174, SPELL_LASHHAN_CHANNEL = 36904 }; class npc_daranelle : public CreatureScript { public: npc_daranelle() : CreatureScript("npc_daranelle") { } CreatureAI* GetAI(Creature* pCreature) const { return new npc_daranelleAI (pCreature); } struct npc_daranelleAI : public ScriptedAI { npc_daranelleAI(Creature *c) : ScriptedAI(c) {} void Reset() { } void EnterCombat(Unit* /*who*/) {} void MoveInLineOfSight(Unit *who) { if (who->GetTypeId() == TYPEID_PLAYER) { if (who->HasAura(SPELL_LASHHAN_CHANNEL) && me->IsWithinDistInMap(who, 10.0f)) { DoScriptText(SAY_SPELL_INFLUENCE, me, who); //TODO: Move the below to updateAI and run if this statement == true DoCast(who, 37028, true); } } ScriptedAI::MoveInLineOfSight(who); } }; }; /*###### ## npc_overseer_nuaar ######*/ #define GOSSIP_HELLO_ON "Overseer, I am here to negotiate on behalf of the Cenarion Expedition." class npc_overseer_nuaar : public CreatureScript { public: npc_overseer_nuaar() : CreatureScript("npc_overseer_nuaar") { } bool OnGossipSelect(Player* pPlayer, Creature* pCreature, uint32 /*uiSender*/, uint32 uiAction) { pPlayer->PlayerTalkClass->ClearMenus(); if (uiAction == GOSSIP_ACTION_INFO_DEF+1) { pPlayer->SEND_GOSSIP_MENU(10533, pCreature->GetGUID()); pPlayer->AreaExploredOrEventHappens(10682); } return true; } bool OnGossipHello(Player* pPlayer, Creature* pCreature) { if (pPlayer->GetQuestStatus(10682) == QUEST_STATUS_INCOMPLETE) pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO_ON, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); pPlayer->SEND_GOSSIP_MENU(10532, pCreature->GetGUID()); return true; } }; /*###### ## npc_saikkal_the_elder ######*/ #define GOSSIP_HELLO_STE "Yes... yes, it's me." #define GOSSIP_SELECT_STE "Yes elder. Tell me more of the book." class npc_saikkal_the_elder : public CreatureScript { public: npc_saikkal_the_elder() : CreatureScript("npc_saikkal_the_elder") { } bool OnGossipSelect(Player* pPlayer, Creature* pCreature, uint32 /*uiSender*/, uint32 uiAction) { pPlayer->PlayerTalkClass->ClearMenus(); switch (uiAction) { case GOSSIP_ACTION_INFO_DEF+1: pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_SELECT_STE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2); pPlayer->SEND_GOSSIP_MENU(10795, pCreature->GetGUID()); break; case GOSSIP_ACTION_INFO_DEF+2: pPlayer->TalkedToCreature(pCreature->GetEntry(), pCreature->GetGUID()); pPlayer->SEND_GOSSIP_MENU(10796, pCreature->GetGUID()); break; } return true; } bool OnGossipHello(Player* pPlayer, Creature* pCreature) { if (pPlayer->GetQuestStatus(10980) == QUEST_STATUS_INCOMPLETE) pPlayer->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_HELLO_STE, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1); pPlayer->SEND_GOSSIP_MENU(10794, pCreature->GetGUID()); return true; } }; /*###### ## go_legion_obelisk ######*/ class go_legion_obelisk : public GameObjectScript { public: go_legion_obelisk() : GameObjectScript("go_legion_obelisk") { } bool OnGossipHello(Player* pPlayer, GameObject* pGo) { if (pPlayer->GetQuestStatus(10821) == QUEST_STATUS_INCOMPLETE) { switch(pGo->GetEntry()) { case LEGION_OBELISK_ONE: obelisk_one = true; break; case LEGION_OBELISK_TWO: obelisk_two = true; break; case LEGION_OBELISK_THREE: obelisk_three = true; break; case LEGION_OBELISK_FOUR: obelisk_four = true; break; case LEGION_OBELISK_FIVE: obelisk_five = true; break; } if (obelisk_one == true && obelisk_two == true && obelisk_three == true && obelisk_four == true && obelisk_five == true) { pGo->SummonCreature(19963, 2943.40f, 4778.20f, 284.49f, 0.94f, TEMPSUMMON_TIMED_DESPAWN_OUT_OF_COMBAT, 120000); //reset global var obelisk_one = false; obelisk_two = false; obelisk_three = false; obelisk_four = false; obelisk_five = false; } } return true; } }; /*###### ## npc_bloodmaul_brutebane ######*/ enum eBloodmaul { NPC_OGRE_BRUTE = 19995, NPC_QUEST_CREDIT = 21241, GO_KEG = 184315, QUEST_GETTING_THE_BLADESPIRE_TANKED = 10512, QUEST_BLADESPIRE_KEGGER = 10545, }; class npc_bloodmaul_brutebane : public CreatureScript { public: npc_bloodmaul_brutebane() : CreatureScript("npc_bloodmaul_brutebane") { } CreatureAI* GetAI(Creature* creature) const { return new npc_bloodmaul_brutebaneAI(creature); } struct npc_bloodmaul_brutebaneAI : public ScriptedAI { npc_bloodmaul_brutebaneAI(Creature* creature) : ScriptedAI(creature) { if(Creature* Ogre = me->FindNearestCreature(NPC_OGRE_BRUTE, 50, true)) { Ogre->SetReactState(REACT_DEFENSIVE); Ogre->GetMotionMaster()->MovePoint(1, me->GetPositionX()-1, me->GetPositionY()+1, me->GetPositionZ()); } } uint64 OgreGUID; void Reset() { OgreGUID = 0; } void UpdateAI(const uint32 /*uiDiff*/) {} }; }; /*###### ## npc_ogre_brute ######*/ class npc_ogre_brute : public CreatureScript { public: npc_ogre_brute() : CreatureScript("npc_ogre_brute") { } CreatureAI* GetAI(Creature* creature) const { return new npc_ogre_bruteAI(creature); } struct npc_ogre_bruteAI : public ScriptedAI { npc_ogre_bruteAI(Creature* creature) : ScriptedAI(creature) {} uint64 PlayerGUID; void Reset() { PlayerGUID = 0; } void MoveInLineOfSight(Unit* who) { if (!who || (!who->isAlive())) return; if (me->IsWithinDistInMap(who, 50.0f)) { if (who->GetTypeId() == TYPEID_PLAYER) if (who->ToPlayer()->GetQuestStatus(QUEST_GETTING_THE_BLADESPIRE_TANKED || QUEST_BLADESPIRE_KEGGER) == QUEST_STATUS_INCOMPLETE) PlayerGUID = who->GetGUID(); } } void MovementInform(uint32 /*type*/, uint32 id) { Player* pPlayer = Unit::GetPlayer(*me, PlayerGUID); if (id == 1) { GameObject* Keg = me->FindNearestGameObject(GO_KEG, 20); if (Keg) Keg->Delete(); me->HandleEmoteCommand(7); me->SetReactState(REACT_AGGRESSIVE); me->GetMotionMaster()->MoveTargetedHome(); Creature* Credit = me->FindNearestCreature(NPC_QUEST_CREDIT, 50, true); if (pPlayer && Credit) pPlayer->KilledMonster(Credit->GetCreatureInfo(), Credit->GetGUID()); } } void UpdateAI(const uint32 /*diff*/) { if (!UpdateVictim()) return; DoMeleeAttackIfReady(); } }; }; /*###### ## AddSC ######*/ void AddSC_blades_edge_mountains() { new mobs_bladespire_ogre(); new mobs_nether_drake(); new npc_daranelle(); new npc_overseer_nuaar(); new npc_saikkal_the_elder(); new go_legion_obelisk(); new npc_bloodmaul_brutebane(); new npc_ogre_brute(); }
SeTM/MythCore
src/server/scripts/Outland/blades_edge_mountains.cpp
C++
gpl-2.0
16,406
package geeksforgeeks.divide.conquer; /* * http://chuansongme.com/n/122759 * * This is actually dutch national flag problem. See SortList.java. * * Check the above link for another solution */ public class Sort123 { }
sindhujapr/ms_prep
companies/geeksforgeeks/divide/conquer/Sort123.java
Java
gpl-2.0
227
/* * Copyright (C) 2011-2021 Project SkyFire <https://www.projectskyfire.org/> * Copyright (C) 2008-2021 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2021 MaNGOS <https://www.getmangos.eu/> * Copyright (C) 2006-2014 ScriptDev2 <https://github.com/scriptdev2/scriptdev2/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* ScriptData SDName: Instance_Razorfen_Kraul SD%Complete: SDComment: SDCategory: Razorfen Kraul EndScriptData */ #include "ScriptMgr.h" #include "InstanceScript.h" #include "razorfen_kraul.h" #include "Player.h" #define WARD_KEEPERS_NR 2 class instance_razorfen_kraul : public InstanceMapScript { public: instance_razorfen_kraul() : InstanceMapScript("instance_razorfen_kraul", 47) { } InstanceScript* GetInstanceScript(InstanceMap* map) const OVERRIDE { return new instance_razorfen_kraul_InstanceMapScript(map); } struct instance_razorfen_kraul_InstanceMapScript : public InstanceScript { instance_razorfen_kraul_InstanceMapScript(Map* map) : InstanceScript(map) { } uint64 DoorWardGUID; int WardKeeperDeath; void Initialize() OVERRIDE { WardKeeperDeath = 0; DoorWardGUID = 0; } Player* GetPlayerInMap() { Map::PlayerList const& players = instance->GetPlayers(); if (!players.isEmpty()) { for (Map::PlayerList::const_iterator itr = players.begin(); itr != players.end(); ++itr) { if (Player* player = itr->GetSource()) return player; } } SF_LOG_DEBUG("scripts", "Instance Razorfen Kraul: GetPlayerInMap, but PlayerList is empty!"); return NULL; } void OnGameObjectCreate(GameObject* go) OVERRIDE { switch (go->GetEntry()) { case 21099: DoorWardGUID = go->GetGUID(); break; case 20920: go->SetUInt32Value(GAMEOBJECT_FIELD_FACTION_TEMPLATE, 0); break; // big fat fugly hack } } void Update(uint32 /*diff*/) OVERRIDE { if (WardKeeperDeath == WARD_KEEPERS_NR) if (GameObject* go = instance->GetGameObject(DoorWardGUID)) { go->SetUInt32Value(GAMEOBJECT_FIELD_FLAGS, 33); go->SetGoState(GOState::GO_STATE_ACTIVE); } } void SetData(uint32 type, uint32 /*data*/) OVERRIDE { switch (type) { case EVENT_WARD_KEEPER: WardKeeperDeath++; break; } } }; }; void AddSC_instance_razorfen_kraul() { new instance_razorfen_kraul(); }
ProjectSkyfire/SkyFire.548
src/server/scripts/Kalimdor/RazorfenKraul/instance_razorfen_kraul.cpp
C++
gpl-2.0
3,367
/** * @author Stefan Brandle * @author Jonathan Geisler * @date September, 2014 * */ #ifndef PLAYERV2_CPP // Double inclusion protection #define PLAYERV2_CPP #include <iostream> #include "PlayerV2.h" /** * @brief Constructor: initializes any game-long data structures. * * The player should reinitialize any inter-round data structures that will be used * for the entire game. * I.e., any intra-round learning data structures should be initialized in the here, * while inter-round data structures need to be initialized in newRound(). */ PlayerV2::PlayerV2( int boardSize ) { // Set boardsize this->boardSize = boardSize; } #endif
BoringCode/BattleshipAI
PlayerV2.cpp
C++
gpl-2.0
658
<?php /* *--------------------------------------------------------- * * CartET - Open Source Shopping Cart Software * http://www.cartet.org * *--------------------------------------------------------- */ define('MODULE_PAYMENT_PLATON_TEXT_TITLE', 'Platon.ua'); define('MODULE_PAYMENT_PLATON_TEXT_DESCRIPTION', 'Platon: Система электронных платежей.'); define('MODULE_PAYMENT_PLATON_STATUS_TITLE', 'Разрешить модуль Platon.ua'); define('MODULE_PAYMENT_PLATON_STATUS_DESC', ''); define('MODULE_PAYMENT_PLATON_ALLOWED_TITLE', 'Разрешённые страны'); define('MODULE_PAYMENT_PLATON_ALLOWED_DESC', 'Укажите коды стран, для которых будет доступен данный модуль (например RU,DE (оставьте поле пустым, если хотите что б модуль был доступен покупателям из любых стран))'); define('MODULE_PAYMENT_PLATON_KEY_TITLE', 'Ключ'); define('MODULE_PAYMENT_PLATON_KEY_DESC', 'Ключ'); define('MODULE_PAYMENT_PLATON_PASSWORD_TITLE', 'Пароль'); define('MODULE_PAYMENT_PLATON_PASSWORD_DESC', 'Пароль'); define('MODULE_PAYMENT_PLATON_SORT_ORDER_TITLE', 'Порядок сортировки'); define('MODULE_PAYMENT_PLATON_SORT_ORDER_DESC', 'Порядок сортировки модуля.'); define('MODULE_PAYMENT_PLATON_ORDER_STATUS_TITLE', 'Статус оплаченного заказа'); define('MODULE_PAYMENT_PLATON_ORDER_STATUS_DESC', 'Статус, устанавливаемый заказу после успешной оплаты'); ?>
OSC-CMS/Shopping-Cart
modules/payment/platon/ru.php
PHP
gpl-2.0
1,645
// La generación de código T4 está habilitada para el modelo 'C:\Proyectos SVN\PRESTLAN\Models\PrestlanModel.edmx'. // Para habilitar la generación de código heredada, cambie el valor de la propiedad del diseñador 'Estrategia de generación de código' // por 'ObjectContext heredado'. Esta propiedad está disponible en la ventana Propiedades cuando se abre // el modelo en el diseñador. // Si no se ha generado ninguna clase de contexto y de entidad, puede que haya creado un modelo vacío pero // no haya elegido todavía la versión de Entity Framework que se va a usar. Para generar una clase de contexto y clases de entidad // para el modelo, abra el modelo en el diseñador, haga clic con el botón secundario en la superficie del diseñador y // seleccione 'Actualizar modelo desde base de datos...', 'Generar base de datos desde modelo...' o 'Agregar elemento de generación // de código...'.
alfre/Prestlan
Models/PrestlanModel.Designer.cs
C#
gpl-2.0
914
<?php // No direct access defined('_JEXEC') or die; jimport('joomla.application.component.view'); class PropertyViewAgent extends JView { protected $form; protected $item; protected $state; public function display($tpl = null) { // Initialiase variables. $this->form = $this->get('Form'); $this->item = $this->get('Item'); $this->state = $this->get('State'); // Check for errors. if (count($errors = $this->get('Errors'))) { JError::raiseError(500, implode("\n", $errors)); return false; } $this->addToolbar(); parent::display($tpl); } protected function addToolbar() { JRequest::setVar('hidemainmenu', true); $user = JFactory::getUser(); $isNew = ($this->item->id == 0); $checkedOut = !($this->item->checked_out == 0 || $this->item->checked_out == $user->get('id')); //$canDo = PropertyHelper::getActions($this->state->get('filter.category_id')); $canDo = PropertyMenuHelper::getActions(); JToolBarHelper::title($isNew ? JText::_('Add Agent') : JText::_('Edit Agent'), 'banners.png'); // If not checked out, can save the item. if (!$checkedOut && ($canDo->get('core.edit')||$canDo->get('core.create'))) { JToolBarHelper::apply('agent.apply', 'JTOOLBAR_APPLY'); JToolBarHelper::save('agent.save', 'JTOOLBAR_SAVE'); } if (!$checkedOut && $canDo->get('core.create')) { JToolBarHelper::custom('agent.save2new', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); } // If an existing item, can save to a copy. if (!$isNew && $canDo->get('core.create')) { JToolBarHelper::custom('agent.save2copy', 'save-copy.png', 'save-copy_f2.png', 'JTOOLBAR_SAVE_AS_COPY', false); } if (empty($this->item->id)) JToolBarHelper::cancel('agent.cancel','JTOOLBAR_CANCEL'); else JToolBarHelper::cancel('agent.cancel', 'JTOOLBAR_CLOSE'); JToolBarHelper::divider(); JToolBarHelper::help('Agent'); } }
djoudi/cambodian-property-today
administrator/components/com_property/views/agent/view.html.php
PHP
gpl-2.0
2,164
package com.savanto.correspondencechess; import android.content.Context; import android.view.MotionEvent; import android.view.View; import android.widget.RelativeLayout; /** * Extension of the View class to allow easy creation and manipulation * of views containing chess pieces. */ public class PieceView extends View { public PieceView(Context context) { super(context); } /** * Produces graphic chess PieceView from given Piece. * @param context * @param resid - the resource id of the Drawable to use for this PieceView. * @param size - the size to make the graphical PieceView. * @param coords - rank and file Coordinates of the piece on the board. */ public PieceView(Context context, int resid, final int size, final Coordinates coords) { super(context); // Set background to Drawable setBackgroundResource(resid); // Set position RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(size, size); lp.leftMargin = coords.x * size; lp.topMargin = coords.y * size; setLayoutParams(lp); // OnTouchListener listens for user interaction with the PieceView setOnTouchListener(new OnTouchListener() { // Initial position of the PieceView, prior to move. private int leftMargin, topMargin; @Override public boolean onTouch(View view, MotionEvent event) { // Get the PieceView being touched, and its LayoutParams for position updating. PieceView pieceView = (PieceView) view; RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) pieceView.getLayoutParams(); // Which touch event is occuring switch (event.getAction()) { // The touch has just started case MotionEvent.ACTION_DOWN: // PieceView has been touched. Bring it // in front of all other views. pieceView.bringToFront(); // Get the PieceView's parent and ask it to redraw itself. RelativeLayout parent = (RelativeLayout) pieceView.getParent(); parent.requestLayout(); parent.invalidate(); // TODO // Record PieceView's initial coordinates leftMargin = lp.leftMargin; topMargin = lp.topMargin; break; // The touch event continues case MotionEvent.ACTION_MOVE: // The PieceView is being moved. Update // its raw coordinates. lp.leftMargin = (int) event.getRawX() - size / 2; lp.topMargin = (int) event.getRawY() - size * 2; pieceView.setLayoutParams(lp); break; // The touch event ends case MotionEvent.ACTION_UP: // The PieceView is released. Calculate its // final position and set it down squarely. // TODO check for legality, captures, special moves (en passant, castle, promotion) if (false) { lp.leftMargin = leftMargin; lp.topMargin = topMargin; } else { // TODO record completed moves, allow step-by-step undo lp.leftMargin = (int) event.getRawX() / size * size; lp.topMargin = ((int) event.getRawY() / size - 1) * size; } pieceView.setLayoutParams(lp); break; } return true; } }); } }
savanto/CorrespondenceChess-Android
src/com/savanto/correspondencechess/PieceView.java
Java
gpl-2.0
3,118
/** * */ package fr.hervedarritchon.soe.soebackend.exception; /** * @author Hervé Darritchon (@hervDarritchon) * */ public class CannotCreateUserException extends Exception { public CannotCreateUserException(final String message) { super(message); } /** * */ private static final long serialVersionUID = -1655114199335112310L; }
herveDarritchon/soebackend
src/main/java/fr/hervedarritchon/soe/soebackend/exception/CannotCreateUserException.java
Java
gpl-2.0
349
#include "skewnessfeature.h" using Romeo::Model::Core::Feature::SkewnessFeature; using Romeo::Model::Core::Feature::StandardDeviationFeature; using Romeo::Model::Core::Feature::FirstOrderFeature; using Romeo::Model::Core::InternalData; using Romeo::Model::Core::InternalData2D; using Romeo::Model::Core::InternalData3D; using Romeo::Model::Core::Feature::MeanFeature; using Romeo::Model::Core::RGBImage2D; using Romeo::Model::Core::RGBImage3D; SkewnessFeature::SkewnessFeature(int idFeat) : FirstOrderFeature(Utils::FEATURE_SKEWNESS, idFeat){ } SkewnessFeature::SkewnessFeature(const QStringList& parameters, int idFeat) : FirstOrderFeature(Utils::FEATURE_SKEWNESS, parameters, idFeat) { } InternalData2D* SkewnessFeature::singleChannelEXecution2D(InternalData2D* channel) { InternalData2D::ImageType::Pointer image = channel->getImage(); MeanFeature meanFeature(getParameters()); InternalData2D::ImageType::Pointer meanImg = meanFeature.singleChannelEXecution2D(channel)->getImage(); StandardDeviationFeature stdDeviation(getParameters()); InternalData2D::ImageType::Pointer stdImg = stdDeviation.singleChannelEXecution2D(channel)->getImage(); InternalData2D* output = new InternalData2D(channel->getXSize(), channel->getYSize()); InternalData2D::ImageType::Pointer outputImg = output->getImage(); InternalData2D::NeighborhoodIteratorInternalType::RadiusType radius; radius.Fill(getWindowSize()/2); InternalData2D::NeighborhoodIteratorInternalType it(radius, image, image->GetRequestedRegion()); InternalData2D::RegionIteratorInternalType outIt(outputImg, outputImg->GetRequestedRegion()); InternalData2D::RegionIteratorInternalType meanIt(meanImg, meanImg->GetRequestedRegion()); InternalData2D::RegionIteratorInternalType stdIt(stdImg, stdImg->GetRequestedRegion()); int size = pow(getWindowSize(),2.0); for(it.GoToBegin(), outIt.GoToBegin(), meanIt.GoToBegin(), stdIt.GoToBegin(); !it.IsAtEnd(); ++it, ++outIt, ++meanIt,++stdIt) { // skewness float sum3 = 0; for(int i=0; i<size; ++i){ float meanValue = meanIt.Value(); float x = it.GetPixel(i) - meanValue; float y = pow(x,3.0); sum3 += y; } float stdValue = stdIt.Value(); float val3 = sum3 / size; float stdValueAllaTerza = pow(stdValue,3.0); outIt.Set(val3/stdValueAllaTerza); } //delete channel; return output; } InternalData3D* SkewnessFeature::singleChannelEXecution3D(InternalData3D* channel) { InternalData3D::ImageType::Pointer image = channel->getImage(); MeanFeature meanFeature(getParameters()); InternalData3D::ImageType::Pointer meanImg = meanFeature.singleChannelEXecution3D(channel)->getImage(); StandardDeviationFeature stdDeviation(getParameters()); InternalData3D::ImageType::Pointer stdImg = stdDeviation.singleChannelEXecution3D(channel)->getImage(); InternalData3D* output = new InternalData3D(channel->getXSize(), channel->getYSize(), channel->getZSize()); InternalData3D::ImageType::Pointer outputImg = output->getImage(); InternalData3D::NeighborhoodIteratorInternalType::RadiusType radius; radius.Fill(getWindowSize()/2); InternalData3D::NeighborhoodIteratorInternalType it(radius, image, image->GetRequestedRegion()); InternalData3D::RegionIteratorInternalType outIt(outputImg, outputImg->GetRequestedRegion()); InternalData3D::RegionIteratorInternalType meanIt(meanImg, meanImg->GetRequestedRegion()); InternalData3D::RegionIteratorInternalType stdIt(stdImg, stdImg->GetRequestedRegion()); int size = pow(getWindowSize(),3.0); for(it.GoToBegin(), outIt.GoToBegin(), meanIt.GoToBegin(), stdIt.GoToBegin(); !it.IsAtEnd(); ++it, ++outIt, ++meanIt,++stdIt) { // skewness float sum3 = 0; for(int i=0; i<size; ++i){ float meanValue = meanIt.Value(); float x = it.GetPixel(i) - meanValue; float y = pow(x,3.0); sum3 += y; } float stdValue = stdIt.Value(); float val3 = sum3 / size; float stdValueAllaTerza = pow(stdValue,3.0); outIt.Set(val3/stdValueAllaTerza); } //delete channel; return output; } SkewnessFeature::~SkewnessFeature() { }
NicolaMagnabosco/Romeo
RomeoCode/model/core/feature/skewnessfeature.cpp
C++
gpl-2.0
4,479
#include <iostream> #include <ctime> #include <QString> #include <QInputDialog> #include "mainwindow.h" #include "ui_mainwindow.h" #include "solution.hpp" MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); results = new ResultsModel(); ui->resultsView->setModel(results); ui->resultsView->verticalHeader()->hide(); } MainWindow::~MainWindow() { delete ui; delete results; } void MainWindow::on_actionRun_test_Solution_triggered() { // std::cout << "0\t60\t3600\t3600000\t143412" << std::endl; // std::cout << Solution::TimeToString(0) << std::endl; // std::cout << Solution::TimeToString(3600) << std::endl; // std::cout << Solution::TimeToString(3600000) << std::endl; // std::cout << Solution::TimeToString(143412) << std::endl; } void MainWindow::on_actionRun_test_ResultsModel_triggered() { Solution s(time(NULL), time(NULL) + 12454, "asdasd", ""); results->addSolution(s); s.setStart(s.getEnd() + 1000); s.setEnd(s.getStart() + 10000); results->addSolution(s); results->addSolution(Solution(time(NULL) + 1400, time(NULL) + 5000)); results->addSolution(Solution(time(NULL) + 1700, time(NULL) + 8500)); results->addSolution(Solution(time(NULL) + 5000, time(NULL) + 10544)); } void MainWindow::on_actionAdd_time_triggered() { QString t = QInputDialog::getText(NULL, "ASD", "asd"); long int tm = atoi(t.toStdString().c_str()); results->addSolution(Solution(time(NULL) - tm, time(NULL))); }
trombipeti/qbtimer
mainwindow.cpp
C++
gpl-2.0
1,568
package com.aifeng.ws.wx; import java.util.Map; /** * Created by pro on 17-4-17. */ public class RequestBody { private String touser; private String msgtype; private int agentid; private Map<String,Object> text; private int safe; public String getTouser() { return touser; } public void setTouser(String touser) { this.touser = touser; } public String getMsgtype() { return msgtype; } public void setMsgtype(String msgtype) { this.msgtype = msgtype; } public int getAgentid() { return agentid; } public void setAgentid(int agentid) { this.agentid = agentid; } public Map<String, Object> getText() { return text; } public void setText(Map<String, Object> text) { this.text = text; } public int getSafe() { return safe; } public void setSafe(int safe) { this.safe = safe; } }
dunyuling/cxh
src/main/java/com/aifeng/ws/wx/RequestBody.java
Java
gpl-2.0
974
/* * This is the source code of Telegram for Android v. 5.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2018. */ package org.telegram.ui.Cells; import android.content.Context; import android.graphics.Canvas; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.text.TextUtils; import android.util.TypedValue; import android.view.Gravity; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import org.telegram.messenger.AndroidUtilities; import org.telegram.messenger.LocaleController; import org.telegram.messenger.R; import org.telegram.ui.ActionBar.Theme; import org.telegram.ui.Components.LayoutHelper; import org.telegram.ui.Components.Switch; public class NotificationsCheckCell extends FrameLayout { private TextView textView; private TextView valueTextView; @SuppressWarnings("FieldCanBeLocal") private ImageView moveImageView; private Switch checkBox; private boolean needDivider; private boolean drawLine = true; private boolean isMultiline; private int currentHeight; public NotificationsCheckCell(Context context) { this(context, 21, 70, false); } public NotificationsCheckCell(Context context, int padding, int height, boolean reorder) { super(context); setWillNotDraw(false); currentHeight = height; if (reorder) { moveImageView = new ImageView(context); moveImageView.setFocusable(false); moveImageView.setScaleType(ImageView.ScaleType.CENTER); moveImageView.setImageResource(R.drawable.poll_reorder); moveImageView.setColorFilter(new PorterDuffColorFilter(Theme.getColor(Theme.key_windowBackgroundWhiteGrayIcon), PorterDuff.Mode.MULTIPLY)); addView(moveImageView, LayoutHelper.createFrame(48, 48, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL, 6, 0, 6, 0)); } textView = new TextView(context); textView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteBlackText)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setLines(1); textView.setMaxLines(1); textView.setSingleLine(true); textView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.CENTER_VERTICAL); textView.setEllipsize(TextUtils.TruncateAt.END); addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 80 : (reorder ? 64 : 23), 13 + (currentHeight - 70) / 2, LocaleController.isRTL ? (reorder ? 64 : 23) : 80, 0)); valueTextView = new TextView(context); valueTextView.setTextColor(Theme.getColor(Theme.key_windowBackgroundWhiteGrayText2)); valueTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 13); valueTextView.setGravity(LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT); valueTextView.setLines(1); valueTextView.setMaxLines(1); valueTextView.setSingleLine(true); valueTextView.setPadding(0, 0, 0, 0); valueTextView.setEllipsize(TextUtils.TruncateAt.END); addView(valueTextView, LayoutHelper.createFrame(LayoutHelper.WRAP_CONTENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, LocaleController.isRTL ? 80 : (reorder ? 64 : 23), 38 + (currentHeight - 70) / 2, LocaleController.isRTL ? (reorder ? 64 : 23) : 80, 0)); checkBox = new Switch(context); checkBox.setColors(Theme.key_switchTrack, Theme.key_switchTrackChecked, Theme.key_windowBackgroundWhite, Theme.key_windowBackgroundWhite); addView(checkBox, LayoutHelper.createFrame(37, 40, (LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.CENTER_VERTICAL, 21, 0, 21, 0)); checkBox.setFocusable(true); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (isMultiline) { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); } else { super.onMeasure(MeasureSpec.makeMeasureSpec(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(AndroidUtilities.dp(currentHeight), MeasureSpec.EXACTLY)); } } public void setTextAndValueAndCheck(String text, CharSequence value, boolean checked, boolean divider) { setTextAndValueAndCheck(text, value, checked, 0, false, divider); } public void setTextAndValueAndCheck(String text, CharSequence value, boolean checked, int iconType, boolean divider) { setTextAndValueAndCheck(text, value, checked, iconType, false, divider); } public void setTextAndValueAndCheck(String text, CharSequence value, boolean checked, int iconType, boolean multiline, boolean divider) { textView.setText(text); valueTextView.setText(value); checkBox.setChecked(checked, iconType, false); valueTextView.setVisibility(VISIBLE); needDivider = divider; isMultiline = multiline; if (multiline) { valueTextView.setLines(0); valueTextView.setMaxLines(0); valueTextView.setSingleLine(false); valueTextView.setEllipsize(null); valueTextView.setPadding(0, 0, 0, AndroidUtilities.dp(14)); } else { valueTextView.setLines(1); valueTextView.setMaxLines(1); valueTextView.setSingleLine(true); valueTextView.setEllipsize(TextUtils.TruncateAt.END); valueTextView.setPadding(0, 0, 0, 0); } checkBox.setContentDescription(text); } public void setDrawLine(boolean value) { drawLine = value; } public void setChecked(boolean checked) { checkBox.setChecked(checked, true); } public void setChecked(boolean checked, int iconType) { checkBox.setChecked(checked, iconType, true); } public boolean isChecked() { return checkBox.isChecked(); } @Override protected void onDraw(Canvas canvas) { if (needDivider) { canvas.drawLine(LocaleController.isRTL ? 0 : AndroidUtilities.dp(20), getMeasuredHeight() - 1, getMeasuredWidth() - (LocaleController.isRTL ? AndroidUtilities.dp(20) : 0), getMeasuredHeight() - 1, Theme.dividerPaint); } if (drawLine) { int x = LocaleController.isRTL ? AndroidUtilities.dp(76) : getMeasuredWidth() - AndroidUtilities.dp(76) - 1; int y = (getMeasuredHeight() - AndroidUtilities.dp(22)) / 2; canvas.drawRect(x, y, x + 2, y + AndroidUtilities.dp(22), Theme.dividerPaint); } } }
CzBiX/Telegram
TMessagesProj/src/main/java/org/telegram/ui/Cells/NotificationsCheckCell.java
Java
gpl-2.0
7,049
<?php if (cfr('BACKUP')) { set_time_limit(0); $alterConf = $ubillingConfig->getAlter(); if (!wf_CheckGet(array('restore'))) { if (isset($_POST['createbackup'])) { if (isset($_POST['imready'])) { if (!empty($alterConf['MYSQLDUMP_PATH'])) { //run system mysqldump command zb_backup_database(); } else { show_error(__('You missed an important option') . ': MYSQLDUMP_PATH'); } } else { show_error(__('You are not mentally prepared for this')); } } //downloading mysql dump if (wf_CheckGet(array('download'))) { if (cfr('ROOT')) { $filePath = base64_decode($_GET['download']); zb_DownloadFile($filePath); } else { show_error(__('Access denied')); } } //deleting dump if (wf_CheckGet(array('deletedump'))) { if (cfr('ROOT')) { $deletePath = base64_decode($_GET['deletedump']); if (file_exists($deletePath)) { rcms_delete_files($deletePath); log_register('BACKUP DELETE `' . $deletePath . '`'); rcms_redirect('?module=backups'); } else { show_error(__('Not existing item')); } } else { show_error(__('Access denied')); } } function web_AvailableDBBackupsList() { $backupsPath = DATA_PATH . 'backups/sql/'; $availbacks = rcms_scandir($backupsPath); $messages = new UbillingMessageHelper(); $result = $messages->getStyledMessage(__('No existing DB backups here'), 'warning'); if (!empty($availbacks)) { $cells = wf_TableCell(__('Date')); $cells.= wf_TableCell(__('Size')); $cells.= wf_TableCell(__('Filename')); $cells.= wf_TableCell(__('Actions')); $rows = wf_TableRow($cells, 'row1'); foreach ($availbacks as $eachDump) { $fileDate = filectime($backupsPath . $eachDump); $fileDate = date("Y-m-d H:i:s", $fileDate); $fileSize = filesize($backupsPath . $eachDump); $fileSize = stg_convert_size($fileSize); $encodedDumpPath = base64_encode($backupsPath . $eachDump); $downloadLink = wf_Link('?module=backups&download=' . $encodedDumpPath, $eachDump, false, ''); $actLinks = wf_JSAlert('?module=backups&deletedump=' . $encodedDumpPath, web_delete_icon(), __('Removing this may lead to irreparable results')) . ' '; $actLinks.= wf_Link('?module=backups&download=' . $encodedDumpPath, wf_img('skins/icon_download.png', __('Download')), false, ''); $actLinks.= wf_JSAlert('?module=backups&restore=true&restoredump=' . $encodedDumpPath, wf_img('skins/icon_restoredb.png', __('Restore DB')), __('Are you serious')); $cells = wf_TableCell($fileDate); $cells.= wf_TableCell($fileSize); $cells.= wf_TableCell($downloadLink); $cells.= wf_TableCell($actLinks); $rows.= wf_TableRow($cells, 'row3'); } $result = wf_TableBody($rows, '100%', '0', 'sortable'); } return ($result); } function web_ConfigsUbillingList() { $downloadable = array( 'config/billing.ini', 'config/mysql.ini', 'config/alter.ini', 'config/ymaps.ini', 'config/catv.ini', 'config/photostorage.ini', 'config/dhcp/global.template', 'config/dhcp/subnets.template', 'config/dhcp/option82.template', 'config/dhcp/option82_vpu.template', 'userstats/config/mysql.ini', 'userstats/config/userstats.ini', 'userstats/config/tariffmatrix.ini' ); if (!empty($downloadable)) { $cells = wf_TableCell(__('Date')); $cells.= wf_TableCell(__('Size')); $cells.= wf_TableCell(__('Filename')); $rows = wf_TableRow($cells, 'row1'); foreach ($downloadable as $eachConfig) { if (file_exists($eachConfig)) { $fileDate = filectime($eachConfig); $fileDate = date("Y-m-d H:i:s", $fileDate); $fileSize = filesize($eachConfig); $fileSize = stg_convert_size($fileSize); $downloadLink = wf_Link('?module=backups&download=' . base64_encode($eachConfig), $eachConfig, false, ''); $cells = wf_TableCell($fileDate); $cells.= wf_TableCell($fileSize); $cells.= wf_TableCell($downloadLink); $rows.= wf_TableRow($cells, 'row3'); } else { $cells = wf_TableCell(''); $cells.= wf_TableCell(''); $cells.= wf_TableCell($eachConfig); $rows.= wf_TableRow($cells, 'row3'); } } $result = wf_TableBody($rows, '100%', '0', 'sortable'); } return ($result); } //tables cleanup if (wf_CheckGet(array('tableclean'))) { zb_DBTableCleanup($_GET['tableclean']); rcms_redirect("?module=backups"); } show_window(__('Create backup'), web_BackupForm()); show_window(__('Available database backups'), web_AvailableDBBackupsList()); show_window(__('Important Ubilling configs'), web_ConfigsUbillingList()); show_window(__('Database cleanup'), web_DBCleanupForm()); } else { //database restoration functionality if (cfr('ROOT')) { if (!empty($alterConf['MYSQL_PATH'])) { if (wf_CheckGet(array('restoredump'))) { $mysqlConf = rcms_parse_ini_file(CONFIG_PATH . 'mysql.ini'); $billingConf = $ubillingConfig->getBilling(); $restoreFilename = base64_decode($_GET['restoredump']); if (file_exists($restoreFilename)) { if (($billingConf['NOSTGCHECKPID']) AND ( !file_exists($billingConf['STGPID']))) { if (!isset($_POST['lastchanceok'])) { $lastChanceInputs = __('Restoring a database from a dump, completely and permanently destroy your current database. Think again if you really want it.'); $lastChanceInputs.=wf_tag('br'); $lastChanceInputs.=__('Filename') . ': ' . $restoreFilename; $lastChanceInputs.=wf_tag('br'); $lastChanceInputs.= wf_CheckInput('lastchanceok', __('I`m ready'), true, false); $lastChanceInputs.= wf_Submit(__('Restore DB')); $lastChanceForm = wf_Form('', 'POST', $lastChanceInputs, 'glamour'); show_window(__('Warning'), $lastChanceForm); show_window('', wf_BackLink('?module=backups', __('Back'), true, 'ubButton')); } else { $restoreCommand = $alterConf['MYSQL_PATH'] . ' -u ' . $mysqlConf['username'] . ' -p' . $mysqlConf['password'] . ' ' . $mysqlConf['db'] . ' --default-character-set=utf8 < ' . $restoreFilename; show_window(__('Result'), shell_exec($restoreCommand)); } } else { log_register("BACKUP RESTORE TRY WITH RUNNING STARGAZER"); show_error(__('You can restore database only with enabled NOSTGCHECKPID option and stopped Stargazer')); show_window('', wf_BackLink('?module=backups', __('Back'), true, 'ubButton')); } } else { show_error(__('Strange exeption') . ': NOT_EXISTING_DUMP_FILE'); } } else { show_error(__('Strange exeption') . ': GET_NO_DUMP_FILENAME'); } } else { show_error(__('You missed an important option') . ': MYSQL_PATH'); } } else { show_error(__('You cant control this module')); } ////////////////////////////////////////////////////// } } else { show_error(__('You cant control this module')); } ?>
pautiina/Ubilling
modules/general/backups/index.php
PHP
gpl-2.0
9,024
jQuery(document).ready( function($) { $('#bp-forum-notifier-toggle-subscription').live('click', function(e) { e.preventDefault(); var subscribe_or_unsubscribe = $(this).data('action'); var nonce = $(this).data('nonce'); var group_id = $(this).data('group_id'); $.ajax({ type: "POST", url: ajaxurl, data: { action: 'bp_forum_notifier_toggle_subscription', nonce: nonce, group_id: group_id, subscribe_or_unsubscribe: subscribe_or_unsubscribe, }, success: function(response) { if ( response[0] != '-' ) { $('#bp-forum-notifier-wrapper').html(response); } } },"JSON"); }); // since this plugin handles the mailsubscriptions, lets remove the checkbox from the form. $('#bbp_topic_subscription').remove(); $("label[for='bbp_topic_subscription']").remove(); });
klandestino/bp-forum-notifier
js/bp-forum-notifier.js
JavaScript
gpl-2.0
821
// Copyright 2015 Dolphin Emulator Project // Licensed under GPLv2+ // Refer to the license.txt file included. #include "VideoCommon/VertexLoaderARM64.h" #include "Common/CommonTypes.h" #include "VideoCommon/DataReader.h" #include "VideoCommon/VertexLoaderManager.h" using namespace Arm64Gen; constexpr ARM64Reg src_reg = X0; constexpr ARM64Reg dst_reg = X1; constexpr ARM64Reg count_reg = W2; constexpr ARM64Reg skipped_reg = W17; constexpr ARM64Reg scratch1_reg = W16; constexpr ARM64Reg scratch2_reg = W15; constexpr ARM64Reg scratch3_reg = W14; constexpr ARM64Reg saved_count = W12; constexpr ARM64Reg stride_reg = X11; constexpr ARM64Reg arraybase_reg = X10; constexpr ARM64Reg scale_reg = X9; alignas(16) static const float scale_factors[] = { 1.0 / (1ULL << 0), 1.0 / (1ULL << 1), 1.0 / (1ULL << 2), 1.0 / (1ULL << 3), 1.0 / (1ULL << 4), 1.0 / (1ULL << 5), 1.0 / (1ULL << 6), 1.0 / (1ULL << 7), 1.0 / (1ULL << 8), 1.0 / (1ULL << 9), 1.0 / (1ULL << 10), 1.0 / (1ULL << 11), 1.0 / (1ULL << 12), 1.0 / (1ULL << 13), 1.0 / (1ULL << 14), 1.0 / (1ULL << 15), 1.0 / (1ULL << 16), 1.0 / (1ULL << 17), 1.0 / (1ULL << 18), 1.0 / (1ULL << 19), 1.0 / (1ULL << 20), 1.0 / (1ULL << 21), 1.0 / (1ULL << 22), 1.0 / (1ULL << 23), 1.0 / (1ULL << 24), 1.0 / (1ULL << 25), 1.0 / (1ULL << 26), 1.0 / (1ULL << 27), 1.0 / (1ULL << 28), 1.0 / (1ULL << 29), 1.0 / (1ULL << 30), 1.0 / (1ULL << 31), }; VertexLoaderARM64::VertexLoaderARM64(const TVtxDesc& vtx_desc, const VAT& vtx_att) : VertexLoaderBase(vtx_desc, vtx_att), m_float_emit(this) { if (!IsInitialized()) return; AllocCodeSpace(4096); ClearCodeSpace(); GenerateVertexLoader(); WriteProtect(); } void VertexLoaderARM64::GetVertexAddr(int array, u64 attribute, ARM64Reg reg) { if (attribute & MASK_INDEXED) { if (attribute == INDEX8) { if (m_src_ofs < 4096) { LDRB(IndexType::Unsigned, scratch1_reg, src_reg, m_src_ofs); } else { ADD(reg, src_reg, m_src_ofs); LDRB(IndexType::Unsigned, scratch1_reg, reg, 0); } m_src_ofs += 1; } else { if (m_src_ofs < 256) { LDURH(scratch1_reg, src_reg, m_src_ofs); } else if (m_src_ofs <= 8190 && !(m_src_ofs & 1)) { LDRH(IndexType::Unsigned, scratch1_reg, src_reg, m_src_ofs); } else { ADD(reg, src_reg, m_src_ofs); LDRH(IndexType::Unsigned, scratch1_reg, reg, 0); } m_src_ofs += 2; REV16(scratch1_reg, scratch1_reg); } if (array == ARRAY_POSITION) { EOR(scratch2_reg, scratch1_reg, 0, attribute == INDEX8 ? 7 : 15); // 0xFF : 0xFFFF m_skip_vertex = CBZ(scratch2_reg); } LDR(IndexType::Unsigned, scratch2_reg, stride_reg, array * 4); MUL(scratch1_reg, scratch1_reg, scratch2_reg); LDR(IndexType::Unsigned, EncodeRegTo64(scratch2_reg), arraybase_reg, array * 8); ADD(EncodeRegTo64(reg), EncodeRegTo64(scratch1_reg), EncodeRegTo64(scratch2_reg)); } else ADD(reg, src_reg, m_src_ofs); } s32 VertexLoaderARM64::GetAddressImm(int array, u64 attribute, Arm64Gen::ARM64Reg reg, u32 align) { if (attribute & MASK_INDEXED || (m_src_ofs > 255 && (m_src_ofs & (align - 1)))) GetVertexAddr(array, attribute, reg); else return m_src_ofs; return -1; } int VertexLoaderARM64::ReadVertex(u64 attribute, int format, int count_in, int count_out, bool dequantize, u8 scaling_exponent, AttributeFormat* native_format, s32 offset) { ARM64Reg coords = count_in == 3 ? Q31 : D31; ARM64Reg scale = count_in == 3 ? Q30 : D30; int elem_size = 1 << (format / 2); int load_bytes = elem_size * count_in; int load_size = load_bytes == 1 ? 1 : load_bytes <= 2 ? 2 : load_bytes <= 4 ? 4 : load_bytes <= 8 ? 8 : 16; load_size <<= 3; elem_size <<= 3; if (offset == -1) { if (count_in == 1) m_float_emit.LDR(elem_size, IndexType::Unsigned, coords, EncodeRegTo64(scratch1_reg), 0); else m_float_emit.LD1(elem_size, 1, coords, EncodeRegTo64(scratch1_reg)); } else if (offset & (load_size - 1)) // Not aligned - unscaled { m_float_emit.LDUR(load_size, coords, src_reg, offset); } else { m_float_emit.LDR(load_size, IndexType::Unsigned, coords, src_reg, offset); } if (format != FORMAT_FLOAT) { // Extend and convert to float switch (format) { case FORMAT_UBYTE: m_float_emit.UXTL(8, EncodeRegToDouble(coords), EncodeRegToDouble(coords)); m_float_emit.UXTL(16, EncodeRegToDouble(coords), EncodeRegToDouble(coords)); break; case FORMAT_BYTE: m_float_emit.SXTL(8, EncodeRegToDouble(coords), EncodeRegToDouble(coords)); m_float_emit.SXTL(16, EncodeRegToDouble(coords), EncodeRegToDouble(coords)); break; case FORMAT_USHORT: m_float_emit.REV16(8, EncodeRegToDouble(coords), EncodeRegToDouble(coords)); m_float_emit.UXTL(16, EncodeRegToDouble(coords), EncodeRegToDouble(coords)); break; case FORMAT_SHORT: m_float_emit.REV16(8, EncodeRegToDouble(coords), EncodeRegToDouble(coords)); m_float_emit.SXTL(16, EncodeRegToDouble(coords), EncodeRegToDouble(coords)); break; } m_float_emit.SCVTF(32, coords, coords); if (dequantize && scaling_exponent) { m_float_emit.LDR(32, IndexType::Unsigned, scale, scale_reg, scaling_exponent * 4); m_float_emit.FMUL(32, coords, coords, scale, 0); } } else { m_float_emit.REV32(8, coords, coords); } const u32 write_size = count_out == 3 ? 128 : count_out * 32; const u32 mask = count_out == 3 ? 0xF : count_out == 2 ? 0x7 : 0x3; if (m_dst_ofs < 256) { m_float_emit.STUR(write_size, coords, dst_reg, m_dst_ofs); } else if (!(m_dst_ofs & mask)) { m_float_emit.STR(write_size, IndexType::Unsigned, coords, dst_reg, m_dst_ofs); } else { ADD(EncodeRegTo64(scratch2_reg), dst_reg, m_dst_ofs); m_float_emit.ST1(32, 1, coords, EncodeRegTo64(scratch2_reg)); } // Z-Freeze if (native_format == &m_native_vtx_decl.position) { CMP(count_reg, 3); FixupBranch dont_store = B(CC_GT); MOVP2R(EncodeRegTo64(scratch2_reg), VertexLoaderManager::position_cache); ADD(EncodeRegTo64(scratch1_reg), EncodeRegTo64(scratch2_reg), EncodeRegTo64(count_reg), ArithOption(EncodeRegTo64(count_reg), ShiftType::LSL, 4)); m_float_emit.STUR(write_size, coords, EncodeRegTo64(scratch1_reg), -16); SetJumpTarget(dont_store); } native_format->components = count_out; native_format->enable = true; native_format->offset = m_dst_ofs; native_format->type = VAR_FLOAT; native_format->integer = false; m_dst_ofs += sizeof(float) * count_out; if (attribute == DIRECT) m_src_ofs += load_bytes; return load_bytes; } void VertexLoaderARM64::ReadColor(u64 attribute, int format, s32 offset) { int load_bytes = 0; switch (format) { case FORMAT_24B_888: case FORMAT_32B_888x: case FORMAT_32B_8888: if (offset == -1) LDR(IndexType::Unsigned, scratch2_reg, EncodeRegTo64(scratch1_reg), 0); else if (offset & 3) // Not aligned - unscaled LDUR(scratch2_reg, src_reg, offset); else LDR(IndexType::Unsigned, scratch2_reg, src_reg, offset); if (format != FORMAT_32B_8888) ORRI2R(scratch2_reg, scratch2_reg, 0xFF000000); STR(IndexType::Unsigned, scratch2_reg, dst_reg, m_dst_ofs); load_bytes = 3 + (format != FORMAT_24B_888); break; case FORMAT_16B_565: // RRRRRGGG GGGBBBBB // AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR if (offset == -1) LDRH(IndexType::Unsigned, scratch3_reg, EncodeRegTo64(scratch1_reg), 0); else if (offset & 1) // Not aligned - unscaled LDURH(scratch3_reg, src_reg, offset); else LDRH(IndexType::Unsigned, scratch3_reg, src_reg, offset); REV16(scratch3_reg, scratch3_reg); // B AND(scratch2_reg, scratch3_reg, 32, 4); ORR(scratch2_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 3)); ORR(scratch2_reg, scratch2_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 5)); ORR(scratch1_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 16)); // G UBFM(scratch2_reg, scratch3_reg, 5, 10); ORR(scratch2_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 2)); ORR(scratch2_reg, scratch2_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 6)); ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 8)); // R UBFM(scratch2_reg, scratch3_reg, 11, 15); ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 3)); ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 2)); // A ORRI2R(scratch1_reg, scratch1_reg, 0xFF000000); STR(IndexType::Unsigned, scratch1_reg, dst_reg, m_dst_ofs); load_bytes = 2; break; case FORMAT_16B_4444: // BBBBAAAA RRRRGGGG // REV16 - RRRRGGGG BBBBAAAA // AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR if (offset == -1) LDRH(IndexType::Unsigned, scratch3_reg, EncodeRegTo64(scratch1_reg), 0); else if (offset & 1) // Not aligned - unscaled LDURH(scratch3_reg, src_reg, offset); else LDRH(IndexType::Unsigned, scratch3_reg, src_reg, offset); // R UBFM(scratch1_reg, scratch3_reg, 4, 7); // G AND(scratch2_reg, scratch3_reg, 32, 3); ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 8)); // B UBFM(scratch2_reg, scratch3_reg, 12, 15); ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 16)); // A UBFM(scratch2_reg, scratch3_reg, 8, 11); ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 24)); // Final duplication ORR(scratch1_reg, scratch1_reg, scratch1_reg, ArithOption(scratch1_reg, ShiftType::LSL, 4)); STR(IndexType::Unsigned, scratch1_reg, dst_reg, m_dst_ofs); load_bytes = 2; break; case FORMAT_24B_6666: // RRRRRRGG GGGGBBBB BBAAAAAA // AAAAAAAA BBBBBBBB GGGGGGGG RRRRRRRR if (offset == -1) { LDUR(scratch3_reg, EncodeRegTo64(scratch1_reg), -1); } else { offset -= 1; if (offset & 3) // Not aligned - unscaled LDUR(scratch3_reg, src_reg, offset); else LDR(IndexType::Unsigned, scratch3_reg, src_reg, offset); } REV32(scratch3_reg, scratch3_reg); // A UBFM(scratch2_reg, scratch3_reg, 0, 5); ORR(scratch2_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 2)); ORR(scratch2_reg, scratch2_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 6)); ORR(scratch1_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 24)); // B UBFM(scratch2_reg, scratch3_reg, 6, 11); ORR(scratch2_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 2)); ORR(scratch2_reg, scratch2_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 6)); ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 16)); // G UBFM(scratch2_reg, scratch3_reg, 12, 17); ORR(scratch2_reg, WSP, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 2)); ORR(scratch2_reg, scratch2_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 6)); ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 8)); // R UBFM(scratch2_reg, scratch3_reg, 18, 23); ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSL, 2)); ORR(scratch1_reg, scratch1_reg, scratch2_reg, ArithOption(scratch2_reg, ShiftType::LSR, 4)); STR(IndexType::Unsigned, scratch1_reg, dst_reg, m_dst_ofs); load_bytes = 3; break; } if (attribute == DIRECT) m_src_ofs += load_bytes; } void VertexLoaderARM64::GenerateVertexLoader() { // R0 - Source pointer // R1 - Destination pointer // R2 - Count // R30 - LR // // R0 return how many // // Registers we don't have to worry about saving // R9-R17 are caller saved temporaries // R18 is a temporary or platform specific register(iOS) // // VFP registers // We can touch all except v8-v15 // If we need to use those, we need to retain the lower 64bits(!) of the register const u64 tc[8] = { m_VtxDesc.Tex0Coord, m_VtxDesc.Tex1Coord, m_VtxDesc.Tex2Coord, m_VtxDesc.Tex3Coord, m_VtxDesc.Tex4Coord, m_VtxDesc.Tex5Coord, m_VtxDesc.Tex6Coord, m_VtxDesc.Tex7Coord, }; bool has_tc = false; bool has_tc_scale = false; for (int i = 0; i < 8; i++) { has_tc |= tc[i] != 0; has_tc_scale |= !!m_VtxAttr.texCoord[i].Frac; } bool need_scale = (m_VtxAttr.ByteDequant && m_VtxAttr.PosFrac) || (has_tc && has_tc_scale) || m_VtxDesc.Normal; AlignCode16(); if (m_VtxDesc.Position & MASK_INDEXED) MOV(skipped_reg, WZR); MOV(saved_count, count_reg); MOVP2R(stride_reg, g_main_cp_state.array_strides); MOVP2R(arraybase_reg, VertexLoaderManager::cached_arraybases); if (need_scale) MOVP2R(scale_reg, scale_factors); const u8* loop_start = GetCodePtr(); if (m_VtxDesc.PosMatIdx) { LDRB(IndexType::Unsigned, scratch1_reg, src_reg, m_src_ofs); AND(scratch1_reg, scratch1_reg, 0, 5); STR(IndexType::Unsigned, scratch1_reg, dst_reg, m_dst_ofs); // Z-Freeze CMP(count_reg, 3); FixupBranch dont_store = B(CC_GT); MOVP2R(EncodeRegTo64(scratch2_reg), VertexLoaderManager::position_matrix_index); STR(IndexType::Unsigned, scratch1_reg, EncodeRegTo64(scratch2_reg), 0); SetJumpTarget(dont_store); m_native_components |= VB_HAS_POSMTXIDX; m_native_vtx_decl.posmtx.components = 4; m_native_vtx_decl.posmtx.enable = true; m_native_vtx_decl.posmtx.offset = m_dst_ofs; m_native_vtx_decl.posmtx.type = VAR_UNSIGNED_BYTE; m_native_vtx_decl.posmtx.integer = true; m_src_ofs += sizeof(u8); m_dst_ofs += sizeof(u32); } u32 texmatidx_ofs[8]; const u64 tm[8] = { m_VtxDesc.Tex0MatIdx, m_VtxDesc.Tex1MatIdx, m_VtxDesc.Tex2MatIdx, m_VtxDesc.Tex3MatIdx, m_VtxDesc.Tex4MatIdx, m_VtxDesc.Tex5MatIdx, m_VtxDesc.Tex6MatIdx, m_VtxDesc.Tex7MatIdx, }; for (int i = 0; i < 8; i++) { if (tm[i]) texmatidx_ofs[i] = m_src_ofs++; } // Position { int elem_size = 1 << (m_VtxAttr.PosFormat / 2); int load_bytes = elem_size * (m_VtxAttr.PosElements + 2); int load_size = load_bytes == 1 ? 1 : load_bytes <= 2 ? 2 : load_bytes <= 4 ? 4 : load_bytes <= 8 ? 8 : 16; load_size <<= 3; s32 offset = GetAddressImm(ARRAY_POSITION, m_VtxDesc.Position, EncodeRegTo64(scratch1_reg), load_size); int pos_elements = m_VtxAttr.PosElements + 2; ReadVertex(m_VtxDesc.Position, m_VtxAttr.PosFormat, pos_elements, pos_elements, m_VtxAttr.ByteDequant, m_VtxAttr.PosFrac, &m_native_vtx_decl.position, offset); } if (m_VtxDesc.Normal) { static const u8 map[8] = {7, 6, 15, 14}; u8 scaling_exponent = map[m_VtxAttr.NormalFormat]; s32 offset = -1; for (int i = 0; i < (m_VtxAttr.NormalElements ? 3 : 1); i++) { if (!i || m_VtxAttr.NormalIndex3) { int elem_size = 1 << (m_VtxAttr.NormalFormat / 2); int load_bytes = elem_size * 3; int load_size = load_bytes == 1 ? 1 : load_bytes <= 2 ? 2 : load_bytes <= 4 ? 4 : load_bytes <= 8 ? 8 : 16; offset = GetAddressImm(ARRAY_NORMAL, m_VtxDesc.Normal, EncodeRegTo64(scratch1_reg), load_size << 3); if (offset == -1) ADD(EncodeRegTo64(scratch1_reg), EncodeRegTo64(scratch1_reg), i * elem_size * 3); else offset += i * elem_size * 3; } int bytes_read = ReadVertex(m_VtxDesc.Normal, m_VtxAttr.NormalFormat, 3, 3, true, scaling_exponent, &m_native_vtx_decl.normals[i], offset); if (offset == -1) ADD(EncodeRegTo64(scratch1_reg), EncodeRegTo64(scratch1_reg), bytes_read); else offset += bytes_read; } m_native_components |= VB_HAS_NRM0; if (m_VtxAttr.NormalElements) m_native_components |= VB_HAS_NRM1 | VB_HAS_NRM2; } const u64 col[2] = {m_VtxDesc.Color0, m_VtxDesc.Color1}; for (int i = 0; i < 2; i++) { m_native_vtx_decl.colors[i].components = 4; m_native_vtx_decl.colors[i].type = VAR_UNSIGNED_BYTE; m_native_vtx_decl.colors[i].integer = false; if (col[i]) { u32 align = 4; if (m_VtxAttr.color[i].Comp == FORMAT_16B_565 || m_VtxAttr.color[i].Comp == FORMAT_16B_4444) align = 2; s32 offset = GetAddressImm(ARRAY_COLOR + i, col[i], EncodeRegTo64(scratch1_reg), align); ReadColor(col[i], m_VtxAttr.color[i].Comp, offset); m_native_components |= VB_HAS_COL0 << i; m_native_vtx_decl.colors[i].components = 4; m_native_vtx_decl.colors[i].enable = true; m_native_vtx_decl.colors[i].offset = m_dst_ofs; m_native_vtx_decl.colors[i].type = VAR_UNSIGNED_BYTE; m_native_vtx_decl.colors[i].integer = false; m_dst_ofs += 4; } } for (int i = 0; i < 8; i++) { m_native_vtx_decl.texcoords[i].offset = m_dst_ofs; m_native_vtx_decl.texcoords[i].type = VAR_FLOAT; m_native_vtx_decl.texcoords[i].integer = false; int elements = m_VtxAttr.texCoord[i].Elements + 1; if (tc[i]) { m_native_components |= VB_HAS_UV0 << i; int elem_size = 1 << (m_VtxAttr.texCoord[i].Format / 2); int load_bytes = elem_size * (elements + 2); int load_size = load_bytes == 1 ? 1 : load_bytes <= 2 ? 2 : load_bytes <= 4 ? 4 : load_bytes <= 8 ? 8 : 16; load_size <<= 3; s32 offset = GetAddressImm(ARRAY_TEXCOORD0 + i, tc[i], EncodeRegTo64(scratch1_reg), load_size); u8 scaling_exponent = m_VtxAttr.texCoord[i].Frac; ReadVertex(tc[i], m_VtxAttr.texCoord[i].Format, elements, tm[i] ? 2 : elements, m_VtxAttr.ByteDequant, scaling_exponent, &m_native_vtx_decl.texcoords[i], offset); } if (tm[i]) { m_native_components |= VB_HAS_TEXMTXIDX0 << i; m_native_vtx_decl.texcoords[i].components = 3; m_native_vtx_decl.texcoords[i].enable = true; m_native_vtx_decl.texcoords[i].type = VAR_FLOAT; m_native_vtx_decl.texcoords[i].integer = false; LDRB(IndexType::Unsigned, scratch2_reg, src_reg, texmatidx_ofs[i]); m_float_emit.UCVTF(S31, scratch2_reg); if (tc[i]) { m_float_emit.STR(32, IndexType::Unsigned, D31, dst_reg, m_dst_ofs); m_dst_ofs += sizeof(float); } else { m_native_vtx_decl.texcoords[i].offset = m_dst_ofs; if (m_dst_ofs < 256) { STUR(SP, dst_reg, m_dst_ofs); } else if (!(m_dst_ofs & 7)) { // If m_dst_ofs isn't 8byte aligned we can't store an 8byte zero register // So store two 4byte zero registers // The destination is always 4byte aligned STR(IndexType::Unsigned, WSP, dst_reg, m_dst_ofs); STR(IndexType::Unsigned, WSP, dst_reg, m_dst_ofs + 4); } else { STR(IndexType::Unsigned, SP, dst_reg, m_dst_ofs); } m_float_emit.STR(32, IndexType::Unsigned, D31, dst_reg, m_dst_ofs + 8); m_dst_ofs += sizeof(float) * 3; } } } // Prepare for the next vertex. ADD(dst_reg, dst_reg, m_dst_ofs); const u8* cont = GetCodePtr(); ADD(src_reg, src_reg, m_src_ofs); SUB(count_reg, count_reg, 1); CBNZ(count_reg, loop_start); if (m_VtxDesc.Position & MASK_INDEXED) { SUB(W0, saved_count, skipped_reg); RET(X30); SetJumpTarget(m_skip_vertex); ADD(skipped_reg, skipped_reg, 1); B(cont); } else { MOV(W0, saved_count); RET(X30); } FlushIcache(); m_VertexSize = m_src_ofs; m_native_vtx_decl.stride = m_dst_ofs; } int VertexLoaderARM64::RunVertices(DataReader src, DataReader dst, int count) { m_numLoadedVertices += count; return ((int (*)(u8 * src, u8 * dst, int count)) region)(src.GetPointer(), dst.GetPointer(), count); }
Ebola16/dolphin
Source/Core/VideoCommon/VertexLoaderARM64.cpp
C++
gpl-2.0
20,467
<?php /** * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; under version 2 * of the License (non-upgradable). * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * Copyright (c) 2017 (original work) Open Assessment Technologies SA; */ namespace oat\taoQtiTest\scripts\install; use oat\generis\model\WidgetRdf; use oat\oatbox\extension\InstallAction; use oat\taoQtiTest\models\cat\CatService; use \common_report_Report as Report; /** * Class ShowQtiAdaptiveSectionIds * * Hide the QTI CAT Adaptive Section IDs from the Graphical User Interface. * * @package oat\taoQtiTest\scripts\install */ class HideQtiAdaptiveSectionIds extends InstallAction { public function __invoke($params) { $adaptiveSectionIdsProperty = new \core_kernel_classes_Property(CatService::CAT_ADAPTIVE_IDS_PROPERTY); $widgetProperty = new \core_kernel_classes_Property(WidgetRdf::PROPERTY_WIDGET); $adaptiveSectionIdsProperty->removePropertyValues($widgetProperty); return new Report(Report::TYPE_SUCCESS, 'QTI CAT Adaptive Section IDs are now hidden in the GUI.'); } }
oat-sa/extension-tao-testqti
scripts/install/HideQtiAdaptiveSectionIds.php
PHP
gpl-2.0
1,644
<?php /** * * Template for the shopping cart * * @package VirtueMart * @subpackage Cart * @author Max Milbers * * @link http://www.virtuemart.net * @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php * VirtueMart is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. */ ?> <?php echo "<h3>".JText::_('COM_VIRTUEMART_CART_ORDERDONE_THANK_YOU')."</h3>"; echo $this->html; ?>
kenbabu/emproj
components/com_virtuemart/views/cart/tmpl/order_done.php
PHP
gpl-2.0
699
//stlÌṩÁËÁ½ÖÖÈÝÆ÷£ºÐòÁУ¨vector¡¢list¡¢deque£©ºÍ¹ØÁªÈÝÆ÷£¨map¡¢mutilmap¡¢set¡¢mutilset£© //¶ø stackºÍqueueÊÇ×÷Ϊ»ù±¾ÈÝÆ÷µÄÊÊÅäÆ÷¡£ ////-----------------------------------Ðò ÁÐ-------------------------------- ////-----------------------------------ÊÊÅäÆ÷-------------------------------- //ÊÊÅäÆ÷ÌṩµÄÊÂÔ­À´ÈÝÆ÷µÄÒ»¸öÊÜÏ޵ĽçÃæ£¬ÌرðÊÇÈÝÆ÷²»Ìṩµü´úÆ÷ //±ÈÈ磺stackĬÈÏʹÓÃÒ»¸ödeque±£´æ×Ô¼ºµÄÔªËØ£¬µ«Ò²¿ÉÒÔ²ÉÓÃÈκÎÌṩÁËback()¡¢push_back()ºÍpop_back()µÄÐòÁÐ // ÀýÈ磺 stack<int> s1; //ÓÃdeque<int>±£´æÊý¾Ý // stack<int,vector<int> > s2;////ÓÃvector<int>±£´æÊý¾Ý // queueĬÈÏʹÓÃÒ»¸ödeque±£´æ×Ô¼ºµÄÔªËØ£¬µ«Ò²¿ÉÒÔ²ÉÓÃÈκÎÌṩÁËfront()¡¢back()¡¢push_back()ºÍpop_front()µÄÐòÁÐ // µ«vectorûÓÐÌṩpop_front()²Ù×÷£¬ËùÒÔvector²»ÄÜÓÃ×÷queueµÄ»ù´¡ÈÝÆ÷ // priority_queue ĬÈÏʹÓÃÒ»¸övector±£´æ×Ô¼ºµÄÔªËØ£¬µ«Ò²¿ÉÒÔ²ÉÓÃÈκÎÌṩÁËfront()¡¢push_back()ºÍpop_back()µÄÐòÁÐ // Æä±¾ÉíÒ²ÊÇÒ»ÖÖ¶ÓÁУ¬ÆäÖеÄÿһ¸öÔªËØ±»¸ø¶¨ÁËÒ»¸öÓÅÏȼ¶£¬ÒÔ´ËÀ´¿ØÖÆÔªËص½´ïtop£¨£©µÄ˳Ðò ////---------------------------------¹ØÁªÈÝÆ÷-------------------------------- //set, multiset, map, multimap ÊÇÒ»ÖÖ·ÇÏßÐÔµÄÊ÷½á¹¹£¬¾ßÌåµÄ˵²ÉÓõÄÊÇÒ»ÖֱȽϸßЧµÄÌØÊâµÄƽºâ¼ìË÷¶þ²æÊ÷¡ª¡ª ºìºÚÊ÷½á¹¹ //set ÓֳƼ¯ºÏ£¬Êµ¼ÊÉϾÍÊÇÒ»×éÔªËØµÄ¼¯ºÏ£¬µ«ÆäÖÐËù°üº¬µÄÔªËØµÄÖµÊÇΨһµÄ£¬ÇÒÊǰ´Ò»¶¨Ë³ÐòÅÅÁе쬼¯ºÏÖеÄÿ¸öÔªËØ±»³Æ×÷ // ¼¯ºÏÖеÄʵÀý¡£ÒòΪÆäÄÚ²¿ÊÇͨ¹ýÁ´±íµÄ·½Ê½À´×éÖ¯£¬ËùÒÔÔÚ²åÈëµÄʱºò±Èvector ¿ì£¬µ«ÔÚ²éÕÒºÍĩβÌí¼ÓÉϱÈvectorÂý¡£ //multiset ÊǶàÖØ¼¯ºÏ£¬ÆäʵÏÖ·½Ê½ºÍset ÊÇÏàËÆµÄ£¬Ö»ÊÇËü²»ÒªÇ󼯺ÏÖеÄÔªËØÊÇΨһµÄ£¬Ò²¾ÍÊÇ˵¼¯ºÏÖеÄͬһ¸öÔªËØ¿ÉÒÔ³öÏÖ¶à´Î¡£ //map ÌṩһÖÖ¡°¼ü- Öµ¡±¹ØÏµµÄÒ»¶ÔÒ»µÄÊý¾Ý´æ´¢ÄÜÁ¦¡£Æä¡°¼ü¡±ÔÚÈÝÆ÷Öв»¿ÉÖØ¸´£¬ÇÒ°´Ò»¶¨Ë³ÐòÅÅÁУ¨ÆäʵÎÒÃÇ¿ÉÒÔ½«set Ò²¿´³ÉÊÇ // Ò»ÖÖ¼ü- Öµ¹ØÏµµÄ´æ´¢£¬Ö»ÊÇËüÖ»ÓмüûÓÐÖµ¡£ËüÊÇmap µÄÒ»ÖÖÌØÊâÐÎʽ£©¡£ÓÉÓÚÆäÊǰ´Á´±íµÄ·½Ê½´æ´¢£¬ËüÒ²¼Ì³ÐÁËÁ´±íµÄÓÅȱµã¡£ //multimap ºÍmap µÄÔ­Àí»ù±¾ÏàËÆ£¬ËüÔÊÐí¡°¼ü¡±ÔÚÈÝÆ÷ÖпÉÒÔ²»Î¨Ò»¡£ //vector¡¢list¡¢dequeÑ¡Ôñ¹æÔò // 1¡¢Èç¹ûÐèÒª¸ßЧµÄËæ¼´´æÈ¡£¬¶ø²»ÔÚºõ²åÈëºÍɾ³ýµÄЧÂÊ£¬Ê¹ÓÃvector // 2¡¢Èç¹ûÐèÒª´óÁ¿µÄ²åÈëºÍɾ³ý£¬¶ø²»¹ØÐÄËæ¼´´æÈ¡£¬ÔòӦʹÓÃlist // 3¡¢Èç¹ûÐèÒªËæ¼´´æÈ¡£¬¶øÇÒ¹ØÐÄÁ½¶ËÊý¾ÝµÄ²åÈëºÍɾ³ý£¬ÔòӦʹÓÃdeque¡£ //map¡¢mutilmap¡¢set¡¢mutilsetÑ¡Ôñ¹æÔò //stackÄ£°åÀàµÄ¶¨ÒåÔÚ<stack>Í·ÎļþÖÐ // stackÄ£°åÀàÐèÒªÁ½¸öÄ£°å²ÎÊý£¬Ò»¸öÊÇÔªËØÀàÐÍ£¬Ò»¸öÈÝÆ÷ÀàÐÍ£¬µ«Ö»ÓÐÔªËØÀàÐÍÊDZØÒªµÄ£¬ÔÚ²»Ö¸¶¨ÈÝÆ÷ÀàÐÍʱ£¬Ä¬ÈϵÄÈÝÆ÷ÀàÐÍΪdeque¡£ // // ¶¨Òåstack¶ÔÏóµÄʾÀý´úÂëÈçÏ£º // stack<int> s1; // stack<string> s2; // //stackµÄ»ù±¾²Ù×÷ÓУº // ÈëÕ»£¬ÈçÀý£ºs.push(x); // ³öÕ»£¬ÈçÀý£ºs.pop();×¢Ò⣬³öÕ»²Ù×÷Ö»ÊÇɾ³ýÕ»¶¥ÔªËØ£¬²¢²»·µ»Ø¸ÃÔªËØ¡£ // ·ÃÎÊÕ»¶¥£¬ÈçÀý£ºs.top() // ÅжÏÕ»¿Õ£¬ÈçÀý£ºs.empty()£¬µ±Õ»¿Õʱ£¬·µ»Øtrue¡£ // ·ÃÎÊÕ»ÖеÄÔªËØ¸öÊý£¬ÈçÀý£ºs.size() #include <iostream> #include <ostream> #include <stack> #include <vector> #include <algorithm> #include <iterator> #include <numeric> using namespace std; int main () { vector<int> v1(5), v2(5), v3(5); iota(v1.begin(), v1.end(), 0); iota(v2.begin(), v2.end(), 5); iota(v3.begin(), v3.end(), 10); stack<vector<int> > s; s.push(v1); s.push(v2); s.push(v3); cout << "size of stack 's' = " << s.size() << endl; if ( v3 != v2 ) s.pop(); cout << "size of stack 's' = " << s.size() << endl; vector<int> top = s.top(); cout << "Contents of v2 : "; copy(top.begin(),top.end(), ostream_iterator<int>(cout," ")); cout << endl; while ( !s.empty() ) s.pop(); cout << "Stack 's' is " << (s.empty() ? "" : "not ") << "empty" << endl; system("pause"); return 0; }
lizhenghn123/CppLanguagePrograms
STL/stackDemo/stackDemo.cpp
C++
gpl-2.0
3,385
package io.github.yannici.bedwars.Game; import io.github.yannici.bedwars.Main; import io.github.yannici.bedwars.Utils; import io.github.yannici.bedwars.Events.BedwarsOpenTeamSelectionEvent; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.potion.PotionEffect; public class PlayerStorage { private Player player = null; private ItemStack[] inventory = null; private ItemStack[] armor = null; private float xp = 0.0F; private Collection<PotionEffect> effects = null; private GameMode mode = null; private Location left = null; private int level = 0; private String displayName = null; private String listName = null; private int foodLevel = 0; public PlayerStorage(Player p) { super(); this.player = p; } public void store() { this.inventory = this.player.getInventory().getContents(); this.armor = this.player.getInventory().getArmorContents(); this.xp = Float.valueOf(this.player.getExp()); this.effects = this.player.getActivePotionEffects(); this.mode = this.player.getGameMode(); this.left = this.player.getLocation(); this.level = this.player.getLevel(); this.listName = this.player.getPlayerListName(); this.displayName = this.player.getDisplayName(); this.foodLevel = this.player.getFoodLevel(); } public void clean() { PlayerInventory inv = this.player.getInventory(); inv.setArmorContents(new ItemStack[4]); inv.setContents(new ItemStack[] {}); this.player.setAllowFlight(false); this.player.setFlying(false); this.player.setExp(0.0F); this.player.setLevel(0); this.player.setSneaking(false); this.player.setSprinting(false); this.player.setFoodLevel(20); this.player.setMaxHealth(20.0D); this.player.setHealth(20.0D); this.player.setFireTicks(0); this.player.setGameMode(GameMode.SURVIVAL); boolean teamnameOnTab = Main.getInstance().getBooleanConfig("teamname-on-tab", true); boolean overwriteNames = Main.getInstance().getBooleanConfig("overwrite-names", false); if(overwriteNames) { Game game = Main.getInstance().getGameManager().getGameOfPlayer(this.player); if(game != null) { Team team = game.getPlayerTeam(this.player); if(team != null) { this.player.setDisplayName(team.getChatColor() + ChatColor.stripColor(this.player.getName())); } else { this.player.setDisplayName(ChatColor.stripColor(this.player.getName())); } } } if(teamnameOnTab && Utils.isSupportingTitles()) { Game game = Main.getInstance().getGameManager().getGameOfPlayer(this.player); if(game != null) { Team team = game.getPlayerTeam(this.player); if(team != null) { this.player.setPlayerListName(team.getChatColor() + team.getName() + ChatColor.WHITE + " | " + team.getChatColor() + ChatColor.stripColor(this.player.getDisplayName())); } else { this.player.setPlayerListName(ChatColor.stripColor(this.player.getDisplayName())); } } } if (this.player.isInsideVehicle()) { this.player.leaveVehicle(); } for (PotionEffect e : this.player.getActivePotionEffects()) { this.player.removePotionEffect(e.getType()); } this.player.updateInventory(); } public void restore() { this.player.getInventory().setContents(this.inventory); this.player.getInventory().setArmorContents(this.armor); this.player.setGameMode(this.mode); if (this.mode == GameMode.CREATIVE) { this.player.setAllowFlight(true); } this.player.addPotionEffects(this.effects); this.player.setLevel(this.level); this.player.setExp(this.xp); this.player.setPlayerListName(this.listName); this.player.setDisplayName(this.displayName); this.player.setFoodLevel(this.foodLevel); for (PotionEffect e : this.player.getActivePotionEffects()) { this.player.removePotionEffect(e.getType()); } this.player.addPotionEffects(this.effects); this.player.updateInventory(); } public Location getLeft() { return this.left; } @SuppressWarnings("deprecation") public void loadLobbyInventory(Game game) { ItemMeta im = null; // choose team only when autobalance is disabled if(!game.isAutobalanceEnabled()) { // Choose team (Wool) ItemStack teamSelection = new ItemStack(Material.BED, 1); im = teamSelection.getItemMeta(); im.setDisplayName(Main._l("lobby.chooseteam")); teamSelection.setItemMeta(im); this.player.getInventory().addItem(teamSelection); } // Leave Game (Slimeball) ItemStack leaveGame = new ItemStack(Material.SLIME_BALL, 1); im = leaveGame.getItemMeta(); im.setDisplayName(Main._l("lobby.leavegame")); leaveGame.setItemMeta(im); this.player.getInventory().setItem(8, leaveGame); Team team = game.getPlayerTeam(this.player); if(team != null) { ItemStack chestplate = new ItemStack(Material.LEATHER_CHESTPLATE, 1); LeatherArmorMeta meta = (LeatherArmorMeta) chestplate.getItemMeta(); meta.setDisplayName(team.getChatColor() + team.getDisplayName()); meta.setColor(team.getColor().getColor()); chestplate.setItemMeta(meta); this.player.getInventory().setItem(7, chestplate); team.equipPlayerWithLeather(this.player); } if (this.player.hasPermission("bw.setup") || this.player.isOp() || this.player.hasPermission("bw.vip.forcestart")) { // Force start game (Diamond) ItemStack startGame = new ItemStack(Material.DIAMOND, 1); im = startGame.getItemMeta(); im.setDisplayName(Main._l("lobby.startgame")); startGame.setItemMeta(im); this.player.getInventory().addItem(startGame); } // lobby gamemode GameMode mode = GameMode.SURVIVAL; try { mode = GameMode.getByValue(Main.getInstance().getIntConfig("lobby-gamemode", 0)); } catch(Exception ex) { // not valid gamemode } if(mode == null) { mode = GameMode.SURVIVAL; } this.player.setGameMode(mode); this.player.updateInventory(); } @SuppressWarnings("deprecation") public void openTeamSelection(Game game) { BedwarsOpenTeamSelectionEvent openEvent = new BedwarsOpenTeamSelectionEvent( game, this.player); Main.getInstance().getServer().getPluginManager().callEvent(openEvent); if (openEvent.isCancelled()) { return; } HashMap<String, Team> teams = game.getTeams(); int nom = (teams.size() % 9 == 0) ? 9 : (teams.size() % 9); Inventory inv = Bukkit.createInventory(this.player, teams.size() + (9 - nom), Main._l("lobby.chooseteam")); for (Team team : teams.values()) { List<Player> players = team.getPlayers(); if (players.size() >= team.getMaxPlayers()) { continue; } ItemStack is = new ItemStack(Material.WOOL, 1, team.getColor() .getDyeColor().getData()); ItemMeta im = is.getItemMeta(); im.setDisplayName(team.getChatColor() + team.getName()); ArrayList<String> teamplayers = new ArrayList<>(); int teamPlayerSize = team.getPlayers().size(); int maxPlayers = team.getMaxPlayers(); String current = "0"; if (teamPlayerSize >= maxPlayers) { current = ChatColor.RED + String.valueOf(teamPlayerSize); } else { current = ChatColor.YELLOW + String.valueOf(teamPlayerSize); } teamplayers.add(ChatColor.GRAY + "(" + current + ChatColor.GRAY + "/" + ChatColor.YELLOW + String.valueOf(maxPlayers) + ChatColor.GRAY + ")"); teamplayers.add(ChatColor.WHITE + "---------"); for (Player teamPlayer : players) { teamplayers.add(team.getChatColor() + ChatColor.stripColor(teamPlayer.getDisplayName())); } im.setLore(teamplayers); is.setItemMeta(im); inv.addItem(is); } this.player.openInventory(inv); } }
homedog21/bedwars-reloaded
src/io/github/yannici/bedwars/Game/PlayerStorage.java
Java
gpl-2.0
9,378
<?php /* -------------------------------------------------------------- blacklist.php 2008-08-10 gambio Gambio OHG http://www.gambio.de Copyright (c) 2008 Gambio OHG Released under the GNU General Public License (Version 2) [http://www.gnu.org/licenses/gpl-2.0.html] -------------------------------------------------------------- $Id: blacklist.php 899 2005-04-29 02:40:57Z hhgag $ XTC-CC - Contribution for XT-Commerce http://www.xt-commerce.com modified by http://www.netz-designer.de Copyright (c) 2003 netz-designer ----------------------------------------------------------------------------- based on: $Id: blacklist.php.php,v 1.00 Copyright (c) 2003 BMC http://www.mainframes.co.uk Released under the GNU General Public License ------------------------------------------------------------------------------*/ define('HEADING_TITLE', 'Kreditkarten-Blackliste'); // BOF GM_MOD define('HEADING_SUB_TITLE', 'Hilfsprogramme'); // EOF GM_MOD define('TABLE_HEADING_BLACKLIST', 'Kreditkarten-Blackliste'); define('TABLE_HEADING_ACTION', 'Aktion'); define('TEXT_MARKED_ELEMENTS','Markiertes Element'); define('TEXT_HEADING_NEW_BLACKLIST_CARD', 'Neue Karte'); define('TEXT_HEADING_EDIT_BLACKLIST_CARD', 'Karte bearbeiten'); define('TEXT_HEADING_DELETE_BLACKLIST_CARD', 'Karte l&ouml;schen'); define('TEXT_DISPLAY_NUMBER_OF_BLACKLIST_CARDS', 'Karten anzeigen'); define('TEXT_DATE_ADDED', 'Hinzugef&uuml;gt am:'); define('TEXT_LAST_MODIFIED', 'Zuletzt ge&auml;ndert:'); define('TEXT_NEW_INTRO', 'Tragen Sie die Kreditkartennummer ein, die gesperrt werden soll.'); define('TEXT_EDIT_INTRO', 'Bitte führen Sie die notwendigen &Auml;nderungen durch.'); define('TEXT_BLACKLIST_CARD_NUMBER', 'Kartennummer:'); define('TEXT_DELETE_INTRO', 'Sind Sie sicher, dass Sie diese Karte l&ouml;schen wollen?'); ?>
pobbes/gambio
lang/german/admin/blacklist.php
PHP
gpl-2.0
1,844
<?php /** * com_simplecalendar - a simple calendar component for Joomla * Copyright (C) 2008-2009 Fabrizio Albonico * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // no direct access defined('_JEXEC') or die('Restricted access'); jimport('joomla.application.component.view'); JHTML::stylesheet('simplecal_front.css','components/com_simplecalendar/assets/css/'); class SimpleCalendarViewCalendar extends JView { function display($tmpl = null) { global $option, $mainframe; $document = & JFactory::getDocument(); $catid = ''; $options = ''; $user =& JFactory::getUser(); $categoryName = ''; $component = JComponentHelper::getComponent( 'com_simplecalendar' ); $params = ''; $config = SCOutput::config(); // --- $menus =& JSite::getMenu(); $menu = $menus->getActive(); $params =& $mainframe->getParams(); $isPrint = false; $isPdf = false; $lists = array(); $pagination = ''; $lists['document'] =& JFactory::getDocument(); $lists['pathway'] =& $mainframe->getPathWay(); $menuitemid = JRequest::getInt( 'Itemid' ); $lists['search'] = $mainframe->getUserStateFromRequest( $option.'search', 'search', '', 'string' ); $lists['search'] = JString::strtolower( $lists['search'] ); $lists['mainframe'] = $mainframe; $lists['categoryName'] = ''; $lists['isPrint'] = false; $lists['isPdf'] = false; // check if entries are available, else print a "no events available" line $lists['hasEntries'] =& $this->get('Total'); // Check whether we're dealing with an iCal/vCal request $vcal = JRequest::getBool('vcal'); if ($vcal) { // $document->setMetaData('robots', 'noindex, nofollow'); $tmpl = 'vcal'; if ($lists['hasEntries'] > 0) { $items =& $this->get('Data'); $this->assignRef('items', $items); $this->assignRef('params', $params); parent::display($tmpl); } } $catidValue = JRequest::getString('catid'); $catid = explode(':', $catidValue); if ( $catid[0] != 0 ) { $lists['catid'] = $catid[0]; $lists['categoryName'] =& $this->get('CategoryName'); } else if ( $params->get('catid') != 0 ) { $lists['catid'] = $params->get('catid'); $lists['categoryName'] =& $this->get('CategoryName'); } else { $lists['catid'] = 0; } $lists['calendarTitle'] = ''; if ( is_object($menu) ) { $menu_params = new JParameter( $menu->params ); if ( !$menu_params->get( 'page_title') ) { $params->set('page_title', JText::_('Calendar')); } } else { $params->set('page_title', JText::_('Calendar')); } if ( $params->get('page_title') != '' && $lists['categoryName'] != '' ){ $params->set('page_title', $params->get('page_title') . ' / ' . $lists['categoryName']); } // Check whether we are dealing with PDF or print version of the calendar if (JRequest::getVar('format') == 'pdf') { $lists['isPdf'] = TRUE; } if (JRequest::getBool('print')) { $lists['isPrint'] = TRUE; } //TODO: add metadata from Joomla site // $metadata = 'Calendar, SimpleCalendar, List'; // $lists['document']->setMetadata('keywords', $metadata ); //http://forum.joomla.org/viewtopic.php?p=1679517 @ini_set("pcre.backtrack_limit", -1); $items =& $this->get('Data'); if ( $config->show_search_bar && !$lists['isPrint'] ) { $pagination =& $this->get('Pagination'); } //feed management if ( $params->get('linkToRSS', '1') ) { $link = 'index.php?view=calendar&format=feed'; $attribs = array('type' => 'application/rss+xml', 'title' => 'RSS 2.0'); $document->addHeadLink(JRoute::_($link.'&type=rss'), 'alternate', 'rel', $attribs); $attribs = array('type' => 'application/atom+xml', 'title' => 'Atom 1.0'); $document->addHeadLink(JRoute::_($link.'&type=atom'), 'alternate', 'rel', $attribs); } $this->assignRef('items', $items); $this->assignRef('params', $params); $this->assignRef('config', $config); $this->assignRef('lists', $lists); $this->assignRef('user', $user); $this->assignRef('pagination', $pagination); $this->assignRef('document', $document); parent::display($tmpl); } } ?>
mchalupar/Union-Leopoldschlag
tmp/install_50dda12248b2d/component/views/calendar/view.html.php
PHP
gpl-2.0
4,869
/*global require,__dirname*/ var connect = require('connect'); connect.createServer( connect.static(__dirname) ).listen(8080);
kurthalex/BRGM-BdCavite-cesium
cesium/Build/server.js
JavaScript
gpl-2.0
127
class TreatmentAreas::PatientsController < ApplicationController before_filter :authenticate_user! before_filter :find_treatment_area def index @patients_table = PatientsTable.new @patient_search = @patients_table.search(params) end def radiology @patient = Patient.find(params[:id]) if dexis? || kodak? app_config["dexis_paths"].each do |root_path| path = [root_path, "passtodex", current_user.x_ray_station_id, ".dat"].join @patient.export_to_dexis(path) end end respond_to do |format| format.html do @patient.check_out(TreatmentArea.radiology) redirect_to treatment_area_patient_procedures_path(TreatmentArea.radiology, @patient.id) end end rescue => e flash[:error] = e.message redirect_to :action => :index end private def find_treatment_area @treatment_area = TreatmentArea.find(params[:treatment_area_id]) end end
mission-of-mercy/georgia
app/controllers/treatment_areas/patients_controller.rb
Ruby
gpl-2.0
945
# replaces the '%' symbol with '+', leaving the return values of actions usable for other things, such as type information, # and leaving whitespace intact. from dparser import Parser # turn a tree of strings into a single string (slowly): def stringify(s): if not isinstance(s, str): return ''.join(map(stringify, s)) return s def d_add1(t, s): "add : add '%' exp" s[1] = '+ ' # replace the % with + def d_add2(t, s): "add : exp" def d_exp(t): 'exp : "[0-9]+" ' # if the start action specifies the 's' argument, then parser # will contain a member, s, parser = Parser() parsedmessage = parser.parse('1 % 2 % 3') if stringify(parsedmessage.getStringLeft()) != '1 + 2 + 3': print 'error'
charlesDGY/coflo
coflo-0.0.4/third_party/d/python/tests/test6.py
Python
gpl-2.0
743
package pub.infoclass.pushservice; public class ACK { private int p = h_protocol_pusher.ACK; private String UserID; private String PushID; public ACK(String userID, String pushID) { super(); UserID = userID; PushID = pushID; } public int getP() { return p; } public void setP(int p) { this.p = p; } public String getUserID() { return UserID; } public void setUserID(String userID) { UserID = userID; } public String getPushID() { return PushID; } public void setPushID(String pushID) { PushID = pushID; } }
282857484/LocationBaseServiceSocialNetworking
src/pub/infoclass/pushservice/ACK.java
Java
gpl-2.0
551
<?php /* * * Ampoliros Application Server * * http://www.ampoliros.com * * * * Copyright (C) 2000-2004 Solarix * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ // $Id: DBLayer_mysql.php,v 1.7 2004-07-08 15:04:26 alex Exp $ package('com.solarix.ampoliros.db.drivers.mysql'); import('com.solarix.ampoliros.db.DBLayer'); import('carthag.db.DataAccessFactory'); /*! @class dblayer_mysql @abstract DbLayer for MySql. */ class DBLayer_mysql extends DBLayer { public $layer = 'mysql'; public $fmtquote = "''"; public $fmttrue = 't'; public $fmtfalse = 'f'; //public $suppautoinc = true; //public $suppblob = true; private $lastquery = false; public function dblayer_mysql($params) { $this -> support['affrows'] = true; $this -> support['transactions'] = false; return $this -> dblayer($params); } function _CreateDB($params) { $result = false; if (!empty($params['dbname'])) { $tmplink = @ mysql_connect($params['dbhost'], $params['dbuser'], $params['dbpass']); if ($tmplink) { if (mysql_query('CREATE DATABASE '.$params['dbname'], $tmplink)) $result = true; else $this -> mLastError = @ mysql_error($tmplink); } //@mysql_close( $tmplink ); } return $result; } function _DropDB($params) { $result = false; if (!empty($params['dbname'])) $result = @ mysql_query('DROP DATABASE '.$params['dbname'], $this -> dbhandler); return $result; } function _Connect() { $result = @ mysql_connect($this -> dbhost, $this -> dbuser, $this -> dbpass); if ($result != false) { $this -> dbhandler = $result; if (!@ mysql_select_db($this -> dbname, $this -> dbhandler)) $result = false; } return $result; } function _PConnect($params) { $result = @ mysql_pconnect($this -> dbhost, $this -> dbuser, $this -> dbpass); if ($result != false) { $this -> dbhandler = $result; if (!@ mysql_select_db($this -> dbname, $this -> dbhandler)) $result = false; } return $result; } function _Close() { return true; //return @mysql_close( $this->dbhandler ); } function _Query($query) { @ mysql_select_db($this -> dbname, $this -> dbhandler); $this -> lastquery = @ mysql_query($query, $this -> dbhandler); //if ( defined( 'DEBUG' ) and !$this->lastquery ) echo mysql_error(); if (@ mysql_error($this -> dbhandler)) { import('com.solarix.ampoliros.io.log.Logger'); $this -> log = new Logger($this -> dblog); $this -> log -> logevent('ampoliros.dblayer_mysql_library.dblayer_mysql_class._query', 'Error: '.@ mysql_error($this -> dbhandler), LOGGER_ERROR); } return $this -> lastquery; } function _AffectedRows($params) { $result = false; if ($this -> lastquery != false) { $result = @ mysql_affected_rows($this -> dbhandler); } return $result; } function _DropTable($params) { $result = false; if (!empty($params['tablename']) and $this -> opened) $result = $this -> _query('DROP TABLE '.$params['tablename']); return $result; } function _AddColumn($params) { $result = FALSE; if (!empty($params['tablename']) and !empty($params['columnformat']) and $this -> opened) $result = $this -> _query('ALTER TABLE '.$params['tablename'].' ADD COLUMN '.$params['columnformat']); return $result; } function _RemoveColumn($params) { $result = FALSE; if (!empty($params['tablename']) and !empty($params['column']) and $this -> opened) $result = $this -> _query('ALTER TABLE '.$params['tablename'].' DROP COLUMN '.$params['column']); return $result; } function _CreateSeq($params) { $result = false; if (!empty($params['name']) and !empty($params['start']) and $this -> opened) { $result = $this -> Execute('CREATE TABLE _sequence_'.$params['name'].' (sequence INT DEFAULT 0 NOT NULL AUTO_INCREMENT, PRIMARY KEY (sequence))'); if ($result and ($params['start'] > 0)) $this -> Execute('INSERT INTO _sequence_'.$params['name'].' (sequence) VALUES ('. ($params['start'] - 1).')'); } return $result; } function _CreateSeqQuery($params) { $result = false; if (!empty($params['name']) and !empty($params['start'])) { $query = 'CREATE TABLE _sequence_'.$params['name'].' (sequence INT DEFAULT 0 NOT NULL AUTO_INCREMENT, PRIMARY KEY (sequence));'; if ($params['start'] > 0) $query.= 'INSERT INTO _sequence_'.$params['name'].' (sequence) VALUES ('. ($params['start'] - 1).');'; return $query; } return $result; } function _DropSeq($params) { if (!empty($params['name'])) return $this -> _query('DROP TABLE _sequence_'.$params['name']); else return false; } function _DropSeqQuery($params) { if (!empty($params['name'])) return 'DROP TABLE _sequence_'.$params['name'].';'; else return false; } function _CurrSeqValue($name) { if (!empty($name)) { $result = $this -> _query('SELECT MAX(sequence) FROM _sequence_'.$name); return @ mysql_result($result, 0, 0); } else return false; } function _CurrSeqValueQuery($name) { $result = false; if (!empty($name)) { $result = 'SELECT MAX(sequence) FROM _sequence_'.$name.';'; } return $result; } function _NextSeqValue($name) { if (!empty($name)) { if ($this -> _query('INSERT INTO _sequence_'.$name.' (sequence) VALUES (NULL)')) { $value = intval(mysql_insert_id($this -> dbhandler)); $this -> _query('DELETE FROM _sequence_'.$name.' WHERE sequence<'.$value); } return $value; } else return false; } // ---------------------------------------------------- // // ---------------------------------------------------- Function GetTextFieldTypeDeclaration($name, & $field) { return (((IsSet($field['length']) and ($field['length'] <= 255)) ? "$name VARCHAR (".$field["length"].")" : "$name TEXT"). (IsSet($field["default"]) ? " DEFAULT '".$field["default"]."'" : ""). (IsSet($field["notnull"]) ? " NOT NULL" : "")); } Function GetTextFieldValue($value) { return ("'".AddSlashes($value)."'"); } Function GetDateFieldTypeDeclaration($name, & $field) { return ($name." DATE". (IsSet($field["default"]) ? " DEFAULT '".$field["default"]."'" : ""). (IsSet($field["notnull"]) ? " NOT NULL" : "")); } Function GetTimeFieldTypeDeclaration($name, & $field) { return ($name." TIME". (IsSet($field["default"]) ? " DEFAULT '".$field["default"]."'" : ""). (IsSet($field["notnull"]) ? " NOT NULL" : "")); } Function GetFloatFieldTypeDeclaration($name, & $field) { return ("$name FLOAT8 ". (IsSet($field["default"]) ? " DEFAULT ".$this -> GetFloatFieldValue($field["default"]) : ""). (IsSet($field["notnull"]) ? " NOT NULL" : "")); } Function GetDecimalFieldTypeDeclaration($name, & $field) { return ("$name DECIMAL ". (IsSet($field["length"]) ? " (".$field["length"].") " : ""). (IsSet($field["default"]) ? " DEFAULT ".$this -> GetDecimalFieldValue($field["default"]) : ""). (IsSet($field["notnull"]) ? " NOT NULL" : "")); } Function GetFloatFieldValue($value) { return (!strcmp($value, "NULL") ? "NULL" : "$value"); } Function GetDecimalFieldValue($value) { return (!strcmp($value, "NULL") ? "NULL" : strval(intval($value * $this -> decimal_factor))); } } ?>
alexpagnoni/ampoliros
var/classes/com/solarix/ampoliros/db/drivers/mysql/DBLayer_mysql.php
PHP
gpl-2.0
7,888
/* * This file is part of the KDE project * * Copyright (c) 2005 Michael Thaler <michael.thaler@physik.tu-muenchen.de> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "kis_dropshadow_plugin.h" #include <klocale.h> #include <kiconloader.h> #include <kcomponentdata.h> #include <kmessagebox.h> #include <kstandarddirs.h> #include <kis_debug.h> #include <kpluginfactory.h> #include <kactioncollection.h> #include "kis_view2.h" #include "kis_types.h" #include "kis_image.h" #include "kis_paint_device.h" #include "kis_layer.h" #include "kis_statusbar.h" #include "widgets/kis_progress_widget.h" #include <KoColorSpace.h> #include <KoProgressUpdater.h> #include <KoUpdater.h> #include "kis_dropshadow.h" #include "dlg_dropshadow.h" K_PLUGIN_FACTORY(KisDropshadowPluginFactory, registerPlugin<KisDropshadowPlugin>();) K_EXPORT_PLUGIN(KisDropshadowPluginFactory("krita")) KisDropshadowPlugin::KisDropshadowPlugin(QObject *parent, const QVariantList &) : KParts::Plugin(parent) { if (parent->inherits("KisView2")) { setXMLFile(KStandardDirs::locate("data", "kritaplugins/dropshadow.rc"), true); m_view = (KisView2*) parent; KAction *action = new KAction(i18n("Add Drop Shadow..."), this); actionCollection()->addAction("dropshadow", action); connect(action, SIGNAL(triggered()), this, SLOT(slotDropshadow())); } } KisDropshadowPlugin::~KisDropshadowPlugin() { } void KisDropshadowPlugin::slotDropshadow() { KisImageWSP image = m_view->image(); if (!image) return; KisLayerSP layer = m_view->activeLayer(); if (!layer) return; DlgDropshadow * dlgDropshadow = new DlgDropshadow(layer->colorSpace()->name(), image->colorSpace()->name(), m_view, "Dropshadow"); Q_CHECK_PTR(dlgDropshadow); dlgDropshadow->setCaption(i18n("Drop Shadow")); if (dlgDropshadow->exec() == QDialog::Accepted) { KisDropshadow dropshadow(m_view); KoProgressUpdater* updater = m_view->createProgressUpdater(); updater->start(); QPointer<KoUpdater> u = updater->startSubtask(); dropshadow.dropshadow(u, dlgDropshadow->getXOffset(), dlgDropshadow->getYOffset(), dlgDropshadow->getBlurRadius(), dlgDropshadow->getShadowColor(), dlgDropshadow->getShadowOpacity(), dlgDropshadow->allowResizingChecked()); updater->deleteLater(); } delete dlgDropshadow; } #include "kis_dropshadow_plugin.moc"
wyuka/calligra
krita/plugins/extensions/dropshadow/kis_dropshadow_plugin.cc
C++
gpl-2.0
3,316
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package cn.edu.hfut.dmic.webcollectorcluster.generator; import cn.edu.hfut.dmic.webcollectorcluster.model.CrawlDatum; import java.io.IOException; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.RecordReader; /** * * @author hu */ public class RecordGenerator implements Generator{ public RecordGenerator(RecordReader<Text, CrawlDatum> reader) { this.reader = reader; } RecordReader<Text, CrawlDatum> reader; @Override public CrawlDatum next() { Text text=new Text(); CrawlDatum datum=new CrawlDatum(); boolean hasMore; try { hasMore = reader.next(text, datum); } catch (IOException ex) { ex.printStackTrace(); return null; } if(hasMore) return datum; else return null; } }
CrawlScript/WebCollectorCluster-Dev
WebCollectorCluster/src/main/java/cn/edu/hfut/dmic/webcollectorcluster/generator/RecordGenerator.java
Java
gpl-2.0
1,060
/* * NimBLERemoteDescriptor.cpp * * Created: on Jan 27 2020 * Author H2zero * * Originally: * * BLERemoteDescriptor.cpp * * Created on: Jul 8, 2017 * Author: kolban */ #include "sdkconfig.h" #if defined(CONFIG_BT_ENABLED) #include "nimconfig.h" #if defined( CONFIG_BT_NIMBLE_ROLE_CENTRAL) #include "NimBLERemoteDescriptor.h" #include "NimBLEUtils.h" #include "NimBLELog.h" static const char* LOG_TAG = "NimBLERemoteDescriptor"; /** * @brief Remote descriptor constructor. * @param [in] pRemoteCharacteristic A pointer to the Characteristic that this belongs to. * @param [in] dsc A pointer to the struct that contains the descriptor information. */ NimBLERemoteDescriptor::NimBLERemoteDescriptor(NimBLERemoteCharacteristic* pRemoteCharacteristic, const struct ble_gatt_dsc *dsc) { NIMBLE_LOGD(LOG_TAG, ">> NimBLERemoteDescriptor()"); switch (dsc->uuid.u.type) { case BLE_UUID_TYPE_16: m_uuid = NimBLEUUID(dsc->uuid.u16.value); break; case BLE_UUID_TYPE_32: m_uuid = NimBLEUUID(dsc->uuid.u32.value); break; case BLE_UUID_TYPE_128: m_uuid = NimBLEUUID(const_cast<ble_uuid128_t*>(&dsc->uuid.u128)); break; default: break; } m_handle = dsc->handle; m_pRemoteCharacteristic = pRemoteCharacteristic; NIMBLE_LOGD(LOG_TAG, "<< NimBLERemoteDescriptor(): %s", m_uuid.toString().c_str()); } /** * @brief Retrieve the handle associated with this remote descriptor. * @return The handle associated with this remote descriptor. */ uint16_t NimBLERemoteDescriptor::getHandle() { return m_handle; } // getHandle /** * @brief Get the characteristic that owns this descriptor. * @return The characteristic that owns this descriptor. */ NimBLERemoteCharacteristic* NimBLERemoteDescriptor::getRemoteCharacteristic() { return m_pRemoteCharacteristic; } // getRemoteCharacteristic /** * @brief Retrieve the UUID associated this remote descriptor. * @return The UUID associated this remote descriptor. */ NimBLEUUID NimBLERemoteDescriptor::getUUID() { return m_uuid; } // getUUID /** * @brief Read a byte value * @return The value as a byte * @deprecated Use readValue<uint8_t>(). */ uint8_t NimBLERemoteDescriptor::readUInt8() { std::string value = readValue(); if (value.length() >= 1) { return (uint8_t) value[0]; } return 0; } // readUInt8 /** * @brief Read an unsigned 16 bit value * @return The unsigned 16 bit value. * @deprecated Use readValue<uint16_t>(). */ uint16_t NimBLERemoteDescriptor::readUInt16() { std::string value = readValue(); if (value.length() >= 2) { return *(uint16_t*) value.data(); } return 0; } // readUInt16 /** * @brief Read an unsigned 32 bit value. * @return the unsigned 32 bit value. * @deprecated Use readValue<uint32_t>(). */ uint32_t NimBLERemoteDescriptor::readUInt32() { std::string value = readValue(); if (value.length() >= 4) { return *(uint32_t*) value.data(); } return 0; } // readUInt32 /** * @brief Read the value of the remote descriptor. * @return The value of the remote descriptor. */ std::string NimBLERemoteDescriptor::readValue() { NIMBLE_LOGD(LOG_TAG, ">> Descriptor readValue: %s", toString().c_str()); NimBLEClient* pClient = getRemoteCharacteristic()->getRemoteService()->getClient(); std::string value; if (!pClient->isConnected()) { NIMBLE_LOGE(LOG_TAG, "Disconnected"); return value; } int rc = 0; int retryCount = 1; ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(),0, &value}; do { rc = ble_gattc_read_long(pClient->getConnId(), m_handle, 0, NimBLERemoteDescriptor::onReadCB, &taskData); if (rc != 0) { NIMBLE_LOGE(LOG_TAG, "Error: Failed to read descriptor; rc=%d, %s", rc, NimBLEUtils::returnCodeToString(rc)); return value; } ulTaskNotifyTake(pdTRUE, portMAX_DELAY); rc = taskData.rc; switch(rc){ case 0: case BLE_HS_EDONE: rc = 0; break; // Descriptor is not long-readable, return with what we have. case BLE_HS_ATT_ERR(BLE_ATT_ERR_ATTR_NOT_LONG): NIMBLE_LOGI(LOG_TAG, "Attribute not long"); rc = 0; break; case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHEN): case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHOR): case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_ENC): if (retryCount && pClient->secureConnection()) break; /* Else falls through. */ default: return value; } } while(rc != 0 && retryCount--); NIMBLE_LOGD(LOG_TAG, "<< Descriptor readValue(): length: %d rc=%d", value.length(), rc); return value; } // readValue /** * @brief Callback for Descriptor read operation. * @return success == 0 or error code. */ int NimBLERemoteDescriptor::onReadCB(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg) { ble_task_data_t *pTaskData = (ble_task_data_t*)arg; NimBLERemoteDescriptor* desc = (NimBLERemoteDescriptor*)pTaskData->pATT; uint16_t conn_id = desc->getRemoteCharacteristic()->getRemoteService()->getClient()->getConnId(); if(conn_id != conn_handle){ return 0; } NIMBLE_LOGD(LOG_TAG, "Read complete; status=%d conn_handle=%d", error->status, conn_handle); std::string *strBuf = (std::string*)pTaskData->buf; int rc = error->status; if(rc == 0) { if(attr) { if(((*strBuf).length() + attr->om->om_len) > BLE_ATT_ATTR_MAX_LEN) { rc = BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; } else { NIMBLE_LOGD(LOG_TAG, "Got %d bytes", attr->om->om_len); (*strBuf) += std::string((char*) attr->om->om_data, attr->om->om_len); return 0; } } } pTaskData->rc = rc; xTaskNotifyGive(pTaskData->task); return rc; } /** * @brief Return a string representation of this Remote Descriptor. * @return A string representation of this Remote Descriptor. */ std::string NimBLERemoteDescriptor::toString() { std::string res = "Descriptor: uuid: " + getUUID().toString(); char val[6]; res += ", handle: "; snprintf(val, sizeof(val), "%d", getHandle()); res += val; return res; } // toString /** * @brief Callback for descriptor write operation. * @return success == 0 or error code. */ int NimBLERemoteDescriptor::onWriteCB(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg) { ble_task_data_t *pTaskData = (ble_task_data_t*)arg; NimBLERemoteDescriptor* descriptor = (NimBLERemoteDescriptor*)pTaskData->pATT; if(descriptor->getRemoteCharacteristic()->getRemoteService()->getClient()->getConnId() != conn_handle){ return 0; } NIMBLE_LOGI(LOG_TAG, "Write complete; status=%d conn_handle=%d", error->status, conn_handle); pTaskData->rc = error->status; xTaskNotifyGive(pTaskData->task); return 0; } /** * @brief Write data to the BLE Remote Descriptor. * @param [in] data The data to send to the remote descriptor. * @param [in] length The length of the data to send. * @param [in] response True if we expect a write response. * @return True if successful */ bool NimBLERemoteDescriptor::writeValue(const uint8_t* data, size_t length, bool response) { NIMBLE_LOGD(LOG_TAG, ">> Descriptor writeValue: %s", toString().c_str()); NimBLEClient* pClient = getRemoteCharacteristic()->getRemoteService()->getClient(); // Check to see that we are connected. if (!pClient->isConnected()) { NIMBLE_LOGE(LOG_TAG, "Disconnected"); return false; } int rc = 0; int retryCount = 1; uint16_t mtu = ble_att_mtu(pClient->getConnId()) - 3; // Check if the data length is longer than we can write in 1 connection event. // If so we must do a long write which requires a response. if(length <= mtu && !response) { rc = ble_gattc_write_no_rsp_flat(pClient->getConnId(), m_handle, data, length); return (rc == 0); } ble_task_data_t taskData = {this, xTaskGetCurrentTaskHandle(), 0, nullptr}; do { if(length > mtu) { NIMBLE_LOGI(LOG_TAG,"long write %d bytes", length); os_mbuf *om = ble_hs_mbuf_from_flat(data, length); rc = ble_gattc_write_long(pClient->getConnId(), m_handle, 0, om, NimBLERemoteDescriptor::onWriteCB, &taskData); } else { rc = ble_gattc_write_flat(pClient->getConnId(), m_handle, data, length, NimBLERemoteDescriptor::onWriteCB, &taskData); } if (rc != 0) { NIMBLE_LOGE(LOG_TAG, "Error: Failed to write descriptor; rc=%d", rc); return false; } ulTaskNotifyTake(pdTRUE, portMAX_DELAY); rc = taskData.rc; switch(rc) { case 0: case BLE_HS_EDONE: rc = 0; break; case BLE_HS_ATT_ERR(BLE_ATT_ERR_ATTR_NOT_LONG): NIMBLE_LOGE(LOG_TAG, "Long write not supported by peer; Truncating length to %d", mtu); retryCount++; length = mtu; break; case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHEN): case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHOR): case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_ENC): if (retryCount && pClient->secureConnection()) break; /* Else falls through. */ default: return false; } } while(rc != 0 && retryCount--); NIMBLE_LOGD(LOG_TAG, "<< Descriptor writeValue, rc: %d",rc); return (rc == 0); } // writeValue /** * @brief Write data represented as a string to the BLE Remote Descriptor. * @param [in] newValue The data to send to the remote descriptor. * @param [in] response True if we expect a response. * @return True if successful */ bool NimBLERemoteDescriptor::writeValue(const std::string &newValue, bool response) { return writeValue((uint8_t*) newValue.data(), newValue.length(), response); } // writeValue #endif // #if defined( CONFIG_BT_NIMBLE_ROLE_CENTRAL) #endif /* CONFIG_BT_ENABLED */
ramalhais/code
arduino/libraries/NimBLE-Arduino/src/NimBLERemoteDescriptor.cpp
C++
gpl-2.0
10,911
<?php /* core/themes/stable/templates/admin/admin-block.html.twig */ class __TwigTemplate_73d94355d598b4dfa4b4ca02e16e4343556a0d714799515056c444f65791e3fc extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array("if" => 16); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array('if'), array(), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 15 echo "<div class=\"panel\"> "; // line 16 if ($this->getAttribute((isset($context["block"]) ? $context["block"] : null), "title", array())) { // line 17 echo " <h3 class=\"panel__title\">"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["block"]) ? $context["block"] : null), "title", array()), "html", null, true)); echo "</h3> "; } // line 19 echo " "; if ($this->getAttribute((isset($context["block"]) ? $context["block"] : null), "content", array())) { // line 20 echo " <div class=\"panel__content\">"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["block"]) ? $context["block"] : null), "content", array()), "html", null, true)); echo "</div> "; } elseif ($this->getAttribute( // line 21 (isset($context["block"]) ? $context["block"] : null), "description", array())) { // line 22 echo " <div class=\"panel__description\">"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, $this->getAttribute((isset($context["block"]) ? $context["block"] : null), "description", array()), "html", null, true)); echo "</div> "; } // line 24 echo "</div> "; } public function getTemplateName() { return "core/themes/stable/templates/admin/admin-block.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 70 => 24, 64 => 22, 62 => 21, 57 => 20, 54 => 19, 48 => 17, 46 => 16, 43 => 15,); } } /* {#*/ /* /***/ /* * @file*/ /* * Theme override for an administrative block.*/ /* **/ /* * Available variables:*/ /* * - block: An array of information about the block, including:*/ /* * - show: A flag indicating if the block should be displayed.*/ /* * - title: The block title.*/ /* * - content: (optional) The content of the block.*/ /* * - description: (optional) A description of the block.*/ /* * (Description should only be output if content is not available).*/ /* *//* */ /* #}*/ /* <div class="panel">*/ /* {% if block.title %}*/ /* <h3 class="panel__title">{{ block.title }}</h3>*/ /* {% endif %}*/ /* {% if block.content %}*/ /* <div class="panel__content">{{ block.content }}</div>*/ /* {% elseif block.description %}*/ /* <div class="panel__description">{{ block.description }}</div>*/ /* {% endif %}*/ /* </div>*/ /* */
neetumorwani/dcon
sites/default/files/php/twig/e7e9cf99_admin-block.html.twig_b440e57db9efed76852fc563c6827050f943bfd78965a8b1ecb3a02c71db4383/d60b7a51460832b200c45935652984dcb99b21f7bda17e389af5047f446ab118.php
PHP
gpl-2.0
4,309
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 4); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /* 1 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Url", function() { return Url; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Http", function() { return Http; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Resource", function() { return Resource; }); /*! * vue-resource v1.3.4 * https://github.com/pagekit/vue-resource * Released under the MIT License. */ /** * Promises/A+ polyfill v1.1.4 (https://github.com/bramstein/promis) */ var RESOLVED = 0; var REJECTED = 1; var PENDING = 2; function Promise$1(executor) { this.state = PENDING; this.value = undefined; this.deferred = []; var promise = this; try { executor(function (x) { promise.resolve(x); }, function (r) { promise.reject(r); }); } catch (e) { promise.reject(e); } } Promise$1.reject = function (r) { return new Promise$1(function (resolve, reject) { reject(r); }); }; Promise$1.resolve = function (x) { return new Promise$1(function (resolve, reject) { resolve(x); }); }; Promise$1.all = function all(iterable) { return new Promise$1(function (resolve, reject) { var count = 0, result = []; if (iterable.length === 0) { resolve(result); } function resolver(i) { return function (x) { result[i] = x; count += 1; if (count === iterable.length) { resolve(result); } }; } for (var i = 0; i < iterable.length; i += 1) { Promise$1.resolve(iterable[i]).then(resolver(i), reject); } }); }; Promise$1.race = function race(iterable) { return new Promise$1(function (resolve, reject) { for (var i = 0; i < iterable.length; i += 1) { Promise$1.resolve(iterable[i]).then(resolve, reject); } }); }; var p$1 = Promise$1.prototype; p$1.resolve = function resolve(x) { var promise = this; if (promise.state === PENDING) { if (x === promise) { throw new TypeError('Promise settled with itself.'); } var called = false; try { var then = x && x['then']; if (x !== null && typeof x === 'object' && typeof then === 'function') { then.call(x, function (x) { if (!called) { promise.resolve(x); } called = true; }, function (r) { if (!called) { promise.reject(r); } called = true; }); return; } } catch (e) { if (!called) { promise.reject(e); } return; } promise.state = RESOLVED; promise.value = x; promise.notify(); } }; p$1.reject = function reject(reason) { var promise = this; if (promise.state === PENDING) { if (reason === promise) { throw new TypeError('Promise settled with itself.'); } promise.state = REJECTED; promise.value = reason; promise.notify(); } }; p$1.notify = function notify() { var promise = this; nextTick(function () { if (promise.state !== PENDING) { while (promise.deferred.length) { var deferred = promise.deferred.shift(), onResolved = deferred[0], onRejected = deferred[1], resolve = deferred[2], reject = deferred[3]; try { if (promise.state === RESOLVED) { if (typeof onResolved === 'function') { resolve(onResolved.call(undefined, promise.value)); } else { resolve(promise.value); } } else if (promise.state === REJECTED) { if (typeof onRejected === 'function') { resolve(onRejected.call(undefined, promise.value)); } else { reject(promise.value); } } } catch (e) { reject(e); } } } }); }; p$1.then = function then(onResolved, onRejected) { var promise = this; return new Promise$1(function (resolve, reject) { promise.deferred.push([onResolved, onRejected, resolve, reject]); promise.notify(); }); }; p$1.catch = function (onRejected) { return this.then(undefined, onRejected); }; /** * Promise adapter. */ if (typeof Promise === 'undefined') { window.Promise = Promise$1; } function PromiseObj(executor, context) { if (executor instanceof Promise) { this.promise = executor; } else { this.promise = new Promise(executor.bind(context)); } this.context = context; } PromiseObj.all = function (iterable, context) { return new PromiseObj(Promise.all(iterable), context); }; PromiseObj.resolve = function (value, context) { return new PromiseObj(Promise.resolve(value), context); }; PromiseObj.reject = function (reason, context) { return new PromiseObj(Promise.reject(reason), context); }; PromiseObj.race = function (iterable, context) { return new PromiseObj(Promise.race(iterable), context); }; var p = PromiseObj.prototype; p.bind = function (context) { this.context = context; return this; }; p.then = function (fulfilled, rejected) { if (fulfilled && fulfilled.bind && this.context) { fulfilled = fulfilled.bind(this.context); } if (rejected && rejected.bind && this.context) { rejected = rejected.bind(this.context); } return new PromiseObj(this.promise.then(fulfilled, rejected), this.context); }; p.catch = function (rejected) { if (rejected && rejected.bind && this.context) { rejected = rejected.bind(this.context); } return new PromiseObj(this.promise.catch(rejected), this.context); }; p.finally = function (callback) { return this.then(function (value) { callback.call(this); return value; }, function (reason) { callback.call(this); return Promise.reject(reason); } ); }; /** * Utility functions. */ var ref = {}; var hasOwnProperty = ref.hasOwnProperty; var ref$1 = []; var slice = ref$1.slice; var debug = false; var ntick; var inBrowser = typeof window !== 'undefined'; var Util = function (ref) { var config = ref.config; var nextTick = ref.nextTick; ntick = nextTick; debug = config.debug || !config.silent; }; function warn(msg) { if (typeof console !== 'undefined' && debug) { console.warn('[VueResource warn]: ' + msg); } } function error(msg) { if (typeof console !== 'undefined') { console.error(msg); } } function nextTick(cb, ctx) { return ntick(cb, ctx); } function trim(str) { return str ? str.replace(/^\s*|\s*$/g, '') : ''; } function trimEnd(str, chars) { if (str && chars === undefined) { return str.replace(/\s+$/, ''); } if (!str || !chars) { return str; } return str.replace(new RegExp(("[" + chars + "]+$")), ''); } function toLower(str) { return str ? str.toLowerCase() : ''; } function toUpper(str) { return str ? str.toUpperCase() : ''; } var isArray = Array.isArray; function isString(val) { return typeof val === 'string'; } function isFunction(val) { return typeof val === 'function'; } function isObject(obj) { return obj !== null && typeof obj === 'object'; } function isPlainObject(obj) { return isObject(obj) && Object.getPrototypeOf(obj) == Object.prototype; } function isBlob(obj) { return typeof Blob !== 'undefined' && obj instanceof Blob; } function isFormData(obj) { return typeof FormData !== 'undefined' && obj instanceof FormData; } function when(value, fulfilled, rejected) { var promise = PromiseObj.resolve(value); if (arguments.length < 2) { return promise; } return promise.then(fulfilled, rejected); } function options(fn, obj, opts) { opts = opts || {}; if (isFunction(opts)) { opts = opts.call(obj); } return merge(fn.bind({$vm: obj, $options: opts}), fn, {$options: opts}); } function each(obj, iterator) { var i, key; if (isArray(obj)) { for (i = 0; i < obj.length; i++) { iterator.call(obj[i], obj[i], i); } } else if (isObject(obj)) { for (key in obj) { if (hasOwnProperty.call(obj, key)) { iterator.call(obj[key], obj[key], key); } } } return obj; } var assign = Object.assign || _assign; function merge(target) { var args = slice.call(arguments, 1); args.forEach(function (source) { _merge(target, source, true); }); return target; } function defaults(target) { var args = slice.call(arguments, 1); args.forEach(function (source) { for (var key in source) { if (target[key] === undefined) { target[key] = source[key]; } } }); return target; } function _assign(target) { var args = slice.call(arguments, 1); args.forEach(function (source) { _merge(target, source); }); return target; } function _merge(target, source, deep) { for (var key in source) { if (deep && (isPlainObject(source[key]) || isArray(source[key]))) { if (isPlainObject(source[key]) && !isPlainObject(target[key])) { target[key] = {}; } if (isArray(source[key]) && !isArray(target[key])) { target[key] = []; } _merge(target[key], source[key], deep); } else if (source[key] !== undefined) { target[key] = source[key]; } } } /** * Root Prefix Transform. */ var root = function (options$$1, next) { var url = next(options$$1); if (isString(options$$1.root) && !/^(https?:)?\//.test(url)) { url = trimEnd(options$$1.root, '/') + '/' + url; } return url; }; /** * Query Parameter Transform. */ var query = function (options$$1, next) { var urlParams = Object.keys(Url.options.params), query = {}, url = next(options$$1); each(options$$1.params, function (value, key) { if (urlParams.indexOf(key) === -1) { query[key] = value; } }); query = Url.params(query); if (query) { url += (url.indexOf('?') == -1 ? '?' : '&') + query; } return url; }; /** * URL Template v2.0.6 (https://github.com/bramstein/url-template) */ function expand(url, params, variables) { var tmpl = parse(url), expanded = tmpl.expand(params); if (variables) { variables.push.apply(variables, tmpl.vars); } return expanded; } function parse(template) { var operators = ['+', '#', '.', '/', ';', '?', '&'], variables = []; return { vars: variables, expand: function expand(context) { return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { if (expression) { var operator = null, values = []; if (operators.indexOf(expression.charAt(0)) !== -1) { operator = expression.charAt(0); expression = expression.substr(1); } expression.split(/,/g).forEach(function (variable) { var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); values.push.apply(values, getValues(context, operator, tmp[1], tmp[2] || tmp[3])); variables.push(tmp[1]); }); if (operator && operator !== '+') { var separator = ','; if (operator === '?') { separator = '&'; } else if (operator !== '#') { separator = operator; } return (values.length !== 0 ? operator : '') + values.join(separator); } else { return values.join(','); } } else { return encodeReserved(literal); } }); } }; } function getValues(context, operator, key, modifier) { var value = context[key], result = []; if (isDefined(value) && value !== '') { if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { value = value.toString(); if (modifier && modifier !== '*') { value = value.substring(0, parseInt(modifier, 10)); } result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null)); } else { if (modifier === '*') { if (Array.isArray(value)) { value.filter(isDefined).forEach(function (value) { result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : null)); }); } else { Object.keys(value).forEach(function (k) { if (isDefined(value[k])) { result.push(encodeValue(operator, value[k], k)); } }); } } else { var tmp = []; if (Array.isArray(value)) { value.filter(isDefined).forEach(function (value) { tmp.push(encodeValue(operator, value)); }); } else { Object.keys(value).forEach(function (k) { if (isDefined(value[k])) { tmp.push(encodeURIComponent(k)); tmp.push(encodeValue(operator, value[k].toString())); } }); } if (isKeyOperator(operator)) { result.push(encodeURIComponent(key) + '=' + tmp.join(',')); } else if (tmp.length !== 0) { result.push(tmp.join(',')); } } } } else { if (operator === ';') { result.push(encodeURIComponent(key)); } else if (value === '' && (operator === '&' || operator === '?')) { result.push(encodeURIComponent(key) + '='); } else if (value === '') { result.push(''); } } return result; } function isDefined(value) { return value !== undefined && value !== null; } function isKeyOperator(operator) { return operator === ';' || operator === '&' || operator === '?'; } function encodeValue(operator, value, key) { value = (operator === '+' || operator === '#') ? encodeReserved(value) : encodeURIComponent(value); if (key) { return encodeURIComponent(key) + '=' + value; } else { return value; } } function encodeReserved(str) { return str.split(/(%[0-9A-Fa-f]{2})/g).map(function (part) { if (!/%[0-9A-Fa-f]/.test(part)) { part = encodeURI(part); } return part; }).join(''); } /** * URL Template (RFC 6570) Transform. */ var template = function (options) { var variables = [], url = expand(options.url, options.params, variables); variables.forEach(function (key) { delete options.params[key]; }); return url; }; /** * Service for URL templating. */ function Url(url, params) { var self = this || {}, options$$1 = url, transform; if (isString(url)) { options$$1 = {url: url, params: params}; } options$$1 = merge({}, Url.options, self.$options, options$$1); Url.transforms.forEach(function (handler) { if (isString(handler)) { handler = Url.transform[handler]; } if (isFunction(handler)) { transform = factory(handler, transform, self.$vm); } }); return transform(options$$1); } /** * Url options. */ Url.options = { url: '', root: null, params: {} }; /** * Url transforms. */ Url.transform = {template: template, query: query, root: root}; Url.transforms = ['template', 'query', 'root']; /** * Encodes a Url parameter string. * * @param {Object} obj */ Url.params = function (obj) { var params = [], escape = encodeURIComponent; params.add = function (key, value) { if (isFunction(value)) { value = value(); } if (value === null) { value = ''; } this.push(escape(key) + '=' + escape(value)); }; serialize(params, obj); return params.join('&').replace(/%20/g, '+'); }; /** * Parse a URL and return its components. * * @param {String} url */ Url.parse = function (url) { var el = document.createElement('a'); if (document.documentMode) { el.href = url; url = el.href; } el.href = url; return { href: el.href, protocol: el.protocol ? el.protocol.replace(/:$/, '') : '', port: el.port, host: el.host, hostname: el.hostname, pathname: el.pathname.charAt(0) === '/' ? el.pathname : '/' + el.pathname, search: el.search ? el.search.replace(/^\?/, '') : '', hash: el.hash ? el.hash.replace(/^#/, '') : '' }; }; function factory(handler, next, vm) { return function (options$$1) { return handler.call(vm, options$$1, next); }; } function serialize(params, obj, scope) { var array = isArray(obj), plain = isPlainObject(obj), hash; each(obj, function (value, key) { hash = isObject(value) || isArray(value); if (scope) { key = scope + '[' + (plain || hash ? key : '') + ']'; } if (!scope && array) { params.add(value.name, value.value); } else if (hash) { serialize(params, value, key); } else { params.add(key, value); } }); } /** * XDomain client (Internet Explorer). */ var xdrClient = function (request) { return new PromiseObj(function (resolve) { var xdr = new XDomainRequest(), handler = function (ref) { var type = ref.type; var status = 0; if (type === 'load') { status = 200; } else if (type === 'error') { status = 500; } resolve(request.respondWith(xdr.responseText, {status: status})); }; request.abort = function () { return xdr.abort(); }; xdr.open(request.method, request.getUrl()); if (request.timeout) { xdr.timeout = request.timeout; } xdr.onload = handler; xdr.onabort = handler; xdr.onerror = handler; xdr.ontimeout = handler; xdr.onprogress = function () {}; xdr.send(request.getBody()); }); }; /** * CORS Interceptor. */ var SUPPORTS_CORS = inBrowser && 'withCredentials' in new XMLHttpRequest(); var cors = function (request, next) { if (inBrowser) { var orgUrl = Url.parse(location.href); var reqUrl = Url.parse(request.getUrl()); if (reqUrl.protocol !== orgUrl.protocol || reqUrl.host !== orgUrl.host) { request.crossOrigin = true; request.emulateHTTP = false; if (!SUPPORTS_CORS) { request.client = xdrClient; } } } next(); }; /** * Form data Interceptor. */ var form = function (request, next) { if (isFormData(request.body)) { request.headers.delete('Content-Type'); } else if (isObject(request.body) && request.emulateJSON) { request.body = Url.params(request.body); request.headers.set('Content-Type', 'application/x-www-form-urlencoded'); } next(); }; /** * JSON Interceptor. */ var json = function (request, next) { var type = request.headers.get('Content-Type') || ''; if (isObject(request.body) && type.indexOf('application/json') === 0) { request.body = JSON.stringify(request.body); } next(function (response) { return response.bodyText ? when(response.text(), function (text) { type = response.headers.get('Content-Type') || ''; if (type.indexOf('application/json') === 0 || isJson(text)) { try { response.body = JSON.parse(text); } catch (e) { response.body = null; } } else { response.body = text; } return response; }) : response; }); }; function isJson(str) { var start = str.match(/^\[|^\{(?!\{)/), end = {'[': /]$/, '{': /}$/}; return start && end[start[0]].test(str); } /** * JSONP client (Browser). */ var jsonpClient = function (request) { return new PromiseObj(function (resolve) { var name = request.jsonp || 'callback', callback = request.jsonpCallback || '_jsonp' + Math.random().toString(36).substr(2), body = null, handler, script; handler = function (ref) { var type = ref.type; var status = 0; if (type === 'load' && body !== null) { status = 200; } else if (type === 'error') { status = 500; } if (status && window[callback]) { delete window[callback]; document.body.removeChild(script); } resolve(request.respondWith(body, {status: status})); }; window[callback] = function (result) { body = JSON.stringify(result); }; request.abort = function () { handler({type: 'abort'}); }; request.params[name] = callback; if (request.timeout) { setTimeout(request.abort, request.timeout); } script = document.createElement('script'); script.src = request.getUrl(); script.type = 'text/javascript'; script.async = true; script.onload = handler; script.onerror = handler; document.body.appendChild(script); }); }; /** * JSONP Interceptor. */ var jsonp = function (request, next) { if (request.method == 'JSONP') { request.client = jsonpClient; } next(); }; /** * Before Interceptor. */ var before = function (request, next) { if (isFunction(request.before)) { request.before.call(this, request); } next(); }; /** * HTTP method override Interceptor. */ var method = function (request, next) { if (request.emulateHTTP && /^(PUT|PATCH|DELETE)$/i.test(request.method)) { request.headers.set('X-HTTP-Method-Override', request.method); request.method = 'POST'; } next(); }; /** * Header Interceptor. */ var header = function (request, next) { var headers = assign({}, Http.headers.common, !request.crossOrigin ? Http.headers.custom : {}, Http.headers[toLower(request.method)] ); each(headers, function (value, name) { if (!request.headers.has(name)) { request.headers.set(name, value); } }); next(); }; /** * XMLHttp client (Browser). */ var xhrClient = function (request) { return new PromiseObj(function (resolve) { var xhr = new XMLHttpRequest(), handler = function (event) { var response = request.respondWith( 'response' in xhr ? xhr.response : xhr.responseText, { status: xhr.status === 1223 ? 204 : xhr.status, // IE9 status bug statusText: xhr.status === 1223 ? 'No Content' : trim(xhr.statusText) } ); each(trim(xhr.getAllResponseHeaders()).split('\n'), function (row) { response.headers.append(row.slice(0, row.indexOf(':')), row.slice(row.indexOf(':') + 1)); }); resolve(response); }; request.abort = function () { return xhr.abort(); }; if (request.progress) { if (request.method === 'GET') { xhr.addEventListener('progress', request.progress); } else if (/^(POST|PUT)$/i.test(request.method)) { xhr.upload.addEventListener('progress', request.progress); } } xhr.open(request.method, request.getUrl(), true); if (request.timeout) { xhr.timeout = request.timeout; } if (request.responseType && 'responseType' in xhr) { xhr.responseType = request.responseType; } if (request.withCredentials || request.credentials) { xhr.withCredentials = true; } if (!request.crossOrigin) { request.headers.set('X-Requested-With', 'XMLHttpRequest'); } request.headers.forEach(function (value, name) { xhr.setRequestHeader(name, value); }); xhr.onload = handler; xhr.onabort = handler; xhr.onerror = handler; xhr.ontimeout = handler; xhr.send(request.getBody()); }); }; /** * Http client (Node). */ var nodeClient = function (request) { var client = __webpack_require__(6); return new PromiseObj(function (resolve) { var url = request.getUrl(); var body = request.getBody(); var method = request.method; var headers = {}, handler; request.headers.forEach(function (value, name) { headers[name] = value; }); client(url, {body: body, method: method, headers: headers}).then(handler = function (resp) { var response = request.respondWith(resp.body, { status: resp.statusCode, statusText: trim(resp.statusMessage) } ); each(resp.headers, function (value, name) { response.headers.set(name, value); }); resolve(response); }, function (error$$1) { return handler(error$$1.response); }); }); }; /** * Base client. */ var Client = function (context) { var reqHandlers = [sendRequest], resHandlers = [], handler; if (!isObject(context)) { context = null; } function Client(request) { return new PromiseObj(function (resolve, reject) { function exec() { handler = reqHandlers.pop(); if (isFunction(handler)) { handler.call(context, request, next); } else { warn(("Invalid interceptor of type " + (typeof handler) + ", must be a function")); next(); } } function next(response) { if (isFunction(response)) { resHandlers.unshift(response); } else if (isObject(response)) { resHandlers.forEach(function (handler) { response = when(response, function (response) { return handler.call(context, response) || response; }, reject); }); when(response, resolve, reject); return; } exec(); } exec(); }, context); } Client.use = function (handler) { reqHandlers.push(handler); }; return Client; }; function sendRequest(request, resolve) { var client = request.client || (inBrowser ? xhrClient : nodeClient); resolve(client(request)); } /** * HTTP Headers. */ var Headers = function Headers(headers) { var this$1 = this; this.map = {}; each(headers, function (value, name) { return this$1.append(name, value); }); }; Headers.prototype.has = function has (name) { return getName(this.map, name) !== null; }; Headers.prototype.get = function get (name) { var list = this.map[getName(this.map, name)]; return list ? list.join() : null; }; Headers.prototype.getAll = function getAll (name) { return this.map[getName(this.map, name)] || []; }; Headers.prototype.set = function set (name, value) { this.map[normalizeName(getName(this.map, name) || name)] = [trim(value)]; }; Headers.prototype.append = function append (name, value){ var list = this.map[getName(this.map, name)]; if (list) { list.push(trim(value)); } else { this.set(name, value); } }; Headers.prototype.delete = function delete$1 (name){ delete this.map[getName(this.map, name)]; }; Headers.prototype.deleteAll = function deleteAll (){ this.map = {}; }; Headers.prototype.forEach = function forEach (callback, thisArg) { var this$1 = this; each(this.map, function (list, name) { each(list, function (value) { return callback.call(thisArg, value, name, this$1); }); }); }; function getName(map, name) { return Object.keys(map).reduce(function (prev, curr) { return toLower(name) === toLower(curr) ? curr : prev; }, null); } function normalizeName(name) { if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) { throw new TypeError('Invalid character in header field name'); } return trim(name); } /** * HTTP Response. */ var Response = function Response(body, ref) { var url = ref.url; var headers = ref.headers; var status = ref.status; var statusText = ref.statusText; this.url = url; this.ok = status >= 200 && status < 300; this.status = status || 0; this.statusText = statusText || ''; this.headers = new Headers(headers); this.body = body; if (isString(body)) { this.bodyText = body; } else if (isBlob(body)) { this.bodyBlob = body; if (isBlobText(body)) { this.bodyText = blobText(body); } } }; Response.prototype.blob = function blob () { return when(this.bodyBlob); }; Response.prototype.text = function text () { return when(this.bodyText); }; Response.prototype.json = function json () { return when(this.text(), function (text) { return JSON.parse(text); }); }; Object.defineProperty(Response.prototype, 'data', { get: function get() { return this.body; }, set: function set(body) { this.body = body; } }); function blobText(body) { return new PromiseObj(function (resolve) { var reader = new FileReader(); reader.readAsText(body); reader.onload = function () { resolve(reader.result); }; }); } function isBlobText(body) { return body.type.indexOf('text') === 0 || body.type.indexOf('json') !== -1; } /** * HTTP Request. */ var Request = function Request(options$$1) { this.body = null; this.params = {}; assign(this, options$$1, { method: toUpper(options$$1.method || 'GET') }); if (!(this.headers instanceof Headers)) { this.headers = new Headers(this.headers); } }; Request.prototype.getUrl = function getUrl (){ return Url(this); }; Request.prototype.getBody = function getBody (){ return this.body; }; Request.prototype.respondWith = function respondWith (body, options$$1) { return new Response(body, assign(options$$1 || {}, {url: this.getUrl()})); }; /** * Service for sending network requests. */ var COMMON_HEADERS = {'Accept': 'application/json, text/plain, */*'}; var JSON_CONTENT_TYPE = {'Content-Type': 'application/json;charset=utf-8'}; function Http(options$$1) { var self = this || {}, client = Client(self.$vm); defaults(options$$1 || {}, self.$options, Http.options); Http.interceptors.forEach(function (handler) { if (isString(handler)) { handler = Http.interceptor[handler]; } if (isFunction(handler)) { client.use(handler); } }); return client(new Request(options$$1)).then(function (response) { return response.ok ? response : PromiseObj.reject(response); }, function (response) { if (response instanceof Error) { error(response); } return PromiseObj.reject(response); }); } Http.options = {}; Http.headers = { put: JSON_CONTENT_TYPE, post: JSON_CONTENT_TYPE, patch: JSON_CONTENT_TYPE, delete: JSON_CONTENT_TYPE, common: COMMON_HEADERS, custom: {} }; Http.interceptor = {before: before, method: method, jsonp: jsonp, json: json, form: form, header: header, cors: cors}; Http.interceptors = ['before', 'method', 'jsonp', 'json', 'form', 'header', 'cors']; ['get', 'delete', 'head', 'jsonp'].forEach(function (method$$1) { Http[method$$1] = function (url, options$$1) { return this(assign(options$$1 || {}, {url: url, method: method$$1})); }; }); ['post', 'put', 'patch'].forEach(function (method$$1) { Http[method$$1] = function (url, body, options$$1) { return this(assign(options$$1 || {}, {url: url, method: method$$1, body: body})); }; }); /** * Service for interacting with RESTful services. */ function Resource(url, params, actions, options$$1) { var self = this || {}, resource = {}; actions = assign({}, Resource.actions, actions ); each(actions, function (action, name) { action = merge({url: url, params: assign({}, params)}, options$$1, action); resource[name] = function () { return (self.$http || Http)(opts(action, arguments)); }; }); return resource; } function opts(action, args) { var options$$1 = assign({}, action), params = {}, body; switch (args.length) { case 2: params = args[0]; body = args[1]; break; case 1: if (/^(POST|PUT|PATCH)$/i.test(options$$1.method)) { body = args[0]; } else { params = args[0]; } break; case 0: break; default: throw 'Expected up to 2 arguments [params, body], got ' + args.length + ' arguments'; } options$$1.body = body; options$$1.params = assign({}, options$$1.params, params); return options$$1; } Resource.actions = { get: {method: 'GET'}, save: {method: 'POST'}, query: {method: 'GET'}, update: {method: 'PUT'}, remove: {method: 'DELETE'}, delete: {method: 'DELETE'} }; /** * Install plugin. */ function plugin(Vue) { if (plugin.installed) { return; } Util(Vue); Vue.url = Url; Vue.http = Http; Vue.resource = Resource; Vue.Promise = PromiseObj; Object.defineProperties(Vue.prototype, { $url: { get: function get() { return options(Vue.url, this, this.$options.url); } }, $http: { get: function get() { return options(Vue.http, this, this.$options.http); } }, $resource: { get: function get() { return Vue.resource.bind(this); } }, $promise: { get: function get() { var this$1 = this; return function (executor) { return new Vue.Promise(executor, this$1); }; } } }); } if (typeof window !== 'undefined' && window.Vue) { window.Vue.use(plugin); } /* harmony default export */ __webpack_exports__["default"] = (plugin); /***/ }), /* 2 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* WEBPACK VAR INJECTION */(function(process) {/** * vue-router v2.7.0 * (c) 2017 Evan You * @license MIT */ /* */ function assert (condition, message) { if (!condition) { throw new Error(("[vue-router] " + message)) } } function warn (condition, message) { if (process.env.NODE_ENV !== 'production' && !condition) { typeof console !== 'undefined' && console.warn(("[vue-router] " + message)); } } function isError (err) { return Object.prototype.toString.call(err).indexOf('Error') > -1 } var View = { name: 'router-view', functional: true, props: { name: { type: String, default: 'default' } }, render: function render (_, ref) { var props = ref.props; var children = ref.children; var parent = ref.parent; var data = ref.data; data.routerView = true; // directly use parent context's createElement() function // so that components rendered by router-view can resolve named slots var h = parent.$createElement; var name = props.name; var route = parent.$route; var cache = parent._routerViewCache || (parent._routerViewCache = {}); // determine current view depth, also check to see if the tree // has been toggled inactive but kept-alive. var depth = 0; var inactive = false; while (parent && parent._routerRoot !== parent) { if (parent.$vnode && parent.$vnode.data.routerView) { depth++; } if (parent._inactive) { inactive = true; } parent = parent.$parent; } data.routerViewDepth = depth; // render previous view if the tree is inactive and kept-alive if (inactive) { return h(cache[name], data, children) } var matched = route.matched[depth]; // render empty node if no matched route if (!matched) { cache[name] = null; return h() } var component = cache[name] = matched.components[name]; // attach instance registration hook // this will be called in the instance's injected lifecycle hooks data.registerRouteInstance = function (vm, val) { // val could be undefined for unregistration var current = matched.instances[name]; if ( (val && current !== vm) || (!val && current === vm) ) { matched.instances[name] = val; } } // also regiseter instance in prepatch hook // in case the same component instance is reused across different routes ;(data.hook || (data.hook = {})).prepatch = function (_, vnode) { matched.instances[name] = vnode.componentInstance; }; // resolve props data.props = resolveProps(route, matched.props && matched.props[name]); return h(component, data, children) } }; function resolveProps (route, config) { switch (typeof config) { case 'undefined': return case 'object': return config case 'function': return config(route) case 'boolean': return config ? route.params : undefined default: if (process.env.NODE_ENV !== 'production') { warn( false, "props in \"" + (route.path) + "\" is a " + (typeof config) + ", " + "expecting an object, function or boolean." ); } } } /* */ var encodeReserveRE = /[!'()*]/g; var encodeReserveReplacer = function (c) { return '%' + c.charCodeAt(0).toString(16); }; var commaRE = /%2C/g; // fixed encodeURIComponent which is more conformant to RFC3986: // - escapes [!'()*] // - preserve commas var encode = function (str) { return encodeURIComponent(str) .replace(encodeReserveRE, encodeReserveReplacer) .replace(commaRE, ','); }; var decode = decodeURIComponent; function resolveQuery ( query, extraQuery, _parseQuery ) { if ( extraQuery === void 0 ) extraQuery = {}; var parse = _parseQuery || parseQuery; var parsedQuery; try { parsedQuery = parse(query || ''); } catch (e) { process.env.NODE_ENV !== 'production' && warn(false, e.message); parsedQuery = {}; } for (var key in extraQuery) { var val = extraQuery[key]; parsedQuery[key] = Array.isArray(val) ? val.slice() : val; } return parsedQuery } function parseQuery (query) { var res = {}; query = query.trim().replace(/^(\?|#|&)/, ''); if (!query) { return res } query.split('&').forEach(function (param) { var parts = param.replace(/\+/g, ' ').split('='); var key = decode(parts.shift()); var val = parts.length > 0 ? decode(parts.join('=')) : null; if (res[key] === undefined) { res[key] = val; } else if (Array.isArray(res[key])) { res[key].push(val); } else { res[key] = [res[key], val]; } }); return res } function stringifyQuery (obj) { var res = obj ? Object.keys(obj).map(function (key) { var val = obj[key]; if (val === undefined) { return '' } if (val === null) { return encode(key) } if (Array.isArray(val)) { var result = []; val.forEach(function (val2) { if (val2 === undefined) { return } if (val2 === null) { result.push(encode(key)); } else { result.push(encode(key) + '=' + encode(val2)); } }); return result.join('&') } return encode(key) + '=' + encode(val) }).filter(function (x) { return x.length > 0; }).join('&') : null; return res ? ("?" + res) : '' } /* */ var trailingSlashRE = /\/?$/; function createRoute ( record, location, redirectedFrom, router ) { var stringifyQuery$$1 = router && router.options.stringifyQuery; var route = { name: location.name || (record && record.name), meta: (record && record.meta) || {}, path: location.path || '/', hash: location.hash || '', query: location.query || {}, params: location.params || {}, fullPath: getFullPath(location, stringifyQuery$$1), matched: record ? formatMatch(record) : [] }; if (redirectedFrom) { route.redirectedFrom = getFullPath(redirectedFrom, stringifyQuery$$1); } return Object.freeze(route) } // the starting route that represents the initial state var START = createRoute(null, { path: '/' }); function formatMatch (record) { var res = []; while (record) { res.unshift(record); record = record.parent; } return res } function getFullPath ( ref, _stringifyQuery ) { var path = ref.path; var query = ref.query; if ( query === void 0 ) query = {}; var hash = ref.hash; if ( hash === void 0 ) hash = ''; var stringify = _stringifyQuery || stringifyQuery; return (path || '/') + stringify(query) + hash } function isSameRoute (a, b) { if (b === START) { return a === b } else if (!b) { return false } else if (a.path && b.path) { return ( a.path.replace(trailingSlashRE, '') === b.path.replace(trailingSlashRE, '') && a.hash === b.hash && isObjectEqual(a.query, b.query) ) } else if (a.name && b.name) { return ( a.name === b.name && a.hash === b.hash && isObjectEqual(a.query, b.query) && isObjectEqual(a.params, b.params) ) } else { return false } } function isObjectEqual (a, b) { if ( a === void 0 ) a = {}; if ( b === void 0 ) b = {}; var aKeys = Object.keys(a); var bKeys = Object.keys(b); if (aKeys.length !== bKeys.length) { return false } return aKeys.every(function (key) { var aVal = a[key]; var bVal = b[key]; // check nested equality if (typeof aVal === 'object' && typeof bVal === 'object') { return isObjectEqual(aVal, bVal) } return String(aVal) === String(bVal) }) } function isIncludedRoute (current, target) { return ( current.path.replace(trailingSlashRE, '/').indexOf( target.path.replace(trailingSlashRE, '/') ) === 0 && (!target.hash || current.hash === target.hash) && queryIncludes(current.query, target.query) ) } function queryIncludes (current, target) { for (var key in target) { if (!(key in current)) { return false } } return true } /* */ // work around weird flow bug var toTypes = [String, Object]; var eventTypes = [String, Array]; var Link = { name: 'router-link', props: { to: { type: toTypes, required: true }, tag: { type: String, default: 'a' }, exact: Boolean, append: Boolean, replace: Boolean, activeClass: String, exactActiveClass: String, event: { type: eventTypes, default: 'click' } }, render: function render (h) { var this$1 = this; var router = this.$router; var current = this.$route; var ref = router.resolve(this.to, current, this.append); var location = ref.location; var route = ref.route; var href = ref.href; var classes = {}; var globalActiveClass = router.options.linkActiveClass; var globalExactActiveClass = router.options.linkExactActiveClass; // Support global empty active class var activeClassFallback = globalActiveClass == null ? 'router-link-active' : globalActiveClass; var exactActiveClassFallback = globalExactActiveClass == null ? 'router-link-exact-active' : globalExactActiveClass; var activeClass = this.activeClass == null ? activeClassFallback : this.activeClass; var exactActiveClass = this.exactActiveClass == null ? exactActiveClassFallback : this.exactActiveClass; var compareTarget = location.path ? createRoute(null, location, null, router) : route; classes[exactActiveClass] = isSameRoute(current, compareTarget); classes[activeClass] = this.exact ? classes[exactActiveClass] : isIncludedRoute(current, compareTarget); var handler = function (e) { if (guardEvent(e)) { if (this$1.replace) { router.replace(location); } else { router.push(location); } } }; var on = { click: guardEvent }; if (Array.isArray(this.event)) { this.event.forEach(function (e) { on[e] = handler; }); } else { on[this.event] = handler; } var data = { class: classes }; if (this.tag === 'a') { data.on = on; data.attrs = { href: href }; } else { // find the first <a> child and apply listener and href var a = findAnchor(this.$slots.default); if (a) { // in case the <a> is a static node a.isStatic = false; var extend = _Vue.util.extend; var aData = a.data = extend({}, a.data); aData.on = on; var aAttrs = a.data.attrs = extend({}, a.data.attrs); aAttrs.href = href; } else { // doesn't have <a> child, apply listener to self data.on = on; } } return h(this.tag, data, this.$slots.default) } }; function guardEvent (e) { // don't redirect with control keys if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) { return } // don't redirect when preventDefault called if (e.defaultPrevented) { return } // don't redirect on right click if (e.button !== undefined && e.button !== 0) { return } // don't redirect if `target="_blank"` if (e.currentTarget && e.currentTarget.getAttribute) { var target = e.currentTarget.getAttribute('target'); if (/\b_blank\b/i.test(target)) { return } } // this may be a Weex event which doesn't have this method if (e.preventDefault) { e.preventDefault(); } return true } function findAnchor (children) { if (children) { var child; for (var i = 0; i < children.length; i++) { child = children[i]; if (child.tag === 'a') { return child } if (child.children && (child = findAnchor(child.children))) { return child } } } } var _Vue; function install (Vue) { if (install.installed) { return } install.installed = true; _Vue = Vue; var isDef = function (v) { return v !== undefined; }; var registerInstance = function (vm, callVal) { var i = vm.$options._parentVnode; if (isDef(i) && isDef(i = i.data) && isDef(i = i.registerRouteInstance)) { i(vm, callVal); } }; Vue.mixin({ beforeCreate: function beforeCreate () { if (isDef(this.$options.router)) { this._routerRoot = this; this._router = this.$options.router; this._router.init(this); Vue.util.defineReactive(this, '_route', this._router.history.current); } else { this._routerRoot = (this.$parent && this.$parent._routerRoot) || this; } registerInstance(this, this); }, destroyed: function destroyed () { registerInstance(this); } }); Object.defineProperty(Vue.prototype, '$router', { get: function get () { return this._routerRoot._router } }); Object.defineProperty(Vue.prototype, '$route', { get: function get () { return this._routerRoot._route } }); Vue.component('router-view', View); Vue.component('router-link', Link); var strats = Vue.config.optionMergeStrategies; // use the same hook merging strategy for route hooks strats.beforeRouteEnter = strats.beforeRouteLeave = strats.beforeRouteUpdate = strats.created; } /* */ var inBrowser = typeof window !== 'undefined'; /* */ function resolvePath ( relative, base, append ) { var firstChar = relative.charAt(0); if (firstChar === '/') { return relative } if (firstChar === '?' || firstChar === '#') { return base + relative } var stack = base.split('/'); // remove trailing segment if: // - not appending // - appending to trailing slash (last segment is empty) if (!append || !stack[stack.length - 1]) { stack.pop(); } // resolve relative path var segments = relative.replace(/^\//, '').split('/'); for (var i = 0; i < segments.length; i++) { var segment = segments[i]; if (segment === '..') { stack.pop(); } else if (segment !== '.') { stack.push(segment); } } // ensure leading slash if (stack[0] !== '') { stack.unshift(''); } return stack.join('/') } function parsePath (path) { var hash = ''; var query = ''; var hashIndex = path.indexOf('#'); if (hashIndex >= 0) { hash = path.slice(hashIndex); path = path.slice(0, hashIndex); } var queryIndex = path.indexOf('?'); if (queryIndex >= 0) { query = path.slice(queryIndex + 1); path = path.slice(0, queryIndex); } return { path: path, query: query, hash: hash } } function cleanPath (path) { return path.replace(/\/\//g, '/') } var index$1 = Array.isArray || function (arr) { return Object.prototype.toString.call(arr) == '[object Array]'; }; /** * Expose `pathToRegexp`. */ var index = pathToRegexp; var parse_1 = parse; var compile_1 = compile; var tokensToFunction_1 = tokensToFunction; var tokensToRegExp_1 = tokensToRegExp; /** * The main path matching regexp utility. * * @type {RegExp} */ var PATH_REGEXP = new RegExp([ // Match escaped characters that would otherwise appear in future matches. // This allows the user to escape special characters that won't transform. '(\\\\.)', // Match Express-style parameters and un-named parameters with a prefix // and optional suffixes. Matches appear as: // // "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined] // "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined] // "/*" => ["/", undefined, undefined, undefined, undefined, "*"] '([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))' ].join('|'), 'g'); /** * Parse a string for the raw tokens. * * @param {string} str * @param {Object=} options * @return {!Array} */ function parse (str, options) { var tokens = []; var key = 0; var index = 0; var path = ''; var defaultDelimiter = options && options.delimiter || '/'; var res; while ((res = PATH_REGEXP.exec(str)) != null) { var m = res[0]; var escaped = res[1]; var offset = res.index; path += str.slice(index, offset); index = offset + m.length; // Ignore already escaped sequences. if (escaped) { path += escaped[1]; continue } var next = str[index]; var prefix = res[2]; var name = res[3]; var capture = res[4]; var group = res[5]; var modifier = res[6]; var asterisk = res[7]; // Push the current path onto the tokens. if (path) { tokens.push(path); path = ''; } var partial = prefix != null && next != null && next !== prefix; var repeat = modifier === '+' || modifier === '*'; var optional = modifier === '?' || modifier === '*'; var delimiter = res[2] || defaultDelimiter; var pattern = capture || group; tokens.push({ name: name || key++, prefix: prefix || '', delimiter: delimiter, optional: optional, repeat: repeat, partial: partial, asterisk: !!asterisk, pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?') }); } // Match any characters still remaining. if (index < str.length) { path += str.substr(index); } // If the path exists, push it onto the end. if (path) { tokens.push(path); } return tokens } /** * Compile a string to a template function for the path. * * @param {string} str * @param {Object=} options * @return {!function(Object=, Object=)} */ function compile (str, options) { return tokensToFunction(parse(str, options)) } /** * Prettier encoding of URI path segments. * * @param {string} * @return {string} */ function encodeURIComponentPretty (str) { return encodeURI(str).replace(/[\/?#]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } /** * Encode the asterisk parameter. Similar to `pretty`, but allows slashes. * * @param {string} * @return {string} */ function encodeAsterisk (str) { return encodeURI(str).replace(/[?#]/g, function (c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase() }) } /** * Expose a method for transforming tokens into the path function. */ function tokensToFunction (tokens) { // Compile all the tokens into regexps. var matches = new Array(tokens.length); // Compile all the patterns before compilation. for (var i = 0; i < tokens.length; i++) { if (typeof tokens[i] === 'object') { matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$'); } } return function (obj, opts) { var path = ''; var data = obj || {}; var options = opts || {}; var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (typeof token === 'string') { path += token; continue } var value = data[token.name]; var segment; if (value == null) { if (token.optional) { // Prepend partial segment prefixes. if (token.partial) { path += token.prefix; } continue } else { throw new TypeError('Expected "' + token.name + '" to be defined') } } if (index$1(value)) { if (!token.repeat) { throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`') } if (value.length === 0) { if (token.optional) { continue } else { throw new TypeError('Expected "' + token.name + '" to not be empty') } } for (var j = 0; j < value.length; j++) { segment = encode(value[j]); if (!matches[i].test(segment)) { throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`') } path += (j === 0 ? token.prefix : token.delimiter) + segment; } continue } segment = token.asterisk ? encodeAsterisk(value) : encode(value); if (!matches[i].test(segment)) { throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"') } path += token.prefix + segment; } return path } } /** * Escape a regular expression string. * * @param {string} str * @return {string} */ function escapeString (str) { return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1') } /** * Escape the capturing group by escaping special characters and meaning. * * @param {string} group * @return {string} */ function escapeGroup (group) { return group.replace(/([=!:$\/()])/g, '\\$1') } /** * Attach the keys as a property of the regexp. * * @param {!RegExp} re * @param {Array} keys * @return {!RegExp} */ function attachKeys (re, keys) { re.keys = keys; return re } /** * Get the flags for a regexp from the options. * * @param {Object} options * @return {string} */ function flags (options) { return options.sensitive ? '' : 'i' } /** * Pull out keys from a regexp. * * @param {!RegExp} path * @param {!Array} keys * @return {!RegExp} */ function regexpToRegexp (path, keys) { // Use a negative lookahead to match only capturing groups. var groups = path.source.match(/\((?!\?)/g); if (groups) { for (var i = 0; i < groups.length; i++) { keys.push({ name: i, prefix: null, delimiter: null, optional: false, repeat: false, partial: false, asterisk: false, pattern: null }); } } return attachKeys(path, keys) } /** * Transform an array into a regexp. * * @param {!Array} path * @param {Array} keys * @param {!Object} options * @return {!RegExp} */ function arrayToRegexp (path, keys, options) { var parts = []; for (var i = 0; i < path.length; i++) { parts.push(pathToRegexp(path[i], keys, options).source); } var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options)); return attachKeys(regexp, keys) } /** * Create a path regexp from string input. * * @param {string} path * @param {!Array} keys * @param {!Object} options * @return {!RegExp} */ function stringToRegexp (path, keys, options) { return tokensToRegExp(parse(path, options), keys, options) } /** * Expose a function for taking tokens and returning a RegExp. * * @param {!Array} tokens * @param {(Array|Object)=} keys * @param {Object=} options * @return {!RegExp} */ function tokensToRegExp (tokens, keys, options) { if (!index$1(keys)) { options = /** @type {!Object} */ (keys || options); keys = []; } options = options || {}; var strict = options.strict; var end = options.end !== false; var route = ''; // Iterate over the tokens and create our regexp string. for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (typeof token === 'string') { route += escapeString(token); } else { var prefix = escapeString(token.prefix); var capture = '(?:' + token.pattern + ')'; keys.push(token); if (token.repeat) { capture += '(?:' + prefix + capture + ')*'; } if (token.optional) { if (!token.partial) { capture = '(?:' + prefix + '(' + capture + '))?'; } else { capture = prefix + '(' + capture + ')?'; } } else { capture = prefix + '(' + capture + ')'; } route += capture; } } var delimiter = escapeString(options.delimiter || '/'); var endsWithDelimiter = route.slice(-delimiter.length) === delimiter; // In non-strict mode we allow a slash at the end of match. If the path to // match already ends with a slash, we remove it for consistency. The slash // is valid at the end of a path match, not in the middle. This is important // in non-ending mode, where "/test/" shouldn't match "/test//route". if (!strict) { route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?'; } if (end) { route += '$'; } else { // In non-ending mode, we need the capturing groups to match as much as // possible by using a positive lookahead to the end or next path segment. route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)'; } return attachKeys(new RegExp('^' + route, flags(options)), keys) } /** * Normalize the given path string, returning a regular expression. * * An empty array can be passed in for the keys, which will hold the * placeholder key descriptions. For example, using `/user/:id`, `keys` will * contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`. * * @param {(string|RegExp|Array)} path * @param {(Array|Object)=} keys * @param {Object=} options * @return {!RegExp} */ function pathToRegexp (path, keys, options) { if (!index$1(keys)) { options = /** @type {!Object} */ (keys || options); keys = []; } options = options || {}; if (path instanceof RegExp) { return regexpToRegexp(path, /** @type {!Array} */ (keys)) } if (index$1(path)) { return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options) } return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options) } index.parse = parse_1; index.compile = compile_1; index.tokensToFunction = tokensToFunction_1; index.tokensToRegExp = tokensToRegExp_1; /* */ var regexpCompileCache = Object.create(null); function fillParams ( path, params, routeMsg ) { try { var filler = regexpCompileCache[path] || (regexpCompileCache[path] = index.compile(path)); return filler(params || {}, { pretty: true }) } catch (e) { if (process.env.NODE_ENV !== 'production') { warn(false, ("missing param for " + routeMsg + ": " + (e.message))); } return '' } } /* */ function createRouteMap ( routes, oldPathList, oldPathMap, oldNameMap ) { // the path list is used to control path matching priority var pathList = oldPathList || []; var pathMap = oldPathMap || Object.create(null); var nameMap = oldNameMap || Object.create(null); routes.forEach(function (route) { addRouteRecord(pathList, pathMap, nameMap, route); }); // ensure wildcard routes are always at the end for (var i = 0, l = pathList.length; i < l; i++) { if (pathList[i] === '*') { pathList.push(pathList.splice(i, 1)[0]); l--; i--; } } return { pathList: pathList, pathMap: pathMap, nameMap: nameMap } } function addRouteRecord ( pathList, pathMap, nameMap, route, parent, matchAs ) { var path = route.path; var name = route.name; if (process.env.NODE_ENV !== 'production') { assert(path != null, "\"path\" is required in a route configuration."); assert( typeof route.component !== 'string', "route config \"component\" for path: " + (String(path || name)) + " cannot be a " + "string id. Use an actual component instead." ); } var normalizedPath = normalizePath(path, parent); var pathToRegexpOptions = route.pathToRegexpOptions || {}; if (typeof route.caseSensitive === 'boolean') { pathToRegexpOptions.sensitive = route.caseSensitive; } var record = { path: normalizedPath, regex: compileRouteRegex(normalizedPath, pathToRegexpOptions), components: route.components || { default: route.component }, instances: {}, name: name, parent: parent, matchAs: matchAs, redirect: route.redirect, beforeEnter: route.beforeEnter, meta: route.meta || {}, props: route.props == null ? {} : route.components ? route.props : { default: route.props } }; if (route.children) { // Warn if route is named, does not redirect and has a default child route. // If users navigate to this route by name, the default child will // not be rendered (GH Issue #629) if (process.env.NODE_ENV !== 'production') { if (route.name && !route.redirect && route.children.some(function (child) { return /^\/?$/.test(child.path); })) { warn( false, "Named Route '" + (route.name) + "' has a default child route. " + "When navigating to this named route (:to=\"{name: '" + (route.name) + "'\"), " + "the default child route will not be rendered. Remove the name from " + "this route and use the name of the default child route for named " + "links instead." ); } } route.children.forEach(function (child) { var childMatchAs = matchAs ? cleanPath((matchAs + "/" + (child.path))) : undefined; addRouteRecord(pathList, pathMap, nameMap, child, record, childMatchAs); }); } if (route.alias !== undefined) { var aliases = Array.isArray(route.alias) ? route.alias : [route.alias]; aliases.forEach(function (alias) { var aliasRoute = { path: alias, children: route.children }; addRouteRecord( pathList, pathMap, nameMap, aliasRoute, parent, record.path || '/' // matchAs ); }); } if (!pathMap[record.path]) { pathList.push(record.path); pathMap[record.path] = record; } if (name) { if (!nameMap[name]) { nameMap[name] = record; } else if (process.env.NODE_ENV !== 'production' && !matchAs) { warn( false, "Duplicate named routes definition: " + "{ name: \"" + name + "\", path: \"" + (record.path) + "\" }" ); } } } function compileRouteRegex (path, pathToRegexpOptions) { var regex = index(path, [], pathToRegexpOptions); if (process.env.NODE_ENV !== 'production') { var keys = {}; regex.keys.forEach(function (key) { warn(!keys[key.name], ("Duplicate param keys in route with path: \"" + path + "\"")); keys[key.name] = true; }); } return regex } function normalizePath (path, parent) { path = path.replace(/\/$/, ''); if (path[0] === '/') { return path } if (parent == null) { return path } return cleanPath(((parent.path) + "/" + path)) } /* */ function normalizeLocation ( raw, current, append, router ) { var next = typeof raw === 'string' ? { path: raw } : raw; // named target if (next.name || next._normalized) { return next } // relative params if (!next.path && next.params && current) { next = assign({}, next); next._normalized = true; var params = assign(assign({}, current.params), next.params); if (current.name) { next.name = current.name; next.params = params; } else if (current.matched.length) { var rawPath = current.matched[current.matched.length - 1].path; next.path = fillParams(rawPath, params, ("path " + (current.path))); } else if (process.env.NODE_ENV !== 'production') { warn(false, "relative params navigation requires a current route."); } return next } var parsedPath = parsePath(next.path || ''); var basePath = (current && current.path) || '/'; var path = parsedPath.path ? resolvePath(parsedPath.path, basePath, append || next.append) : basePath; var query = resolveQuery( parsedPath.query, next.query, router && router.options.parseQuery ); var hash = next.hash || parsedPath.hash; if (hash && hash.charAt(0) !== '#') { hash = "#" + hash; } return { _normalized: true, path: path, query: query, hash: hash } } function assign (a, b) { for (var key in b) { a[key] = b[key]; } return a } /* */ function createMatcher ( routes, router ) { var ref = createRouteMap(routes); var pathList = ref.pathList; var pathMap = ref.pathMap; var nameMap = ref.nameMap; function addRoutes (routes) { createRouteMap(routes, pathList, pathMap, nameMap); } function match ( raw, currentRoute, redirectedFrom ) { var location = normalizeLocation(raw, currentRoute, false, router); var name = location.name; if (name) { var record = nameMap[name]; if (process.env.NODE_ENV !== 'production') { warn(record, ("Route with name '" + name + "' does not exist")); } if (!record) { return _createRoute(null, location) } var paramNames = record.regex.keys .filter(function (key) { return !key.optional; }) .map(function (key) { return key.name; }); if (typeof location.params !== 'object') { location.params = {}; } if (currentRoute && typeof currentRoute.params === 'object') { for (var key in currentRoute.params) { if (!(key in location.params) && paramNames.indexOf(key) > -1) { location.params[key] = currentRoute.params[key]; } } } if (record) { location.path = fillParams(record.path, location.params, ("named route \"" + name + "\"")); return _createRoute(record, location, redirectedFrom) } } else if (location.path) { location.params = {}; for (var i = 0; i < pathList.length; i++) { var path = pathList[i]; var record$1 = pathMap[path]; if (matchRoute(record$1.regex, location.path, location.params)) { return _createRoute(record$1, location, redirectedFrom) } } } // no match return _createRoute(null, location) } function redirect ( record, location ) { var originalRedirect = record.redirect; var redirect = typeof originalRedirect === 'function' ? originalRedirect(createRoute(record, location, null, router)) : originalRedirect; if (typeof redirect === 'string') { redirect = { path: redirect }; } if (!redirect || typeof redirect !== 'object') { if (process.env.NODE_ENV !== 'production') { warn( false, ("invalid redirect option: " + (JSON.stringify(redirect))) ); } return _createRoute(null, location) } var re = redirect; var name = re.name; var path = re.path; var query = location.query; var hash = location.hash; var params = location.params; query = re.hasOwnProperty('query') ? re.query : query; hash = re.hasOwnProperty('hash') ? re.hash : hash; params = re.hasOwnProperty('params') ? re.params : params; if (name) { // resolved named direct var targetRecord = nameMap[name]; if (process.env.NODE_ENV !== 'production') { assert(targetRecord, ("redirect failed: named route \"" + name + "\" not found.")); } return match({ _normalized: true, name: name, query: query, hash: hash, params: params }, undefined, location) } else if (path) { // 1. resolve relative redirect var rawPath = resolveRecordPath(path, record); // 2. resolve params var resolvedPath = fillParams(rawPath, params, ("redirect route with path \"" + rawPath + "\"")); // 3. rematch with existing query and hash return match({ _normalized: true, path: resolvedPath, query: query, hash: hash }, undefined, location) } else { if (process.env.NODE_ENV !== 'production') { warn(false, ("invalid redirect option: " + (JSON.stringify(redirect)))); } return _createRoute(null, location) } } function alias ( record, location, matchAs ) { var aliasedPath = fillParams(matchAs, location.params, ("aliased route with path \"" + matchAs + "\"")); var aliasedMatch = match({ _normalized: true, path: aliasedPath }); if (aliasedMatch) { var matched = aliasedMatch.matched; var aliasedRecord = matched[matched.length - 1]; location.params = aliasedMatch.params; return _createRoute(aliasedRecord, location) } return _createRoute(null, location) } function _createRoute ( record, location, redirectedFrom ) { if (record && record.redirect) { return redirect(record, redirectedFrom || location) } if (record && record.matchAs) { return alias(record, location, record.matchAs) } return createRoute(record, location, redirectedFrom, router) } return { match: match, addRoutes: addRoutes } } function matchRoute ( regex, path, params ) { var m = path.match(regex); if (!m) { return false } else if (!params) { return true } for (var i = 1, len = m.length; i < len; ++i) { var key = regex.keys[i - 1]; var val = typeof m[i] === 'string' ? decodeURIComponent(m[i]) : m[i]; if (key) { params[key.name] = val; } } return true } function resolveRecordPath (path, record) { return resolvePath(path, record.parent ? record.parent.path : '/', true) } /* */ var positionStore = Object.create(null); function setupScroll () { window.addEventListener('popstate', function (e) { saveScrollPosition(); if (e.state && e.state.key) { setStateKey(e.state.key); } }); } function handleScroll ( router, to, from, isPop ) { if (!router.app) { return } var behavior = router.options.scrollBehavior; if (!behavior) { return } if (process.env.NODE_ENV !== 'production') { assert(typeof behavior === 'function', "scrollBehavior must be a function"); } // wait until re-render finishes before scrolling router.app.$nextTick(function () { var position = getScrollPosition(); var shouldScroll = behavior(to, from, isPop ? position : null); if (!shouldScroll) { return } var isObject = typeof shouldScroll === 'object'; if (isObject && typeof shouldScroll.selector === 'string') { var el = document.querySelector(shouldScroll.selector); if (el) { var offset = shouldScroll.offset && typeof shouldScroll.offset === 'object' ? shouldScroll.offset : {}; offset = normalizeOffset(offset); position = getElementPosition(el, offset); } else if (isValidPosition(shouldScroll)) { position = normalizePosition(shouldScroll); } } else if (isObject && isValidPosition(shouldScroll)) { position = normalizePosition(shouldScroll); } if (position) { window.scrollTo(position.x, position.y); } }); } function saveScrollPosition () { var key = getStateKey(); if (key) { positionStore[key] = { x: window.pageXOffset, y: window.pageYOffset }; } } function getScrollPosition () { var key = getStateKey(); if (key) { return positionStore[key] } } function getElementPosition (el, offset) { var docEl = document.documentElement; var docRect = docEl.getBoundingClientRect(); var elRect = el.getBoundingClientRect(); return { x: elRect.left - docRect.left - offset.x, y: elRect.top - docRect.top - offset.y } } function isValidPosition (obj) { return isNumber(obj.x) || isNumber(obj.y) } function normalizePosition (obj) { return { x: isNumber(obj.x) ? obj.x : window.pageXOffset, y: isNumber(obj.y) ? obj.y : window.pageYOffset } } function normalizeOffset (obj) { return { x: isNumber(obj.x) ? obj.x : 0, y: isNumber(obj.y) ? obj.y : 0 } } function isNumber (v) { return typeof v === 'number' } /* */ var supportsPushState = inBrowser && (function () { var ua = window.navigator.userAgent; if ( (ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1 ) { return false } return window.history && 'pushState' in window.history })(); // use User Timing api (if present) for more accurate key precision var Time = inBrowser && window.performance && window.performance.now ? window.performance : Date; var _key = genKey(); function genKey () { return Time.now().toFixed(3) } function getStateKey () { return _key } function setStateKey (key) { _key = key; } function pushState (url, replace) { saveScrollPosition(); // try...catch the pushState call to get around Safari // DOM Exception 18 where it limits to 100 pushState calls var history = window.history; try { if (replace) { history.replaceState({ key: _key }, '', url); } else { _key = genKey(); history.pushState({ key: _key }, '', url); } } catch (e) { window.location[replace ? 'replace' : 'assign'](url); } } function replaceState (url) { pushState(url, true); } /* */ function runQueue (queue, fn, cb) { var step = function (index) { if (index >= queue.length) { cb(); } else { if (queue[index]) { fn(queue[index], function () { step(index + 1); }); } else { step(index + 1); } } }; step(0); } /* */ function resolveAsyncComponents (matched) { return function (to, from, next) { var hasAsync = false; var pending = 0; var error = null; flatMapComponents(matched, function (def, _, match, key) { // if it's a function and doesn't have cid attached, // assume it's an async component resolve function. // we are not using Vue's default async resolving mechanism because // we want to halt the navigation until the incoming component has been // resolved. if (typeof def === 'function' && def.cid === undefined) { hasAsync = true; pending++; var resolve = once(function (resolvedDef) { if (resolvedDef.__esModule && resolvedDef.default) { resolvedDef = resolvedDef.default; } // save resolved on async factory in case it's used elsewhere def.resolved = typeof resolvedDef === 'function' ? resolvedDef : _Vue.extend(resolvedDef); match.components[key] = resolvedDef; pending--; if (pending <= 0) { next(); } }); var reject = once(function (reason) { var msg = "Failed to resolve async component " + key + ": " + reason; process.env.NODE_ENV !== 'production' && warn(false, msg); if (!error) { error = isError(reason) ? reason : new Error(msg); next(error); } }); var res; try { res = def(resolve, reject); } catch (e) { reject(e); } if (res) { if (typeof res.then === 'function') { res.then(resolve, reject); } else { // new syntax in Vue 2.3 var comp = res.component; if (comp && typeof comp.then === 'function') { comp.then(resolve, reject); } } } } }); if (!hasAsync) { next(); } } } function flatMapComponents ( matched, fn ) { return flatten(matched.map(function (m) { return Object.keys(m.components).map(function (key) { return fn( m.components[key], m.instances[key], m, key ); }) })) } function flatten (arr) { return Array.prototype.concat.apply([], arr) } // in Webpack 2, require.ensure now also returns a Promise // so the resolve/reject functions may get called an extra time // if the user uses an arrow function shorthand that happens to // return that Promise. function once (fn) { var called = false; return function () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; if (called) { return } called = true; return fn.apply(this, args) } } /* */ var History = function History (router, base) { this.router = router; this.base = normalizeBase(base); // start with a route object that stands for "nowhere" this.current = START; this.pending = null; this.ready = false; this.readyCbs = []; this.readyErrorCbs = []; this.errorCbs = []; }; History.prototype.listen = function listen (cb) { this.cb = cb; }; History.prototype.onReady = function onReady (cb, errorCb) { if (this.ready) { cb(); } else { this.readyCbs.push(cb); if (errorCb) { this.readyErrorCbs.push(errorCb); } } }; History.prototype.onError = function onError (errorCb) { this.errorCbs.push(errorCb); }; History.prototype.transitionTo = function transitionTo (location, onComplete, onAbort) { var this$1 = this; var route = this.router.match(location, this.current); this.confirmTransition(route, function () { this$1.updateRoute(route); onComplete && onComplete(route); this$1.ensureURL(); // fire ready cbs once if (!this$1.ready) { this$1.ready = true; this$1.readyCbs.forEach(function (cb) { cb(route); }); } }, function (err) { if (onAbort) { onAbort(err); } if (err && !this$1.ready) { this$1.ready = true; this$1.readyErrorCbs.forEach(function (cb) { cb(err); }); } }); }; History.prototype.confirmTransition = function confirmTransition (route, onComplete, onAbort) { var this$1 = this; var current = this.current; var abort = function (err) { if (isError(err)) { if (this$1.errorCbs.length) { this$1.errorCbs.forEach(function (cb) { cb(err); }); } else { warn(false, 'uncaught error during route navigation:'); console.error(err); } } onAbort && onAbort(err); }; if ( isSameRoute(route, current) && // in the case the route map has been dynamically appended to route.matched.length === current.matched.length ) { this.ensureURL(); return abort() } var ref = resolveQueue(this.current.matched, route.matched); var updated = ref.updated; var deactivated = ref.deactivated; var activated = ref.activated; var queue = [].concat( // in-component leave guards extractLeaveGuards(deactivated), // global before hooks this.router.beforeHooks, // in-component update hooks extractUpdateHooks(updated), // in-config enter guards activated.map(function (m) { return m.beforeEnter; }), // async components resolveAsyncComponents(activated) ); this.pending = route; var iterator = function (hook, next) { if (this$1.pending !== route) { return abort() } try { hook(route, current, function (to) { if (to === false || isError(to)) { // next(false) -> abort navigation, ensure current URL this$1.ensureURL(true); abort(to); } else if ( typeof to === 'string' || (typeof to === 'object' && ( typeof to.path === 'string' || typeof to.name === 'string' )) ) { // next('/') or next({ path: '/' }) -> redirect abort(); if (typeof to === 'object' && to.replace) { this$1.replace(to); } else { this$1.push(to); } } else { // confirm transition and pass on the value next(to); } }); } catch (e) { abort(e); } }; runQueue(queue, iterator, function () { var postEnterCbs = []; var isValid = function () { return this$1.current === route; }; // wait until async components are resolved before // extracting in-component enter guards var enterGuards = extractEnterGuards(activated, postEnterCbs, isValid); var queue = enterGuards.concat(this$1.router.resolveHooks); runQueue(queue, iterator, function () { if (this$1.pending !== route) { return abort() } this$1.pending = null; onComplete(route); if (this$1.router.app) { this$1.router.app.$nextTick(function () { postEnterCbs.forEach(function (cb) { cb(); }); }); } }); }); }; History.prototype.updateRoute = function updateRoute (route) { var prev = this.current; this.current = route; this.cb && this.cb(route); this.router.afterHooks.forEach(function (hook) { hook && hook(route, prev); }); }; function normalizeBase (base) { if (!base) { if (inBrowser) { // respect <base> tag var baseEl = document.querySelector('base'); base = (baseEl && baseEl.getAttribute('href')) || '/'; // strip full URL origin base = base.replace(/^https?:\/\/[^\/]+/, ''); } else { base = '/'; } } // make sure there's the starting slash if (base.charAt(0) !== '/') { base = '/' + base; } // remove trailing slash return base.replace(/\/$/, '') } function resolveQueue ( current, next ) { var i; var max = Math.max(current.length, next.length); for (i = 0; i < max; i++) { if (current[i] !== next[i]) { break } } return { updated: next.slice(0, i), activated: next.slice(i), deactivated: current.slice(i) } } function extractGuards ( records, name, bind, reverse ) { var guards = flatMapComponents(records, function (def, instance, match, key) { var guard = extractGuard(def, name); if (guard) { return Array.isArray(guard) ? guard.map(function (guard) { return bind(guard, instance, match, key); }) : bind(guard, instance, match, key) } }); return flatten(reverse ? guards.reverse() : guards) } function extractGuard ( def, key ) { if (typeof def !== 'function') { // extend now so that global mixins are applied. def = _Vue.extend(def); } return def.options[key] } function extractLeaveGuards (deactivated) { return extractGuards(deactivated, 'beforeRouteLeave', bindGuard, true) } function extractUpdateHooks (updated) { return extractGuards(updated, 'beforeRouteUpdate', bindGuard) } function bindGuard (guard, instance) { if (instance) { return function boundRouteGuard () { return guard.apply(instance, arguments) } } } function extractEnterGuards ( activated, cbs, isValid ) { return extractGuards(activated, 'beforeRouteEnter', function (guard, _, match, key) { return bindEnterGuard(guard, match, key, cbs, isValid) }) } function bindEnterGuard ( guard, match, key, cbs, isValid ) { return function routeEnterGuard (to, from, next) { return guard(to, from, function (cb) { next(cb); if (typeof cb === 'function') { cbs.push(function () { // #750 // if a router-view is wrapped with an out-in transition, // the instance may not have been registered at this time. // we will need to poll for registration until current route // is no longer valid. poll(cb, match.instances, key, isValid); }); } }) } } function poll ( cb, // somehow flow cannot infer this is a function instances, key, isValid ) { if (instances[key]) { cb(instances[key]); } else if (isValid()) { setTimeout(function () { poll(cb, instances, key, isValid); }, 16); } } /* */ var HTML5History = (function (History$$1) { function HTML5History (router, base) { var this$1 = this; History$$1.call(this, router, base); var expectScroll = router.options.scrollBehavior; if (expectScroll) { setupScroll(); } window.addEventListener('popstate', function (e) { var current = this$1.current; this$1.transitionTo(getLocation(this$1.base), function (route) { if (expectScroll) { handleScroll(router, route, current, true); } }); }); } if ( History$$1 ) HTML5History.__proto__ = History$$1; HTML5History.prototype = Object.create( History$$1 && History$$1.prototype ); HTML5History.prototype.constructor = HTML5History; HTML5History.prototype.go = function go (n) { window.history.go(n); }; HTML5History.prototype.push = function push (location, onComplete, onAbort) { var this$1 = this; var ref = this; var fromRoute = ref.current; this.transitionTo(location, function (route) { pushState(cleanPath(this$1.base + route.fullPath)); handleScroll(this$1.router, route, fromRoute, false); onComplete && onComplete(route); }, onAbort); }; HTML5History.prototype.replace = function replace (location, onComplete, onAbort) { var this$1 = this; var ref = this; var fromRoute = ref.current; this.transitionTo(location, function (route) { replaceState(cleanPath(this$1.base + route.fullPath)); handleScroll(this$1.router, route, fromRoute, false); onComplete && onComplete(route); }, onAbort); }; HTML5History.prototype.ensureURL = function ensureURL (push) { if (getLocation(this.base) !== this.current.fullPath) { var current = cleanPath(this.base + this.current.fullPath); push ? pushState(current) : replaceState(current); } }; HTML5History.prototype.getCurrentLocation = function getCurrentLocation () { return getLocation(this.base) }; return HTML5History; }(History)); function getLocation (base) { var path = window.location.pathname; if (base && path.indexOf(base) === 0) { path = path.slice(base.length); } return (path || '/') + window.location.search + window.location.hash } /* */ var HashHistory = (function (History$$1) { function HashHistory (router, base, fallback) { History$$1.call(this, router, base); // check history fallback deeplinking if (fallback && checkFallback(this.base)) { return } ensureSlash(); } if ( History$$1 ) HashHistory.__proto__ = History$$1; HashHistory.prototype = Object.create( History$$1 && History$$1.prototype ); HashHistory.prototype.constructor = HashHistory; // this is delayed until the app mounts // to avoid the hashchange listener being fired too early HashHistory.prototype.setupListeners = function setupListeners () { var this$1 = this; window.addEventListener('hashchange', function () { if (!ensureSlash()) { return } this$1.transitionTo(getHash(), function (route) { replaceHash(route.fullPath); }); }); }; HashHistory.prototype.push = function push (location, onComplete, onAbort) { this.transitionTo(location, function (route) { pushHash(route.fullPath); onComplete && onComplete(route); }, onAbort); }; HashHistory.prototype.replace = function replace (location, onComplete, onAbort) { this.transitionTo(location, function (route) { replaceHash(route.fullPath); onComplete && onComplete(route); }, onAbort); }; HashHistory.prototype.go = function go (n) { window.history.go(n); }; HashHistory.prototype.ensureURL = function ensureURL (push) { var current = this.current.fullPath; if (getHash() !== current) { push ? pushHash(current) : replaceHash(current); } }; HashHistory.prototype.getCurrentLocation = function getCurrentLocation () { return getHash() }; return HashHistory; }(History)); function checkFallback (base) { var location = getLocation(base); if (!/^\/#/.test(location)) { window.location.replace( cleanPath(base + '/#' + location) ); return true } } function ensureSlash () { var path = getHash(); if (path.charAt(0) === '/') { return true } replaceHash('/' + path); return false } function getHash () { // We can't use window.location.hash here because it's not // consistent across browsers - Firefox will pre-decode it! var href = window.location.href; var index = href.indexOf('#'); return index === -1 ? '' : href.slice(index + 1) } function pushHash (path) { window.location.hash = path; } function replaceHash (path) { var href = window.location.href; var i = href.indexOf('#'); var base = i >= 0 ? href.slice(0, i) : href; window.location.replace((base + "#" + path)); } /* */ var AbstractHistory = (function (History$$1) { function AbstractHistory (router, base) { History$$1.call(this, router, base); this.stack = []; this.index = -1; } if ( History$$1 ) AbstractHistory.__proto__ = History$$1; AbstractHistory.prototype = Object.create( History$$1 && History$$1.prototype ); AbstractHistory.prototype.constructor = AbstractHistory; AbstractHistory.prototype.push = function push (location, onComplete, onAbort) { var this$1 = this; this.transitionTo(location, function (route) { this$1.stack = this$1.stack.slice(0, this$1.index + 1).concat(route); this$1.index++; onComplete && onComplete(route); }, onAbort); }; AbstractHistory.prototype.replace = function replace (location, onComplete, onAbort) { var this$1 = this; this.transitionTo(location, function (route) { this$1.stack = this$1.stack.slice(0, this$1.index).concat(route); onComplete && onComplete(route); }, onAbort); }; AbstractHistory.prototype.go = function go (n) { var this$1 = this; var targetIndex = this.index + n; if (targetIndex < 0 || targetIndex >= this.stack.length) { return } var route = this.stack[targetIndex]; this.confirmTransition(route, function () { this$1.index = targetIndex; this$1.updateRoute(route); }); }; AbstractHistory.prototype.getCurrentLocation = function getCurrentLocation () { var current = this.stack[this.stack.length - 1]; return current ? current.fullPath : '/' }; AbstractHistory.prototype.ensureURL = function ensureURL () { // noop }; return AbstractHistory; }(History)); /* */ var VueRouter = function VueRouter (options) { if ( options === void 0 ) options = {}; this.app = null; this.apps = []; this.options = options; this.beforeHooks = []; this.resolveHooks = []; this.afterHooks = []; this.matcher = createMatcher(options.routes || [], this); var mode = options.mode || 'hash'; this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false; if (this.fallback) { mode = 'hash'; } if (!inBrowser) { mode = 'abstract'; } this.mode = mode; switch (mode) { case 'history': this.history = new HTML5History(this, options.base); break case 'hash': this.history = new HashHistory(this, options.base, this.fallback); break case 'abstract': this.history = new AbstractHistory(this, options.base); break default: if (process.env.NODE_ENV !== 'production') { assert(false, ("invalid mode: " + mode)); } } }; var prototypeAccessors = { currentRoute: {} }; VueRouter.prototype.match = function match ( raw, current, redirectedFrom ) { return this.matcher.match(raw, current, redirectedFrom) }; prototypeAccessors.currentRoute.get = function () { return this.history && this.history.current }; VueRouter.prototype.init = function init (app /* Vue component instance */) { var this$1 = this; process.env.NODE_ENV !== 'production' && assert( install.installed, "not installed. Make sure to call `Vue.use(VueRouter)` " + "before creating root instance." ); this.apps.push(app); // main app already initialized. if (this.app) { return } this.app = app; var history = this.history; if (history instanceof HTML5History) { history.transitionTo(history.getCurrentLocation()); } else if (history instanceof HashHistory) { var setupHashListener = function () { history.setupListeners(); }; history.transitionTo( history.getCurrentLocation(), setupHashListener, setupHashListener ); } history.listen(function (route) { this$1.apps.forEach(function (app) { app._route = route; }); }); }; VueRouter.prototype.beforeEach = function beforeEach (fn) { return registerHook(this.beforeHooks, fn) }; VueRouter.prototype.beforeResolve = function beforeResolve (fn) { return registerHook(this.resolveHooks, fn) }; VueRouter.prototype.afterEach = function afterEach (fn) { return registerHook(this.afterHooks, fn) }; VueRouter.prototype.onReady = function onReady (cb, errorCb) { this.history.onReady(cb, errorCb); }; VueRouter.prototype.onError = function onError (errorCb) { this.history.onError(errorCb); }; VueRouter.prototype.push = function push (location, onComplete, onAbort) { this.history.push(location, onComplete, onAbort); }; VueRouter.prototype.replace = function replace (location, onComplete, onAbort) { this.history.replace(location, onComplete, onAbort); }; VueRouter.prototype.go = function go (n) { this.history.go(n); }; VueRouter.prototype.back = function back () { this.go(-1); }; VueRouter.prototype.forward = function forward () { this.go(1); }; VueRouter.prototype.getMatchedComponents = function getMatchedComponents (to) { var route = to ? to.matched ? to : this.resolve(to).route : this.currentRoute; if (!route) { return [] } return [].concat.apply([], route.matched.map(function (m) { return Object.keys(m.components).map(function (key) { return m.components[key] }) })) }; VueRouter.prototype.resolve = function resolve ( to, current, append ) { var location = normalizeLocation( to, current || this.history.current, append, this ); var route = this.match(location, current); var fullPath = route.redirectedFrom || route.fullPath; var base = this.history.base; var href = createHref(base, fullPath, this.mode); return { location: location, route: route, href: href, // for backwards compat normalizedTo: location, resolved: route } }; VueRouter.prototype.addRoutes = function addRoutes (routes) { this.matcher.addRoutes(routes); if (this.history.current !== START) { this.history.transitionTo(this.history.getCurrentLocation()); } }; Object.defineProperties( VueRouter.prototype, prototypeAccessors ); function registerHook (list, fn) { list.push(fn); return function () { var i = list.indexOf(fn); if (i > -1) { list.splice(i, 1); } } } function createHref (base, fullPath, mode) { var path = mode === 'hash' ? '#' + fullPath : fullPath; return base ? cleanPath(base + '/' + path) : path } VueRouter.install = install; VueRouter.version = '2.7.0'; if (inBrowser && window.Vue) { window.Vue.use(VueRouter); } /* harmony default export */ __webpack_exports__["default"] = (VueRouter); /* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(0))) /***/ }), /* 3 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* WEBPACK VAR INJECTION */(function(process, global) {/*! * Vue.js v2.3.4 * (c) 2014-2017 Evan You * Released under the MIT License. */ /* */ // these helpers produces better vm code in JS engines due to their // explicitness and function inlining function isUndef (v) { return v === undefined || v === null } function isDef (v) { return v !== undefined && v !== null } function isTrue (v) { return v === true } function isFalse (v) { return v === false } /** * Check if value is primitive */ function isPrimitive (value) { return typeof value === 'string' || typeof value === 'number' } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } var _toString = Object.prototype.toString; /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject (obj) { return _toString.call(obj) === '[object Object]' } function isRegExp (v) { return _toString.call(v) === '[object RegExp]' } /** * Convert a value to a string that is actually rendered. */ function toString (val) { return val == null ? '' : typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val) } /** * Convert a input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Remove an item from an array */ function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether the object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /([^-])([A-Z])/g; var hyphenate = cached(function (str) { return str .replace(hyphenateRE, '$1-$2') .replace(hyphenateRE, '$1-$2') .toLowerCase() }); /** * Simple bind, faster than native */ function bind (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } // record original fn length boundFn._length = fn.length; return boundFn } /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /** * Perform no operation. */ function noop () {} /** * Always return false. */ var no = function () { return false; }; /** * Return same value */ var identity = function (_) { return _; }; /** * Generate a static keys string from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { return JSON.stringify(a) === JSON.stringify(b) } catch (e) { // possible circular reference return a === b } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /** * Ensure a function is called only once. */ function once (fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } } } var SSR_ATTR = 'data-server-rendered'; var ASSET_TYPES = [ 'component', 'directive', 'filter' ]; var LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated' ]; /* */ var config = ({ /** * Option merge strategies (used in core/util/options) */ optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: process.env.NODE_ENV !== 'production', /** * Whether to enable devtools */ devtools: process.env.NODE_ENV !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS }); /* */ var emptyObject = Object.freeze({}); /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = /[^\w.$]/; function parsePath (path) { if (bailRE.test(path)) { return } var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } /* */ var warn = noop; var tip = noop; var formatComponentName = (null); // work around flow check if (process.env.NODE_ENV !== 'production') { var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; var classify = function (str) { return str .replace(classifyRE, function (c) { return c.toUpperCase(); }) .replace(/[-_]/g, ''); }; warn = function (msg, vm) { if (hasConsole && (!config.silent)) { console.error("[Vue warn]: " + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; tip = function (msg, vm) { if (hasConsole && (!config.silent)) { console.warn("[Vue tip]: " + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; formatComponentName = function (vm, includeFile) { if (vm.$root === vm) { return '<Root>' } var name = typeof vm === 'string' ? vm : typeof vm === 'function' && vm.options ? vm.options.name : vm._isVue ? vm.$options.name || vm.$options._componentTag : vm.name; var file = vm._isVue && vm.$options.__file; if (!name && file) { var match = file.match(/([^/\\]+)\.vue$/); name = match && match[1]; } return ( (name ? ("<" + (classify(name)) + ">") : "<Anonymous>") + (file && includeFile !== false ? (" at " + file) : '') ) }; var repeat = function (str, n) { var res = ''; while (n) { if (n % 2 === 1) { res += str; } if (n > 1) { str += str; } n >>= 1; } return res }; var generateComponentTrace = function (vm) { if (vm._isVue && vm.$parent) { var tree = []; var currentRecursiveSequence = 0; while (vm) { if (tree.length > 0) { var last = tree[tree.length - 1]; if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; continue } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [last, currentRecursiveSequence]; currentRecursiveSequence = 0; } } tree.push(vm); vm = vm.$parent; } return '\n\nfound in\n\n' + tree .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") : formatComponentName(vm))); }) .join('\n') } else { return ("\n\n(found in " + (formatComponentName(vm)) + ")") } }; } /* */ function handleError (err, vm, info) { if (config.errorHandler) { config.errorHandler.call(null, err, vm, info); } else { if (process.env.NODE_ENV !== 'production') { warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); } /* istanbul ignore else */ if (inBrowser && typeof console !== 'undefined') { console.error(err); } else { throw err } } } /* */ /* globals MutationObserver */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = UA && UA.indexOf('android') > 0; var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; var supportsPassive = false; if (inBrowser) { try { var opts = {}; Object.defineProperty(opts, 'passive', ({ get: function get () { /* istanbul ignore next */ supportsPassive = true; } } )); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) {} } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) } var hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); /** * Defer a task to execute it asynchronously. */ var nextTick = (function () { var callbacks = []; var pending = false; var timerFunc; function nextTickHandler () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // the nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore if */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); var logError = function (err) { console.error(err); }; timerFunc = function () { p.then(nextTickHandler).catch(logError); // in problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; } else if (typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]' )) { // use MutationObserver where native Promise is not available, // e.g. PhantomJS IE11, iOS7, Android 4.4 var counter = 1; var observer = new MutationObserver(nextTickHandler); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; } else { // fallback to setTimeout /* istanbul ignore next */ timerFunc = function () { setTimeout(nextTickHandler, 0); }; } return function queueNextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve, reject) { _resolve = resolve; }) } } })(); var _Set; /* istanbul ignore if */ if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = (function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } /* */ var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; var targetStack = []; function pushTarget (_target) { if (Dep.target) { targetStack.push(Dep.target); } Dep.target = _target; } function popTarget () { Dep.target = targetStack.pop(); } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto);[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] .forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var arguments$1 = arguments; // avoid leaking arguments: // http://jsperf.com/closure-with-arguments var i = arguments.length; var args = new Array(i); while (i--) { args[i] = arguments$1[i]; } var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': inserted = args; break case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * By default, when a reactive property is set, the new value is * also converted to become reactive. However when passing down props, * we don't want to force conversion because the value may be a nested value * under a frozen data structure. Converting it would defeat the optimization. */ var observerState = { shouldConvert: true, isSettingProps: false }; /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } }; /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive$$1(obj, keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment an target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value, asRootData) { if (!isObject(value)) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( observerState.shouldConvert && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob } /** * Define a reactive property on an Object. */ function defineReactive$$1 ( obj, key, val, customSetter ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; var childOb = observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); } if (Array.isArray(value)) { dependArray(value); } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (process.env.NODE_ENV !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set (target, key, val) { if (Array.isArray(target) && typeof key === 'number') { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val } if (hasOwn(target, key)) { target[key] = val; return val } var ob = (target ).__ob__; if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return val } if (!ob) { target[key] = val; return val } defineReactive$$1(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (target, key) { if (Array.isArray(target) && typeof key === 'number') { target.splice(key, 1); return } var ob = (target ).__ob__; if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(target, key)) { return } delete target[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ if (process.env.NODE_ENV !== 'production') { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if (isPlainObject(toVal) && isPlainObject(fromVal)) { mergeData(toVal, fromVal); } } return to } /** * Data */ strats.data = function ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (typeof childVal !== 'function') { process.env.NODE_ENV !== 'production' && warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( childVal.call(this), parentVal.call(this) ) } } else if (parentVal || childVal) { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : undefined; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } }; /** * Hooks and props are merged as arrays. */ function mergeHook ( parentVal, childVal ) { return childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal } LIFECYCLE_HOOKS.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets (parentVal, childVal) { var res = Object.create(parentVal || null); return childVal ? extend(res, childVal) : res } ASSET_TYPES.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function (parentVal, childVal) { /* istanbul ignore if */ if (!childVal) { return Object.create(parentVal || null) } if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key in childVal) { var parent = ret[key]; var child = childVal[key]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key] = parent ? parent.concat(child) : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.computed = function (parentVal, childVal) { if (!childVal) { return Object.create(parentVal || null) } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); extend(ret, childVal); return ret }; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { var lower = key.toLowerCase(); if (isBuiltInTag(lower) || config.isReservedTag(lower)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + key ); } } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else if (process.env.NODE_ENV !== 'production') { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } options.props = res; } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def = dirs[key]; if (typeof def === 'function') { dirs[key] = { bind: def, update: def }; } } } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { if (process.env.NODE_ENV !== 'production') { checkComponents(child); } if (typeof child === 'function') { child = child.options; } normalizeProps(child); normalizeDirectives(child); var extendsFrom = child.extends; if (extendsFrom) { parent = mergeOptions(parent, extendsFrom, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (process.env.NODE_ENV !== 'production' && warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // handle boolean props if (isType(Boolean, prop.type)) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) { value = true; } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldConvert = observerState.shouldConvert; observerState.shouldConvert = true; observe(value); observerState.shouldConvert = prevShouldConvert; } if (process.env.NODE_ENV !== 'production') { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (process.env.NODE_ENV !== 'production' && isObject(def)) { warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm._props[key] !== undefined ) { return vm._props[key] } // call factory function for non-Function types // a value is Function if its prototype is function even across different execution context return typeof def === 'function' && getType(prop.type) !== 'Function' ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( 'Invalid prop: type check failed for prop "' + name + '".' + ' Expected ' + expectedTypes.map(capitalize).join(', ') + ', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.', vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; function assertType (value, type) { var valid; var expectedType = getType(type); if (simpleCheckRE.test(expectedType)) { valid = typeof value === expectedType.toLowerCase(); } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match ? match[1] : '' } function isType (type, fn) { if (!Array.isArray(fn)) { return getType(fn) === getType(type) } for (var i = 0, len = fn.length; i < len; i++) { if (getType(fn[i]) === getType(type)) { return true } } /* istanbul ignore next */ return false } /* */ var mark; var measure; if (process.env.NODE_ENV !== 'production') { var perf = inBrowser && window.performance; /* istanbul ignore if */ if ( perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures ) { mark = function (tag) { return perf.mark(tag); }; measure = function (name, startTag, endTag) { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); perf.clearMeasures(name); }; } } /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; if (process.env.NODE_ENV !== 'production') { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + "referenced during render. Make sure to declare reactive data " + "properties in the data option.", target ); }; var hasProxy = typeof Proxy !== 'undefined' && Proxy.toString().match(/native code/); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || key.charAt(0) === '_'; if (!has && !isAllowed) { warnNonPresent(target, key); } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { warnNonPresent(target, key); } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.functionalContext = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; }; var prototypeAccessors = { child: {} }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { return this.componentInstance }; Object.defineProperties( VNode.prototype, prototypeAccessors ); var createEmptyVNode = function () { var node = new VNode(); node.text = ''; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode) { var cloned = new VNode( vnode.tag, vnode.data, vnode.children, vnode.text, vnode.elm, vnode.context, vnode.componentOptions ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.isCloned = true; return cloned } function cloneVNodes (vnodes) { var len = vnodes.length; var res = new Array(len); for (var i = 0; i < len; i++) { res[i] = cloneVNode(vnodes[i]); } return res } /* */ var normalizeEvent = cached(function (name) { var passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first name = once$$1 ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, once: once$$1, capture: capture, passive: passive } }); function createFnInvoker (fns) { function invoker () { var arguments$1 = arguments; var fns = invoker.fns; if (Array.isArray(fns)) { for (var i = 0; i < fns.length; i++) { fns[i].apply(null, arguments$1); } } else { // return handler return value for single handlers return fns.apply(null, arguments) } } invoker.fns = fns; return invoker } function updateListeners ( on, oldOn, add, remove$$1, vm ) { var name, cur, old, event; for (name in on) { cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (isUndef(cur)) { process.env.NODE_ENV !== 'production' && warn( "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), vm ); } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur); } add(event.name, cur, event.once, event.capture, event.passive); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name], event.capture); } } } /* */ function mergeVNodeHook (def, hookKey, hook) { var invoker; var oldHook = def[hookKey]; function wrappedHook () { hook.apply(this, arguments); // important: remove merged hook to ensure it's called only once // and prevent memory leak remove(invoker.fns, wrappedHook); } if (isUndef(oldHook)) { // no existing hook invoker = createFnInvoker([wrappedHook]); } else { /* istanbul ignore if */ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { // already a merged invoker invoker = oldHook; invoker.fns.push(wrappedHook); } else { // existing plain hook invoker = createFnInvoker([oldHook, wrappedHook]); } } invoker.merged = true; def[hookKey] = invoker; } /* */ function extractPropsFromVNodeData ( data, Ctor, tag ) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (isUndef(propOptions)) { return } var res = {}; var attrs = data.attrs; var props = data.props; if (isDef(attrs) || isDef(props)) { for (var key in propOptions) { var altKey = hyphenate(key); if (process.env.NODE_ENV !== 'production') { var keyInLowerCase = key.toLowerCase(); if ( key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase) ) { tip( "Prop \"" + keyInLowerCase + "\" is passed to component " + (formatComponentName(tag || Ctor)) + ", but the declared prop name is" + " \"" + key + "\". " + "Note that HTML attributes are case-insensitive and camelCased " + "props need to use their kebab-case equivalents when using in-DOM " + "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"." ); } } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array<VNode>. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // 2. When the children contains constructs that always generated nested Arrays, // e.g. <template>, <slot>, v-for, or when the children is provided by user // with hand-written render functions / JSX. In such cases a full normalization // is needed to cater to all possible types of children values. function normalizeChildren (children) { return isPrimitive(children) ? [createTextVNode(children)] : Array.isArray(children) ? normalizeArrayChildren(children) : undefined } function isTextNode (node) { return isDef(node) && isDef(node.text) && isFalse(node.isComment) } function normalizeArrayChildren (children, nestedIndex) { var res = []; var i, c, last; for (i = 0; i < children.length; i++) { c = children[i]; if (isUndef(c) || typeof c === 'boolean') { continue } last = res[res.length - 1]; // nested if (Array.isArray(c)) { res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i))); } else if (isPrimitive(c)) { if (isTextNode(last)) { // merge adjacent text nodes // this is necessary for SSR hydration because text nodes are // essentially merged when rendered to HTML strings (last).text += String(c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (isTextNode(c) && isTextNode(last)) { // merge adjacent text nodes res[res.length - 1] = createTextVNode(last.text + c.text); } else { // default key for nested array children (likely generated by v-for) if (isTrue(children._isVList) && isDef(c.tag) && isUndef(c.key) && isDef(nestedIndex)) { c.key = "__vlist" + nestedIndex + "_" + i + "__"; } res.push(c); } } } return res } /* */ function ensureCtor (comp, base) { return isObject(comp) ? base.extend(comp) : comp } function resolveAsyncComponent ( factory, baseCtor, context ) { if (isTrue(factory.error) && isDef(factory.errorComp)) { return factory.errorComp } if (isDef(factory.resolved)) { return factory.resolved } if (isTrue(factory.loading) && isDef(factory.loadingComp)) { return factory.loadingComp } if (isDef(factory.contexts)) { // already pending factory.contexts.push(context); } else { var contexts = factory.contexts = [context]; var sync = true; var forceRender = function () { for (var i = 0, l = contexts.length; i < l; i++) { contexts[i].$forceUpdate(); } }; var resolve = once(function (res) { // cache resolved factory.resolved = ensureCtor(res, baseCtor); // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { forceRender(); } }); var reject = once(function (reason) { process.env.NODE_ENV !== 'production' && warn( "Failed to resolve async component: " + (String(factory)) + (reason ? ("\nReason: " + reason) : '') ); if (isDef(factory.errorComp)) { factory.error = true; forceRender(); } }); var res = factory(resolve, reject); if (isObject(res)) { if (typeof res.then === 'function') { // () => Promise if (isUndef(factory.resolved)) { res.then(resolve, reject); } } else if (isDef(res.component) && typeof res.component.then === 'function') { res.component.then(resolve, reject); if (isDef(res.error)) { factory.errorComp = ensureCtor(res.error, baseCtor); } if (isDef(res.loading)) { factory.loadingComp = ensureCtor(res.loading, baseCtor); if (res.delay === 0) { factory.loading = true; } else { setTimeout(function () { if (isUndef(factory.resolved) && isUndef(factory.error)) { factory.loading = true; forceRender(); } }, res.delay || 200); } } if (isDef(res.timeout)) { setTimeout(function () { if (isUndef(factory.resolved)) { reject( process.env.NODE_ENV !== 'production' ? ("timeout (" + (res.timeout) + "ms)") : null ); } }, res.timeout); } } } sync = false; // return in case resolved synchronously return factory.loading ? factory.loadingComp : factory.resolved } } /* */ function getFirstComponentChild (children) { if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var c = children[i]; if (isDef(c) && isDef(c.componentOptions)) { return c } } } } /* */ /* */ function initEvents (vm) { vm._events = Object.create(null); vm._hasHookEvent = false; // init parent attached events var listeners = vm.$options._parentListeners; if (listeners) { updateComponentListeners(vm, listeners); } } var target; function add (event, fn, once$$1) { if (once$$1) { target.$once(event, fn); } else { target.$on(event, fn); } } function remove$1 (event, fn) { target.$off(event, fn); } function updateComponentListeners ( vm, listeners, oldListeners ) { target = vm; updateListeners(listeners, oldListeners || {}, add, remove$1, vm); } function eventsMixin (Vue) { var hookRE = /^hook:/; Vue.prototype.$on = function (event, fn) { var this$1 = this; var vm = this; if (Array.isArray(event)) { for (var i = 0, l = event.length; i < l; i++) { this$1.$on(event[i], fn); } } else { (vm._events[event] || (vm._events[event] = [])).push(fn); // optimize hook:event cost by using a boolean flag marked at registration // instead of a hash lookup if (hookRE.test(event)) { vm._hasHookEvent = true; } } return vm }; Vue.prototype.$once = function (event, fn) { var vm = this; function on () { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm }; Vue.prototype.$off = function (event, fn) { var this$1 = this; var vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm } // array of events if (Array.isArray(event)) { for (var i$1 = 0, l = event.length; i$1 < l; i$1++) { this$1.$off(event[i$1], fn); } return vm } // specific event var cbs = vm._events[event]; if (!cbs) { return vm } if (arguments.length === 1) { vm._events[event] = null; return vm } // specific handler var cb; var i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { cbs.splice(i, 1); break } } return vm }; Vue.prototype.$emit = function (event) { var vm = this; if (process.env.NODE_ENV !== 'production') { var lowerCaseEvent = event.toLowerCase(); if (lowerCaseEvent !== event && vm._events[lowerCaseEvent]) { tip( "Event \"" + lowerCaseEvent + "\" is emitted in component " + (formatComponentName(vm)) + " but the handler is registered for \"" + event + "\". " + "Note that HTML attributes are case-insensitive and you cannot use " + "v-on to listen to camelCase events when using in-DOM templates. " + "You should probably use \"" + (hyphenate(event)) + "\" instead of \"" + event + "\"." ); } } var cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { cbs[i].apply(vm, args); } } return vm }; } /* */ /** * Runtime helper for resolving raw children VNodes into a slot object. */ function resolveSlots ( children, context ) { var slots = {}; if (!children) { return slots } var defaultSlot = []; for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.functionalContext === context) && child.data && child.data.slot != null ) { var name = child.data.slot; var slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children); } else { slot.push(child); } } else { defaultSlot.push(child); } } // ignore whitespace if (!defaultSlot.every(isWhitespace)) { slots.default = defaultSlot; } return slots } function isWhitespace (node) { return node.isComment || node.text === ' ' } function resolveScopedSlots ( fns, // see flow/vnode res ) { res = res || {}; for (var i = 0; i < fns.length; i++) { if (Array.isArray(fns[i])) { resolveScopedSlots(fns[i], res); } else { res[fns[i].key] = fns[i].fn; } } return res } /* */ var activeInstance = null; function initLifecycle (vm) { var options = vm.$options; // locate first non-abstract parent var parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = null; vm._directInactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin (Vue) { Vue.prototype._update = function (vnode, hydrating) { var vm = this; if (vm._isMounted) { callHook(vm, 'beforeUpdate'); } var prevEl = vm.$el; var prevVnode = vm._vnode; var prevActiveInstance = activeInstance; activeInstance = vm; vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__( vm.$el, vnode, hydrating, false /* removeOnly */, vm.$options._parentElm, vm.$options._refElm ); } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } activeInstance = prevActiveInstance; // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } // updated hook is called by the scheduler to ensure that children are // updated in a parent's updated hook. }; Vue.prototype.$forceUpdate = function () { var vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function () { var vm = this; if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent var parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } var i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); // fire destroyed hook callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } // remove reference to DOM nodes (prevents leak) vm.$options._parentElm = vm.$options._refElm = null; }; } function mountComponent ( vm, el, hydrating ) { vm.$el = el; if (!vm.$options.render) { vm.$options.render = createEmptyVNode; if (process.env.NODE_ENV !== 'production') { /* istanbul ignore if */ if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') || vm.$options.el || el) { warn( 'You are using the runtime-only build of Vue where the template ' + 'compiler is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); var updateComponent; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { updateComponent = function () { var name = vm._name; var id = vm._uid; var startTag = "vue-perf-start:" + id; var endTag = "vue-perf-end:" + id; mark(startTag); var vnode = vm._render(); mark(endTag); measure((name + " render"), startTag, endTag); mark(startTag); vm._update(vnode, hydrating); mark(endTag); measure((name + " patch"), startTag, endTag); }; } else { updateComponent = function () { vm._update(vm._render(), hydrating); }; } vm._watcher = new Watcher(vm, updateComponent, noop); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm } function updateChildComponent ( vm, propsData, listeners, parentVnode, renderChildren ) { // determine whether component has slot children // we need to do this before overwriting $options._renderChildren var hasChildren = !!( renderChildren || // has new static slots vm.$options._renderChildren || // has old static slots parentVnode.data.scopedSlots || // has new scoped slots vm.$scopedSlots !== emptyObject // has old scoped slots ); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update props if (propsData && vm.$options.props) { observerState.shouldConvert = false; if (process.env.NODE_ENV !== 'production') { observerState.isSettingProps = true; } var props = vm._props; var propKeys = vm.$options._propKeys || []; for (var i = 0; i < propKeys.length; i++) { var key = propKeys[i]; props[key] = validateProp(key, vm.$options.props, propsData, vm); } observerState.shouldConvert = true; if (process.env.NODE_ENV !== 'production') { observerState.isSettingProps = false; } // keep a copy of raw propsData vm.$options.propsData = propsData; } // update listeners if (listeners) { var oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; updateComponentListeners(vm, listeners, oldListeners); } // resolve slots + force update if has children if (hasChildren) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } } function isInInactiveTree (vm) { while (vm && (vm = vm.$parent)) { if (vm._inactive) { return true } } return false } function activateChildComponent (vm, direct) { if (direct) { vm._directInactive = false; if (isInInactiveTree(vm)) { return } } else if (vm._directInactive) { return } if (vm._inactive || vm._inactive === null) { vm._inactive = false; for (var i = 0; i < vm.$children.length; i++) { activateChildComponent(vm.$children[i]); } callHook(vm, 'activated'); } } function deactivateChildComponent (vm, direct) { if (direct) { vm._directInactive = true; if (isInInactiveTree(vm)) { return } } if (!vm._inactive) { vm._inactive = true; for (var i = 0; i < vm.$children.length; i++) { deactivateChildComponent(vm.$children[i]); } callHook(vm, 'deactivated'); } } function callHook (vm, hook) { var handlers = vm.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { try { handlers[i].call(vm); } catch (e) { handleError(e, vm, (hook + " hook")); } } } if (vm._hasHookEvent) { vm.$emit('hook:' + hook); } } /* */ var MAX_UPDATE_COUNT = 100; var queue = []; var activatedChildren = []; var has = {}; var circular = {}; var waiting = false; var flushing = false; var index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState () { index = queue.length = activatedChildren.length = 0; has = {}; if (process.env.NODE_ENV !== 'production') { circular = {}; } waiting = flushing = false; } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue () { flushing = true; var watcher, id; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function (a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index]; id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (process.env.NODE_ENV !== 'production' && has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > MAX_UPDATE_COUNT) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ("in watcher with expression \"" + (watcher.expression) + "\"") : "in a component render function." ), watcher.vm ); break } } } // keep copies of post queues before resetting state var activatedQueue = activatedChildren.slice(); var updatedQueue = queue.slice(); resetSchedulerState(); // call component updated and activated hooks callActivatedHooks(activatedQueue); callUpdateHooks(updatedQueue); // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } } function callUpdateHooks (queue) { var i = queue.length; while (i--) { var watcher = queue[i]; var vm = watcher.vm; if (vm._watcher === watcher && vm._isMounted) { callHook(vm, 'updated'); } } } /** * Queue a kept-alive component that was activated during patch. * The queue will be processed after the entire tree has been patched. */ function queueActivatedComponent (vm) { // setting _inactive to false here so that a render function can // rely on checking whether it's in an inactive tree (e.g. router-view) vm._inactive = false; activatedChildren.push(vm); } function callActivatedHooks (queue) { for (var i = 0; i < queue.length; i++) { queue[i]._inactive = true; activateChildComponent(queue[i], true /* true */); } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher (watcher) { var id = watcher.id; if (has[id] == null) { has[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i > index && queue[i].id > watcher.id) { i--; } queue.splice(i + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; nextTick(flushSchedulerQueue); } } } /* */ var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher ( vm, expOrFn, cb, options ) { this.vm = vm; vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; } else { this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.expression = process.env.NODE_ENV !== 'production' ? expOrFn.toString() : ''; // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = function () {}; process.env.NODE_ENV !== 'production' && warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get () { pushTarget(this); var value; var vm = this.vm; if (this.user) { try { value = this.getter.call(vm, vm); } catch (e) { handleError(e, vm, ("getter for watcher \"" + (this.expression) + "\"")); } } else { value = this.getter.call(vm, vm); } // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); return value }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { var this$1 = this; var i = this.deps.length; while (i--) { var dep = this$1.deps[i]; if (!this$1.newDepIds.has(dep.id)) { dep.removeSub(this$1); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run () { if (this.active) { var value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value var oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { handleError(e, this.vm, ("callback for watcher \"" + (this.expression) + "\"")); } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { var this$1 = this; var i = this.deps.length; while (i--) { this$1.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { var this$1 = this; if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove(this.vm._watchers, this); } var i = this.deps.length; while (i--) { this$1.deps[i].removeSub(this$1); } this.active = false; } }; /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ var seenObjects = new _Set(); function traverse (val) { seenObjects.clear(); _traverse(val, seenObjects); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || !Object.isExtensible(val)) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ var sharedPropertyDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; function proxy (target, sourceKey, key) { sharedPropertyDefinition.get = function proxyGetter () { return this[sourceKey][key] }; sharedPropertyDefinition.set = function proxySetter (val) { this[sourceKey][key] = val; }; Object.defineProperty(target, key, sharedPropertyDefinition); } function initState (vm) { vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch) { initWatch(vm, opts.watch); } } var isReservedProp = { key: 1, ref: 1, slot: 1 }; function initProps (vm, propsOptions) { var propsData = vm.$options.propsData || {}; var props = vm._props = {}; // cache prop keys so that future props updates can iterate using Array // instead of dynamic object key enumeration. var keys = vm.$options._propKeys = []; var isRoot = !vm.$parent; // root instance props should be converted observerState.shouldConvert = isRoot; var loop = function ( key ) { keys.push(key); var value = validateProp(key, propsOptions, propsData, vm); /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { if (isReservedProp[key] || config.isReservedAttr(key)) { warn( ("\"" + key + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive$$1(props, key, value, function () { if (vm.$parent && !observerState.isSettingProps) { warn( "Avoid mutating a prop directly since the value will be " + "overwritten whenever the parent component re-renders. " + "Instead, use a data or computed property based on the prop's " + "value. Prop being mutated: \"" + key + "\"", vm ); } }); } else { defineReactive$$1(props, key, value); } // static props are already proxied on the component's prototype // during Vue.extend(). We only need to proxy props defined at // instantiation here. if (!(key in vm)) { proxy(vm, "_props", key); } }; for (var key in propsOptions) loop( key ); observerState.shouldConvert = true; } function initData (vm) { var data = vm.$options.data; data = vm._data = typeof data === 'function' ? getData(data, vm) : data || {}; if (!isPlainObject(data)) { data = {}; process.env.NODE_ENV !== 'production' && warn( 'data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm ); } // proxy data on instance var keys = Object.keys(data); var props = vm.$options.props; var i = keys.length; while (i--) { if (props && hasOwn(props, keys[i])) { process.env.NODE_ENV !== 'production' && warn( "The data property \"" + (keys[i]) + "\" is already declared as a prop. " + "Use prop default value instead.", vm ); } else if (!isReserved(keys[i])) { proxy(vm, "_data", keys[i]); } } // observe data observe(data, true /* asRootData */); } function getData (data, vm) { try { return data.call(vm) } catch (e) { handleError(e, vm, "data()"); return {} } } var computedWatcherOptions = { lazy: true }; function initComputed (vm, computed) { var watchers = vm._computedWatchers = Object.create(null); for (var key in computed) { var userDef = computed[key]; var getter = typeof userDef === 'function' ? userDef : userDef.get; if (process.env.NODE_ENV !== 'production') { if (getter === undefined) { warn( ("No getter function has been defined for computed property \"" + key + "\"."), vm ); getter = noop; } } // create internal watcher for the computed property. watchers[key] = new Watcher(vm, getter, noop, computedWatcherOptions); // component-defined computed properties are already defined on the // component prototype. We only need to define computed properties defined // at instantiation here. if (!(key in vm)) { defineComputed(vm, key, userDef); } else if (process.env.NODE_ENV !== 'production') { if (key in vm.$data) { warn(("The computed property \"" + key + "\" is already defined in data."), vm); } else if (vm.$options.props && key in vm.$options.props) { warn(("The computed property \"" + key + "\" is already defined as a prop."), vm); } } } } function defineComputed (target, key, userDef) { if (typeof userDef === 'function') { sharedPropertyDefinition.get = createComputedGetter(key); sharedPropertyDefinition.set = noop; } else { sharedPropertyDefinition.get = userDef.get ? userDef.cache !== false ? createComputedGetter(key) : userDef.get : noop; sharedPropertyDefinition.set = userDef.set ? userDef.set : noop; } Object.defineProperty(target, key, sharedPropertyDefinition); } function createComputedGetter (key) { return function computedGetter () { var watcher = this._computedWatchers && this._computedWatchers[key]; if (watcher) { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value } } } function initMethods (vm, methods) { var props = vm.$options.props; for (var key in methods) { vm[key] = methods[key] == null ? noop : bind(methods[key], vm); if (process.env.NODE_ENV !== 'production') { if (methods[key] == null) { warn( "method \"" + key + "\" has an undefined value in the component definition. " + "Did you reference the function correctly?", vm ); } if (props && hasOwn(props, key)) { warn( ("method \"" + key + "\" has already been defined as a prop."), vm ); } } } } function initWatch (vm, watch) { for (var key in watch) { var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } function createWatcher (vm, key, handler) { var options; if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } vm.$watch(key, handler, options); } function stateMixin (Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. var dataDef = {}; dataDef.get = function () { return this._data }; var propsDef = {}; propsDef.get = function () { return this._props }; if (process.env.NODE_ENV !== 'production') { dataDef.set = function (newData) { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; propsDef.set = function () { warn("$props is readonly.", this); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Object.defineProperty(Vue.prototype, '$props', propsDef); Vue.prototype.$set = set; Vue.prototype.$delete = del; Vue.prototype.$watch = function ( expOrFn, cb, options ) { var vm = this; options = options || {}; options.user = true; var watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn () { watcher.teardown(); } }; } /* */ function initProvide (vm) { var provide = vm.$options.provide; if (provide) { vm._provided = typeof provide === 'function' ? provide.call(vm) : provide; } } function initInjections (vm) { var result = resolveInject(vm.$options.inject, vm); if (result) { Object.keys(result).forEach(function (key) { /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { defineReactive$$1(vm, key, result[key], function () { warn( "Avoid mutating an injected value directly since the changes will be " + "overwritten whenever the provided component re-renders. " + "injection being mutated: \"" + key + "\"", vm ); }); } else { defineReactive$$1(vm, key, result[key]); } }); } } function resolveInject (inject, vm) { if (inject) { // inject is :any because flow is not smart enough to figure out cached // isArray here var isArray = Array.isArray(inject); var result = Object.create(null); var keys = isArray ? inject : hasSymbol ? Reflect.ownKeys(inject) : Object.keys(inject); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var provideKey = isArray ? key : inject[key]; var source = vm; while (source) { if (source._provided && provideKey in source._provided) { result[key] = source._provided[provideKey]; break } source = source.$parent; } } return result } } /* */ function createFunctionalComponent ( Ctor, propsData, data, context, children ) { var props = {}; var propOptions = Ctor.options.props; if (isDef(propOptions)) { for (var key in propOptions) { props[key] = validateProp(key, propOptions, propsData || {}); } } else { if (isDef(data.attrs)) { mergeProps(props, data.attrs); } if (isDef(data.props)) { mergeProps(props, data.props); } } // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check var _context = Object.create(context); var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); }; var vnode = Ctor.options.render.call(null, h, { data: data, props: props, children: children, parent: context, listeners: data.on || {}, injections: resolveInject(Ctor.options.inject, context), slots: function () { return resolveSlots(children, context); } }); if (vnode instanceof VNode) { vnode.functionalContext = context; vnode.functionalOptions = Ctor.options; if (data.slot) { (vnode.data || (vnode.data = {})).slot = data.slot; } } return vnode } function mergeProps (to, from) { for (var key in from) { to[camelize(key)] = from[key]; } } /* */ // hooks to be invoked on component VNodes during patch var componentVNodeHooks = { init: function init ( vnode, hydrating, parentElm, refElm ) { if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) { var child = vnode.componentInstance = createComponentInstanceForVnode( vnode, activeInstance, parentElm, refElm ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } else if (vnode.data.keepAlive) { // kept-alive components, treat as a patch var mountedNode = vnode; // work around flow componentVNodeHooks.prepatch(mountedNode, mountedNode); } }, prepatch: function prepatch (oldVnode, vnode) { var options = vnode.componentOptions; var child = vnode.componentInstance = oldVnode.componentInstance; updateChildComponent( child, options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); }, insert: function insert (vnode) { var context = vnode.context; var componentInstance = vnode.componentInstance; if (!componentInstance._isMounted) { componentInstance._isMounted = true; callHook(componentInstance, 'mounted'); } if (vnode.data.keepAlive) { if (context._isMounted) { // vue-router#1212 // During updates, a kept-alive component's child components may // change, so directly walking the tree here may call activated hooks // on incorrect children. Instead we push them into a queue which will // be processed after the whole patch process ended. queueActivatedComponent(componentInstance); } else { activateChildComponent(componentInstance, true /* direct */); } } }, destroy: function destroy (vnode) { var componentInstance = vnode.componentInstance; if (!componentInstance._isDestroyed) { if (!vnode.data.keepAlive) { componentInstance.$destroy(); } else { deactivateChildComponent(componentInstance, true /* direct */); } } } }; var hooksToMerge = Object.keys(componentVNodeHooks); function createComponent ( Ctor, data, context, children, tag ) { if (isUndef(Ctor)) { return } var baseCtor = context.$options._base; // plain options object: turn it into a constructor if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } // if at this stage it's not a constructor or an async component factory, // reject. if (typeof Ctor !== 'function') { if (process.env.NODE_ENV !== 'production') { warn(("Invalid Component definition: " + (String(Ctor))), context); } return } // async component if (isUndef(Ctor.cid)) { Ctor = resolveAsyncComponent(Ctor, baseCtor, context); if (Ctor === undefined) { // return nothing if this is indeed an async component // wait for the callback to trigger parent update. return } } // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); data = data || {}; // transform component v-model data into props & events if (isDef(data.model)) { transformModel(Ctor.options, data); } // extract props var propsData = extractPropsFromVNodeData(data, Ctor, tag); // functional component if (isTrue(Ctor.options.functional)) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners var listeners = data.on; // replace with listeners with .native modifier data.on = data.nativeOn; if (isTrue(Ctor.options.abstract)) { // abstract components do not keep anything // other than props & listeners data = {}; } // merge component management hooks onto the placeholder node mergeHooks(data); // return a placeholder vnode var name = Ctor.options.name || tag; var vnode = new VNode( ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')), data, undefined, undefined, undefined, context, { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children } ); return vnode } function createComponentInstanceForVnode ( vnode, // we know it's MountedComponentVNode but flow doesn't parent, // activeInstance in lifecycle state parentElm, refElm ) { var vnodeComponentOptions = vnode.componentOptions; var options = { _isComponent: true, parent: parent, propsData: vnodeComponentOptions.propsData, _componentTag: vnodeComponentOptions.tag, _parentVnode: vnode, _parentListeners: vnodeComponentOptions.listeners, _renderChildren: vnodeComponentOptions.children, _parentElm: parentElm || null, _refElm: refElm || null }; // check inline-template render functions var inlineTemplate = vnode.data.inlineTemplate; if (isDef(inlineTemplate)) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnodeComponentOptions.Ctor(options) } function mergeHooks (data) { if (!data.hook) { data.hook = {}; } for (var i = 0; i < hooksToMerge.length; i++) { var key = hooksToMerge[i]; var fromParent = data.hook[key]; var ours = componentVNodeHooks[key]; data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours; } } function mergeHook$1 (one, two) { return function (a, b, c, d) { one(a, b, c, d); two(a, b, c, d); } } // transform component v-model info (value and callback) into // prop and event handler respectively. function transformModel (options, data) { var prop = (options.model && options.model.prop) || 'value'; var event = (options.model && options.model.event) || 'input';(data.props || (data.props = {}))[prop] = data.model.value; var on = data.on || (data.on = {}); if (isDef(on[event])) { on[event] = [data.model.callback].concat(on[event]); } else { on[event] = data.model.callback; } } /* */ var SIMPLE_NORMALIZE = 1; var ALWAYS_NORMALIZE = 2; // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement ( context, tag, data, children, normalizationType, alwaysNormalize ) { if (Array.isArray(data) || isPrimitive(data)) { normalizationType = children; children = data; data = undefined; } if (isTrue(alwaysNormalize)) { normalizationType = ALWAYS_NORMALIZE; } return _createElement(context, tag, data, children, normalizationType) } function _createElement ( context, tag, data, children, normalizationType ) { if (isDef(data) && isDef((data).__ob__)) { process.env.NODE_ENV !== 'production' && warn( "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" + 'Always create fresh vnode data objects in each render!', context ); return createEmptyVNode() } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode() } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function' ) { data = data || {}; data.scopedSlots = { default: children[0] }; children.length = 0; } if (normalizationType === ALWAYS_NORMALIZE) { children = normalizeChildren(children); } else if (normalizationType === SIMPLE_NORMALIZE) { children = simpleNormalizeChildren(children); } var vnode, ns; if (typeof tag === 'string') { var Ctor; ns = config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements vnode = new VNode( config.parsePlatformTagName(tag), data, children, undefined, undefined, context ); } else if (isDef(Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag); } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children vnode = new VNode( tag, data, children, undefined, undefined, context ); } } else { // direct component options / constructor vnode = createComponent(tag, data, context, children); } if (isDef(vnode)) { if (ns) { applyNS(vnode, ns); } return vnode } else { return createEmptyVNode() } } function applyNS (vnode, ns) { vnode.ns = ns; if (vnode.tag === 'foreignObject') { // use default namespace inside foreignObject return } if (isDef(vnode.children)) { for (var i = 0, l = vnode.children.length; i < l; i++) { var child = vnode.children[i]; if (isDef(child.tag) && isUndef(child.ns)) { applyNS(child, ns); } } } } /* */ /** * Runtime helper for rendering v-for lists. */ function renderList ( val, render ) { var ret, i, l, keys, key; if (Array.isArray(val) || typeof val === 'string') { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } if (isDef(ret)) { (ret)._isVList = true; } return ret } /* */ /** * Runtime helper for rendering <slot> */ function renderSlot ( name, fallback, props, bindObject ) { var scopedSlotFn = this.$scopedSlots[name]; if (scopedSlotFn) { // scoped slot props = props || {}; if (bindObject) { extend(props, bindObject); } return scopedSlotFn(props) || fallback } else { var slotNodes = this.$slots[name]; // warn duplicate slot usage if (slotNodes && process.env.NODE_ENV !== 'production') { slotNodes._rendered && warn( "Duplicate presence of slot \"" + name + "\" found in the same render tree " + "- this will likely cause render errors.", this ); slotNodes._rendered = true; } return slotNodes || fallback } } /* */ /** * Runtime helper for resolving filters */ function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity } /* */ /** * Runtime helper for checking keyCodes from config. */ function checkKeyCodes ( eventKeyCode, key, builtInAlias ) { var keyCodes = config.keyCodes[key] || builtInAlias; if (Array.isArray(keyCodes)) { return keyCodes.indexOf(eventKeyCode) === -1 } else { return keyCodes !== eventKeyCode } } /* */ /** * Runtime helper for merging v-bind="object" into a VNode's data. */ function bindObjectProps ( data, tag, value, asProp ) { if (value) { if (!isObject(value)) { process.env.NODE_ENV !== 'production' && warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } var hash; for (var key in value) { if (key === 'class' || key === 'style') { hash = data; } else { var type = data.attrs && data.attrs.type; hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); } if (!(key in hash)) { hash[key] = value[key]; } } } } return data } /* */ /** * Runtime helper for rendering static trees. */ function renderStatic ( index, isInFor ) { var tree = this._staticTrees[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree by doing a shallow clone. if (tree && !isInFor) { return Array.isArray(tree) ? cloneVNodes(tree) : cloneVNode(tree) } // otherwise, render a fresh tree. tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy); markStatic(tree, ("__static__" + index), false); return tree } /** * Runtime helper for v-once. * Effectively it means marking the node as static with a unique key. */ function markOnce ( tree, index, key ) { markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true); return tree } function markStatic ( tree, key, isOnce ) { if (Array.isArray(tree)) { for (var i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + "_" + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode (node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } /* */ function initRender (vm) { vm._vnode = null; // the root of the child tree vm._staticTrees = null; var parentVnode = vm.$vnode = vm.$options._parentVnode; // the placeholder node in parent tree var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext); vm.$scopedSlots = emptyObject; // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, normalizationType, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); }; // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }; } function renderMixin (Vue) { Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; Vue.prototype._render = function () { var vm = this; var ref = vm.$options; var render = ref.render; var staticRenderFns = ref.staticRenderFns; var _parentVnode = ref._parentVnode; if (vm._isMounted) { // clone slot nodes on re-renders for (var key in vm.$slots) { vm.$slots[key] = cloneVNodes(vm.$slots[key]); } } vm.$scopedSlots = (_parentVnode && _parentVnode.data.scopedSlots) || emptyObject; if (staticRenderFns && !vm._staticTrees) { vm._staticTrees = []; } // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self var vnode; try { vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { handleError(e, vm, "render function"); // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { vnode = vm.$options.renderError ? vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e) : vm._vnode; } else { vnode = vm._vnode; } } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = createEmptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode }; // internal render helpers. // these are exposed on the instance prototype to reduce generated render // code size. Vue.prototype._o = markOnce; Vue.prototype._n = toNumber; Vue.prototype._s = toString; Vue.prototype._l = renderList; Vue.prototype._t = renderSlot; Vue.prototype._q = looseEqual; Vue.prototype._i = looseIndexOf; Vue.prototype._m = renderStatic; Vue.prototype._f = resolveFilter; Vue.prototype._k = checkKeyCodes; Vue.prototype._b = bindObjectProps; Vue.prototype._v = createTextVNode; Vue.prototype._e = createEmptyVNode; Vue.prototype._u = resolveScopedSlots; } /* */ var uid$1 = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid$1++; var startTag, endTag; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { startTag = "vue-perf-init:" + (vm._uid); endTag = "vue-perf-end:" + (vm._uid); mark(startTag); } // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { initProxy(vm); } else { vm._renderProxy = vm; } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); initRender(vm); callHook(vm, 'beforeCreate'); initInjections(vm); // resolve injections before data/props initState(vm); initProvide(vm); // resolve provide after data/props callHook(vm, 'created'); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { vm._name = formatComponentName(vm, false); mark(endTag); measure(((vm._name) + " init"), startTag, endTag); } if (vm.$options.el) { vm.$mount(vm.$options.el); } }; } function initInternalComponent (vm, options) { var opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. opts.parent = options.parent; opts.propsData = options.propsData; opts._parentVnode = options._parentVnode; opts._parentListeners = options._parentListeners; opts._renderChildren = options._renderChildren; opts._componentTag = options._componentTag; opts._parentElm = options._parentElm; opts._refElm = options._refElm; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions (Ctor) { var options = Ctor.options; if (Ctor.super) { var superOptions = resolveConstructorOptions(Ctor.super); var cachedSuperOptions = Ctor.superOptions; if (superOptions !== cachedSuperOptions) { // super option changed, // need to resolve new options. Ctor.superOptions = superOptions; // check if there are any late-modified/attached options (#4976) var modifiedOptions = resolveModifiedOptions(Ctor); // update base extend options if (modifiedOptions) { extend(Ctor.extendOptions, modifiedOptions); } options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options } function resolveModifiedOptions (Ctor) { var modified; var latest = Ctor.options; var extended = Ctor.extendOptions; var sealed = Ctor.sealedOptions; for (var key in latest) { if (latest[key] !== sealed[key]) { if (!modified) { modified = {}; } modified[key] = dedupe(latest[key], extended[key], sealed[key]); } } return modified } function dedupe (latest, extended, sealed) { // compare latest and sealed to ensure lifecycle hooks won't be duplicated // between merges if (Array.isArray(latest)) { var res = []; sealed = Array.isArray(sealed) ? sealed : [sealed]; extended = Array.isArray(extended) ? extended : [extended]; for (var i = 0; i < latest.length; i++) { // push original options and not sealed options to exclude duplicated options if (extended.indexOf(latest[i]) >= 0 || sealed.indexOf(latest[i]) < 0) { res.push(latest[i]); } } return res } else { return latest } } function Vue$3 (options) { if (process.env.NODE_ENV !== 'production' && !(this instanceof Vue$3) ) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue$3); stateMixin(Vue$3); eventsMixin(Vue$3); lifecycleMixin(Vue$3); renderMixin(Vue$3); /* */ function initUse (Vue) { Vue.use = function (plugin) { /* istanbul ignore if */ if (plugin.installed) { return this } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else if (typeof plugin === 'function') { plugin.apply(null, args); } plugin.installed = true; return this }; } /* */ function initMixin$1 (Vue) { Vue.mixin = function (mixin) { this.options = mergeOptions(this.options, mixin); return this }; } /* */ function initExtend (Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var SuperId = Super.cid; var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } var name = extendOptions.name || Super.options.name; if (process.env.NODE_ENV !== 'production') { if (!/^[a-zA-Z][\w-]*$/.test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characters and the hyphen, ' + 'and must start with a letter.' ); } } var Sub = function VueComponent (options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub['super'] = Super; // For props and computed properties, we define the proxy getters on // the Vue instances at extension time, on the extended prototype. This // avoids Object.defineProperty calls for each instance created. if (Sub.options.props) { initProps$1(Sub); } if (Sub.options.computed) { initComputed$1(Sub); } // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. ASSET_TYPES.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; Sub.sealedOptions = extend({}, Sub.options); // cache constructor cachedCtors[SuperId] = Sub; return Sub }; } function initProps$1 (Comp) { var props = Comp.options.props; for (var key in props) { proxy(Comp.prototype, "_props", key); } } function initComputed$1 (Comp) { var computed = Comp.options.computed; for (var key in computed) { defineComputed(Comp.prototype, key, computed[key]); } } /* */ function initAssetRegisters (Vue) { /** * Create asset registration methods. */ ASSET_TYPES.forEach(function (type) { Vue[type] = function ( id, definition ) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if (type === 'component' && config.isReservedTag(id)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + id ); } } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition }; } this.options[type + 's'][id] = definition; return definition } }; }); } /* */ var patternTypes = [String, RegExp]; function getComponentName (opts) { return opts && (opts.Ctor.options.name || opts.tag) } function matches (pattern, name) { if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else if (isRegExp(pattern)) { return pattern.test(name) } /* istanbul ignore next */ return false } function pruneCache (cache, current, filter) { for (var key in cache) { var cachedNode = cache[key]; if (cachedNode) { var name = getComponentName(cachedNode.componentOptions); if (name && !filter(name)) { if (cachedNode !== current) { pruneCacheEntry(cachedNode); } cache[key] = null; } } } } function pruneCacheEntry (vnode) { if (vnode) { vnode.componentInstance.$destroy(); } } var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes }, created: function created () { this.cache = Object.create(null); }, destroyed: function destroyed () { var this$1 = this; for (var key in this$1.cache) { pruneCacheEntry(this$1.cache[key]); } }, watch: { include: function include (val) { pruneCache(this.cache, this._vnode, function (name) { return matches(val, name); }); }, exclude: function exclude (val) { pruneCache(this.cache, this._vnode, function (name) { return !matches(val, name); }); } }, render: function render () { var vnode = getFirstComponentChild(this.$slots.default); var componentOptions = vnode && vnode.componentOptions; if (componentOptions) { // check pattern var name = getComponentName(componentOptions); if (name && ( (this.include && !matches(this.include, name)) || (this.exclude && matches(this.exclude, name)) )) { return vnode } var key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '') : vnode.key; if (this.cache[key]) { vnode.componentInstance = this.cache[key].componentInstance; } else { this.cache[key] = vnode; } vnode.data.keepAlive = true; } return vnode } }; var builtInComponents = { KeepAlive: KeepAlive }; /* */ function initGlobalAPI (Vue) { // config var configDef = {}; configDef.get = function () { return config; }; if (process.env.NODE_ENV !== 'production') { configDef.set = function () { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); // exposed util methods. // NOTE: these are not considered part of the public API - avoid relying on // them unless you are aware of the risk. Vue.util = { warn: warn, extend: extend, mergeOptions: mergeOptions, defineReactive: defineReactive$$1 }; Vue.set = set; Vue.delete = del; Vue.nextTick = nextTick; Vue.options = Object.create(null); ASSET_TYPES.forEach(function (type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue$3); Object.defineProperty(Vue$3.prototype, '$isServer', { get: isServerRendering }); Object.defineProperty(Vue$3.prototype, '$ssrContext', { get: function get () { /* istanbul ignore next */ return this.$vnode.ssrContext } }); Vue$3.version = '2.3.4'; /* */ // these are reserved for web because they are directly compiled away // during template compilation var isReservedAttr = makeMap('style,class'); // attributes that should be using props for binding var acceptValue = makeMap('input,textarea,option,select'); var mustUseProp = function (tag, type, attr) { return ( (attr === 'value' && acceptValue(tag)) && type !== 'button' || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ) }; var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); var xlinkNS = 'http://www.w3.org/1999/xlink'; var isXlink = function (name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink' }; var getXlinkProp = function (name) { return isXlink(name) ? name.slice(6, name.length) : '' }; var isFalsyAttrValue = function (val) { return val == null || val === false }; /* */ function genClassForVnode (vnode) { var data = vnode.data; var parentNode = vnode; var childNode = vnode; while (isDef(childNode.componentInstance)) { childNode = childNode.componentInstance._vnode; if (childNode.data) { data = mergeClassData(childNode.data, data); } } while (isDef(parentNode = parentNode.parent)) { if (parentNode.data) { data = mergeClassData(data, parentNode.data); } } return genClassFromData(data) } function mergeClassData (child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: isDef(child.class) ? [child.class, parent.class] : parent.class } } function genClassFromData (data) { var dynamicClass = data.class; var staticClass = data.staticClass; if (isDef(staticClass) || isDef(dynamicClass)) { return concat(staticClass, stringifyClass(dynamicClass)) } /* istanbul ignore next */ return '' } function concat (a, b) { return a ? b ? (a + ' ' + b) : a : (b || '') } function stringifyClass (value) { if (isUndef(value)) { return '' } if (typeof value === 'string') { return value } var res = ''; if (Array.isArray(value)) { var stringified; for (var i = 0, l = value.length; i < l; i++) { if (isDef(value[i])) { if (isDef(stringified = stringifyClass(value[i])) && stringified !== '') { res += stringified + ' '; } } } return res.slice(0, -1) } if (isObject(value)) { for (var key in value) { if (value[key]) { res += key + ' '; } } return res.slice(0, -1) } /* istanbul ignore next */ return res } /* */ var namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML' }; var isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,' + 'foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); var isPreTag = function (tag) { return tag === 'pre'; }; var isReservedTag = function (tag) { return isHTMLTag(tag) || isSVG(tag) }; function getTagNamespace (tag) { if (isSVG(tag)) { return 'svg' } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math' } } var unknownElementCache = Object.create(null); function isUnknownElement (tag) { /* istanbul ignore if */ if (!inBrowser) { return true } if (isReservedTag(tag)) { return false } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag] } var el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )) } else { return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())) } } /* */ /** * Query an element selector if it's not an element already. */ function query (el) { if (typeof el === 'string') { var selected = document.querySelector(el); if (!selected) { process.env.NODE_ENV !== 'production' && warn( 'Cannot find element: ' + el ); return document.createElement('div') } return selected } else { return el } } /* */ function createElement$1 (tagName, vnode) { var elm = document.createElement(tagName); if (tagName !== 'select') { return elm } // false or null will remove the attribute but undefined will not if (vnode.data && vnode.data.attrs && vnode.data.attrs.multiple !== undefined) { elm.setAttribute('multiple', 'multiple'); } return elm } function createElementNS (namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName) } function createTextNode (text) { return document.createTextNode(text) } function createComment (text) { return document.createComment(text) } function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild (node, child) { node.removeChild(child); } function appendChild (node, child) { node.appendChild(child); } function parentNode (node) { return node.parentNode } function nextSibling (node) { return node.nextSibling } function tagName (node) { return node.tagName } function setTextContent (node, text) { node.textContent = text; } function setAttribute (node, key, val) { node.setAttribute(key, val); } var nodeOps = Object.freeze({ createElement: createElement$1, createElementNS: createElementNS, createTextNode: createTextNode, createComment: createComment, insertBefore: insertBefore, removeChild: removeChild, appendChild: appendChild, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent, setAttribute: setAttribute }); /* */ var ref = { create: function create (_, vnode) { registerRef(vnode); }, update: function update (oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy (vnode) { registerRef(vnode, true); } }; function registerRef (vnode, isRemoval) { var key = vnode.data.ref; if (!key) { return } var vm = vnode.context; var ref = vnode.componentInstance || vnode.elm; var refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (Array.isArray(refs[key]) && refs[key].indexOf(ref) < 0) { refs[key].push(ref); } else { refs[key] = [ref]; } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * /* * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ var emptyNode = new VNode('', {}, []); var hooks = ['create', 'activate', 'update', 'remove', 'destroy']; function sameVnode (a, b) { return ( a.key === b.key && a.tag === b.tag && a.isComment === b.isComment && isDef(a.data) === isDef(b.data) && sameInputType(a, b) ) } // Some browsers do not support dynamically changing type for <input> // so they need to be treated as different nodes function sameInputType (a, b) { if (a.tag !== 'input') { return true } var i; var typeA = isDef(i = a.data) && isDef(i = i.attrs) && i.type; var typeB = isDef(i = b.data) && isDef(i = i.attrs) && i.type; return typeA === typeB } function createKeyToOldIdx (children, beginIdx, endIdx) { var i, key; var map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map } function createPatchFunction (backend) { var i, j; var cbs = {}; var modules = backend.modules; var nodeOps = backend.nodeOps; for (i = 0; i < hooks.length; ++i) { cbs[hooks[i]] = []; for (j = 0; j < modules.length; ++j) { if (isDef(modules[j][hooks[i]])) { cbs[hooks[i]].push(modules[j][hooks[i]]); } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove$$1 () { if (--remove$$1.listeners === 0) { removeNode(childElm); } } remove$$1.listeners = listeners; return remove$$1 } function removeNode (el) { var parent = nodeOps.parentNode(el); // element may have already been removed due to v-html / v-text if (isDef(parent)) { nodeOps.removeChild(parent, el); } } var inPre = 0; function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) { vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } var data = vnode.data; var children = vnode.children; var tag = vnode.tag; if (isDef(tag)) { if (process.env.NODE_ENV !== 'production') { if (data && data.pre) { inPre++; } if ( !inPre && !vnode.ns && !(config.ignoredElements.length && config.ignoredElements.indexOf(tag) > -1) && config.isUnknownElement(tag) ) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if (process.env.NODE_ENV !== 'production' && data && data.pre) { inPre--; } } else if (isTrue(vnode.isComment)) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i = vnode.data; if (isDef(i)) { var isReactivated = isDef(vnode.componentInstance) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue); if (isTrue(isReactivated)) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true } } } function initComponent (vnode, insertedVnodeQueue) { if (isDef(vnode.data.pendingInsert)) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); vnode.data.pendingInsert = null; } vnode.elm = vnode.componentInstance.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. var innerNode = vnode; while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert (parent, elm, ref) { if (isDef(parent)) { if (isDef(ref)) { if (ref.parentNode === parent) { nodeOps.insertBefore(parent, elm, ref); } } else { nodeOps.appendChild(parent, elm); } } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { for (var i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text)); } } function isPatchable (vnode) { while (vnode.componentInstance) { vnode = vnode.componentInstance._vnode; } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (isDef(i.create)) { i.create(emptyNode, vnode); } if (isDef(i.insert)) { insertedVnodeQueue.push(vnode); } } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { var i; var ancestor = vnode; while (ancestor) { if (isDef(i = ancestor.context) && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } ancestor = ancestor.parent; } // for slot content they should also get the scopeId from the host instance. if (isDef(i = activeInstance) && i !== vnode.context && isDef(i = i.$options._scopeId) ) { nodeOps.setAttribute(vnode.elm, i, ''); } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm); } } function invokeDestroyHook (vnode) { var i, j; var data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes (parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node removeNode(ch.elm); } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (isDef(rm) || isDef(vnode.data)) { var i; var listeners = cbs.remove.length + 1; if (isDef(rm)) { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } else { // directly removing rm = createRmCb(vnode.elm, listeners); } // recursively invoke hooks on child component root node if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeNode(vnode.elm); } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { var oldStartIdx = 0; var newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, elmToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions var canMove = !removeOnly; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null; if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { elmToMove = oldCh[idxInOld]; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !elmToMove) { warn( 'It seems there are duplicate keys that is causing an update error. ' + 'Make sure each v-for item has a unique key.' ); } if (sameVnode(elmToMove, newStartVnode)) { patchVnode(elmToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } } } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) { if (oldVnode === vnode) { return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (isTrue(vnode.isStatic) && isTrue(oldVnode.isStatic) && vnode.key === oldVnode.key && (isTrue(vnode.isCloned) || isTrue(vnode.isOnce)) ) { vnode.elm = oldVnode.elm; vnode.componentInstance = oldVnode.componentInstance; return } var i; var data = vnode.data; if (isDef(data) && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } var elm = vnode.elm = oldVnode.elm; var oldCh = oldVnode.children; var ch = vnode.children; if (isDef(data) && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (isTrue(initial) && isDef(vnode.parent)) { vnode.parent.data.pendingInsert = queue; } else { for (var i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } var bailed = false; // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization var isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key'); // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate (elm, vnode, insertedVnodeQueue) { if (process.env.NODE_ENV !== 'production') { if (!assertNodeMatch(elm, vnode)) { return false } } vnode.elm = elm; var tag = vnode.tag; var data = vnode.data; var children = vnode.children; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.componentInstance)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue); } else { var childrenMatch = true; var childNode = elm.firstChild; for (var i$1 = 0; i$1 < children.length; i$1++) { if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue)) { childrenMatch = false; break } childNode = childNode.nextSibling; } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { if (process.env.NODE_ENV !== 'production' && typeof console !== 'undefined' && !bailed ) { bailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children); } return false } } } if (isDef(data)) { for (var key in data) { if (!isRenderedModule(key)) { invokeCreateHooks(vnode, insertedVnodeQueue); break } } } } else if (elm.data !== vnode.text) { elm.data = vnode.text; } return true } function assertNodeMatch (node, vnode) { if (isDef(vnode.tag)) { return ( vnode.tag.indexOf('vue-component') === 0 || vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ) } else { return node.nodeType === (vnode.isComment ? 8 : 3) } } return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) { if (isUndef(vnode)) { if (isDef(oldVnode)) { invokeDestroyHook(oldVnode); } return } var isInitialPatch = false; var insertedVnodeQueue = []; if (isUndef(oldVnode)) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue, parentElm, refElm); } else { var isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute(SSR_ATTR)) { oldVnode.removeAttribute(SSR_ATTR); hydrating = true; } if (isTrue(hydrating)) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode } else if (process.env.NODE_ENV !== 'production') { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element var oldElm = oldVnode.elm; var parentElm$1 = nodeOps.parentNode(oldElm); createElm( vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a // leaving transition. Only happens when combining transition + // keep-alive + HOCs. (#4590) oldElm._leaveCb ? null : parentElm$1, nodeOps.nextSibling(oldElm) ); if (isDef(vnode.parent)) { // component root element replaced. // update parent placeholder node element, recursively var ancestor = vnode.parent; while (ancestor) { ancestor.elm = vnode.elm; ancestor = ancestor.parent; } if (isPatchable(vnode)) { for (var i = 0; i < cbs.create.length; ++i) { cbs.create[i](emptyNode, vnode.parent); } } } if (isDef(parentElm$1)) { removeVnodes(parentElm$1, [oldVnode], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm } } /* */ var directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode) { updateDirectives(vnode, emptyNode); } }; function updateDirectives (oldVnode, vnode) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode); } } function _update (oldVnode, vnode) { var isCreate = oldVnode === emptyNode; var isDestroy = vnode === emptyNode; var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); var dirsWithInsert = []; var dirsWithPostpatch = []; var key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { var callInsert = function () { for (var i = 0; i < dirsWithInsert.length; i++) { callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode); } }; if (isCreate) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () { for (var i = 0; i < dirsWithPostpatch.length; i++) { callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode); } }); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy); } } } } var emptyModifiers = Object.create(null); function normalizeDirectives$1 ( dirs, vm ) { var res = Object.create(null); if (!dirs) { return res } var i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } return res } function getRawDirName (dir) { return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.'))) } function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) { var fn = dir.def && dir.def[hook]; if (fn) { try { fn(vnode.elm, dir, vnode, oldVnode, isDestroy); } catch (e) { handleError(e, vnode.context, ("directive " + (dir.name) + " " + hook + " hook")); } } } var baseModules = [ ref, directives ]; /* */ function updateAttrs (oldVnode, vnode) { if (isUndef(oldVnode.data.attrs) && isUndef(vnode.data.attrs)) { return } var key, cur, old; var elm = vnode.elm; var oldAttrs = oldVnode.data.attrs || {}; var attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(attrs.__ob__)) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } // #4391: in IE9, setting type can reset value for input[type=radio] /* istanbul ignore if */ if (isIE9 && attrs.value !== oldAttrs.value) { setAttr(elm, 'value', attrs.value); } for (key in oldAttrs) { if (isUndef(attrs[key])) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr (el, key, value) { if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, key); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true'); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, value); } } } var attrs = { create: updateAttrs, update: updateAttrs }; /* */ function updateClass (oldVnode, vnode) { var el = vnode.elm; var data = vnode.data; var oldData = oldVnode.data; if ( isUndef(data.staticClass) && isUndef(data.class) && ( isUndef(oldData) || ( isUndef(oldData.staticClass) && isUndef(oldData.class) ) ) ) { return } var cls = genClassForVnode(vnode); // handle transition classes var transitionClass = el._transitionClasses; if (isDef(transitionClass)) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } var klass = { create: updateClass, update: updateClass }; /* */ var validDivisionCharRE = /[\w).+\-_$\]]/; function parseFilters (exp) { var inSingle = false; var inDouble = false; var inTemplateString = false; var inRegex = false; var curly = 0; var square = 0; var paren = 0; var lastFilterIndex = 0; var c, prev, i, expression, filters; for (i = 0; i < exp.length; i++) { prev = c; c = exp.charCodeAt(i); if (inSingle) { if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( c === 0x7C && // pipe exp.charCodeAt(i + 1) !== 0x7C && exp.charCodeAt(i - 1) !== 0x7C && !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1; expression = exp.slice(0, i).trim(); } else { pushFilter(); } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x60: inTemplateString = true; break // ` case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } if (c === 0x2f) { // / var j = i - 1; var p = (void 0); // find first non-whitespace prev char for (; j >= 0; j--) { p = exp.charAt(j); if (p !== ' ') { break } } if (!p || !validDivisionCharRE.test(p)) { inRegex = true; } } } } if (expression === undefined) { expression = exp.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } function pushFilter () { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i]); } } return expression } function wrapFilter (exp, filter) { var i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter return ("_f(\"" + filter + "\")(" + exp + ")") } else { var name = filter.slice(0, i); var args = filter.slice(i + 1); return ("_f(\"" + name + "\")(" + exp + "," + args) } } /* */ function baseWarn (msg) { console.error(("[Vue compiler]: " + msg)); } function pluckModuleFunction ( modules, key ) { return modules ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; }) : [] } function addProp (el, name, value) { (el.props || (el.props = [])).push({ name: name, value: value }); } function addAttr (el, name, value) { (el.attrs || (el.attrs = [])).push({ name: name, value: value }); } function addDirective ( el, name, rawName, value, arg, modifiers ) { (el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers }); } function addHandler ( el, name, value, modifiers, important, warn ) { // warn prevent and passive modifier /* istanbul ignore if */ if ( process.env.NODE_ENV !== 'production' && warn && modifiers && modifiers.prevent && modifiers.passive ) { warn( 'passive and prevent can\'t be used together. ' + 'Passive handler can\'t prevent default event.' ); } // check capture modifier if (modifiers && modifiers.capture) { delete modifiers.capture; name = '!' + name; // mark the event as captured } if (modifiers && modifiers.once) { delete modifiers.once; name = '~' + name; // mark the event as once } /* istanbul ignore if */ if (modifiers && modifiers.passive) { delete modifiers.passive; name = '&' + name; // mark the event as passive } var events; if (modifiers && modifiers.native) { delete modifiers.native; events = el.nativeEvents || (el.nativeEvents = {}); } else { events = el.events || (el.events = {}); } var newHandler = { value: value, modifiers: modifiers }; var handlers = events[name]; /* istanbul ignore if */ if (Array.isArray(handlers)) { important ? handlers.unshift(newHandler) : handlers.push(newHandler); } else if (handlers) { events[name] = important ? [newHandler, handlers] : [handlers, newHandler]; } else { events[name] = newHandler; } } function getBindingAttr ( el, name, getStatic ) { var dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { return parseFilters(dynamicValue) } else if (getStatic !== false) { var staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { return JSON.stringify(staticValue) } } } function getAndRemoveAttr (el, name) { var val; if ((val = el.attrsMap[name]) != null) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); break } } } return val } /* */ /** * Cross-platform code generation for component v-model */ function genComponentModel ( el, value, modifiers ) { var ref = modifiers || {}; var number = ref.number; var trim = ref.trim; var baseValueExpression = '$$v'; var valueExpression = baseValueExpression; if (trim) { valueExpression = "(typeof " + baseValueExpression + " === 'string'" + "? " + baseValueExpression + ".trim()" + ": " + baseValueExpression + ")"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var assignment = genAssignmentCode(value, valueExpression); el.model = { value: ("(" + value + ")"), expression: ("\"" + value + "\""), callback: ("function (" + baseValueExpression + ") {" + assignment + "}") }; } /** * Cross-platform codegen helper for generating v-model value assignment code. */ function genAssignmentCode ( value, assignment ) { var modelRs = parseModel(value); if (modelRs.idx === null) { return (value + "=" + assignment) } else { return "var $$exp = " + (modelRs.exp) + ", $$idx = " + (modelRs.idx) + ";" + "if (!Array.isArray($$exp)){" + value + "=" + assignment + "}" + "else{$$exp.splice($$idx, 1, " + assignment + ")}" } } /** * parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val) * * for loop possible cases: * * - test * - test[idx] * - test[test1[idx]] * - test["a"][idx] * - xxx.test[a[a].test1[idx]] * - test.xxx.a["asa"][test1[idx]] * */ var len; var str; var chr; var index$1; var expressionPos; var expressionEndPos; function parseModel (val) { str = val; len = str.length; index$1 = expressionPos = expressionEndPos = 0; if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { return { exp: val, idx: null } } while (!eof()) { chr = next(); /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); } else if (chr === 0x5B) { parseBracket(chr); } } return { exp: val.substring(0, expressionPos), idx: val.substring(expressionPos + 1, expressionEndPos) } } function next () { return str.charCodeAt(++index$1) } function eof () { return index$1 >= len } function isStringStart (chr) { return chr === 0x22 || chr === 0x27 } function parseBracket (chr) { var inBracket = 1; expressionPos = index$1; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); continue } if (chr === 0x5B) { inBracket++; } if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index$1; break } } } function parseString (chr) { var stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { break } } } /* */ var warn$1; // in some cases, the event used has to be determined at runtime // so we used some reserved tokens during compile. var RANGE_TOKEN = '__r'; var CHECKBOX_RADIO_TOKEN = '__c'; function model ( el, dir, _warn ) { warn$1 = _warn; var value = dir.value; var modifiers = dir.modifiers; var tag = el.tag; var type = el.attrsMap.type; if (process.env.NODE_ENV !== 'production') { var dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type']; if (tag === 'input' && dynamicType) { warn$1( "<input :type=\"" + dynamicType + "\" v-model=\"" + value + "\">:\n" + "v-model does not support dynamic input types. Use v-if branches instead." ); } // inputs with type="file" are read only and setting the input's // value will throw an error. if (tag === 'input' && type === 'file') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" + "File inputs are read only. Use a v-on:change listener instead." ); } } if (tag === 'select') { genSelect(el, value, modifiers); } else if (tag === 'input' && type === 'checkbox') { genCheckboxModel(el, value, modifiers); } else if (tag === 'input' && type === 'radio') { genRadioModel(el, value, modifiers); } else if (tag === 'input' || tag === 'textarea') { genDefaultModel(el, value, modifiers); } else if (!config.isReservedTag(tag)) { genComponentModel(el, value, modifiers); // component v-model doesn't need extra runtime return false } else if (process.env.NODE_ENV !== 'production') { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "v-model is not supported on this element type. " + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.' ); } // ensure runtime directive metadata return true } function genCheckboxModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; var trueValueBinding = getBindingAttr(el, 'true-value') || 'true'; var falseValueBinding = getBindingAttr(el, 'false-value') || 'false'; addProp(el, 'checked', "Array.isArray(" + value + ")" + "?_i(" + value + "," + valueBinding + ")>-1" + ( trueValueBinding === 'true' ? (":(" + value + ")") : (":_q(" + value + "," + trueValueBinding + ")") ) ); addHandler(el, CHECKBOX_RADIO_TOKEN, "var $$a=" + value + "," + '$$el=$event.target,' + "$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" + 'if(Array.isArray($$a)){' + "var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," + '$$i=_i($$a,$$v);' + "if($$c){$$i<0&&(" + value + "=$$a.concat($$v))}" + "else{$$i>-1&&(" + value + "=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}" + "}else{" + (genAssignmentCode(value, '$$c')) + "}", null, true ); } function genRadioModel ( el, value, modifiers ) { var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding; addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")")); addHandler(el, CHECKBOX_RADIO_TOKEN, genAssignmentCode(value, valueBinding), null, true); } function genSelect ( el, value, modifiers ) { var number = modifiers && modifiers.number; var selectedVal = "Array.prototype.filter" + ".call($event.target.options,function(o){return o.selected})" + ".map(function(o){var val = \"_value\" in o ? o._value : o.value;" + "return " + (number ? '_n(val)' : 'val') + "})"; var assignment = '$event.target.multiple ? $$selectedVal : $$selectedVal[0]'; var code = "var $$selectedVal = " + selectedVal + ";"; code = code + " " + (genAssignmentCode(value, assignment)); addHandler(el, 'change', code, null, true); } function genDefaultModel ( el, value, modifiers ) { var type = el.attrsMap.type; var ref = modifiers || {}; var lazy = ref.lazy; var number = ref.number; var trim = ref.trim; var needCompositionGuard = !lazy && type !== 'range'; var event = lazy ? 'change' : type === 'range' ? RANGE_TOKEN : 'input'; var valueExpression = '$event.target.value'; if (trim) { valueExpression = "$event.target.value.trim()"; } if (number) { valueExpression = "_n(" + valueExpression + ")"; } var code = genAssignmentCode(value, valueExpression); if (needCompositionGuard) { code = "if($event.target.composing)return;" + code; } addProp(el, 'value', ("(" + value + ")")); addHandler(el, event, code, null, true); if (trim || number || type === 'number') { addHandler(el, 'blur', '$forceUpdate()'); } } /* */ // normalize v-model event tokens that can only be determined at runtime. // it's important to place the event as the first in the array because // the whole point is ensuring the v-model callback gets called before // user-attached handlers. function normalizeEvents (on) { var event; /* istanbul ignore if */ if (isDef(on[RANGE_TOKEN])) { // IE input[type=range] only supports `change` event event = isIE ? 'change' : 'input'; on[event] = [].concat(on[RANGE_TOKEN], on[event] || []); delete on[RANGE_TOKEN]; } if (isDef(on[CHECKBOX_RADIO_TOKEN])) { // Chrome fires microtasks in between click/change, leads to #4521 event = isChrome ? 'click' : 'change'; on[event] = [].concat(on[CHECKBOX_RADIO_TOKEN], on[event] || []); delete on[CHECKBOX_RADIO_TOKEN]; } } var target$1; function add$1 ( event, handler, once$$1, capture, passive ) { if (once$$1) { var oldHandler = handler; var _target = target$1; // save current target element in closure handler = function (ev) { var res = arguments.length === 1 ? oldHandler(ev) : oldHandler.apply(null, arguments); if (res !== null) { remove$2(event, handler, capture, _target); } }; } target$1.addEventListener( event, handler, supportsPassive ? { capture: capture, passive: passive } : capture ); } function remove$2 ( event, handler, capture, _target ) { (_target || target$1).removeEventListener(event, handler, capture); } function updateDOMListeners (oldVnode, vnode) { if (isUndef(oldVnode.data.on) && isUndef(vnode.data.on)) { return } var on = vnode.data.on || {}; var oldOn = oldVnode.data.on || {}; target$1 = vnode.elm; normalizeEvents(on); updateListeners(on, oldOn, add$1, remove$2, vnode.context); } var events = { create: updateDOMListeners, update: updateDOMListeners }; /* */ function updateDOMProps (oldVnode, vnode) { if (isUndef(oldVnode.data.domProps) && isUndef(vnode.data.domProps)) { return } var key, cur; var elm = vnode.elm; var oldProps = oldVnode.data.domProps || {}; var props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (isDef(props.__ob__)) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (isUndef(props[key])) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue } } if (key === 'value') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same var strCur = isUndef(cur) ? '' : String(cur); if (shouldUpdateValue(elm, vnode, strCur)) { elm.value = strCur; } } else { elm[key] = cur; } } } // check platforms/web/util/attrs.js acceptValue function shouldUpdateValue ( elm, vnode, checkVal ) { return (!elm.composing && ( vnode.tag === 'option' || isDirty(elm, checkVal) || isInputChanged(elm, checkVal) )) } function isDirty (elm, checkVal) { // return true when textbox (.number and .trim) loses focus and its value is not equal to the updated value return document.activeElement !== elm && elm.value !== checkVal } function isInputChanged (elm, newVal) { var value = elm.value; var modifiers = elm._vModifiers; // injected by v-model runtime if ((isDef(modifiers) && modifiers.number) || elm.type === 'number') { return toNumber(value) !== toNumber(newVal) } if (isDef(modifiers) && modifiers.trim) { return value.trim() !== newVal.trim() } return value !== newVal } var domProps = { create: updateDOMProps, update: updateDOMProps }; /* */ var parseStyleText = cached(function (cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res }); // merge static and dynamic style data on the same vnode function normalizeStyleData (data) { var style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style } // normalize possible array / string values into Object function normalizeStyleBinding (bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle) } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle) } return bindingStyle } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle (vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if (childNode.data && (styleData = normalizeStyleData(childNode.data))) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res } /* */ var cssVarRE = /^--/; var importantRE = /\s*!important$/; var setProp = function (el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(name, val.replace(importantRE, ''), 'important'); } else { var normalizedName = normalize(name); if (Array.isArray(val)) { // Support values array created by autoprefixer, e.g. // {display: ["-webkit-box", "-ms-flexbox", "flex"]} // Set them one by one, and the browser will only set those it can recognize for (var i = 0, len = val.length; i < len; i++) { el.style[normalizedName] = val[i]; } } else { el.style[normalizedName] = val; } } }; var prefixes = ['Webkit', 'Moz', 'ms']; var testEl; var normalize = cached(function (prop) { testEl = testEl || document.createElement('div'); prop = camelize(prop); if (prop !== 'filter' && (prop in testEl.style)) { return prop } var upper = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = 0; i < prefixes.length; i++) { var prefixed = prefixes[i] + upper; if (prefixed in testEl.style) { return prefixed } } }); function updateStyle (oldVnode, vnode) { var data = vnode.data; var oldData = oldVnode.data; if (isUndef(data.staticStyle) && isUndef(data.style) && isUndef(oldData.staticStyle) && isUndef(oldData.style) ) { return } var cur, name; var el = vnode.elm; var oldStaticStyle = oldData.staticStyle; var oldStyleBinding = oldData.normalizedStyle || oldData.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData var oldStyle = oldStaticStyle || oldStyleBinding; var style = normalizeStyleBinding(vnode.data.style) || {}; // store normalized style under a different key for next diff // make sure to clone it if it's reactive, since the user likley wants // to mutate it. vnode.data.normalizedStyle = isDef(style.__ob__) ? extend({}, style) : style; var newStyle = getStyle(vnode, true); for (name in oldStyle) { if (isUndef(newStyle[name])) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } var style = { create: updateStyle, update: updateStyle }; /* */ /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !(cls = cls.trim())) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } } else { var cur = " " + (el.getAttribute('class') || '') + " "; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } el.setAttribute('class', cur.trim()); } } /* */ function resolveTransition (def$$1) { if (!def$$1) { return } /* istanbul ignore else */ if (typeof def$$1 === 'object') { var res = {}; if (def$$1.css !== false) { extend(res, autoCssTransition(def$$1.name || 'v')); } extend(res, def$$1); return res } else if (typeof def$$1 === 'string') { return autoCssTransition(def$$1) } } var autoCssTransition = cached(function (name) { return { enterClass: (name + "-enter"), enterToClass: (name + "-enter-to"), enterActiveClass: (name + "-enter-active"), leaveClass: (name + "-leave"), leaveToClass: (name + "-leave-to"), leaveActiveClass: (name + "-leave-active") } }); var hasTransition = inBrowser && !isIE9; var TRANSITION = 'transition'; var ANIMATION = 'animation'; // Transition property/event sniffing var transitionProp = 'transition'; var transitionEndEvent = 'transitionend'; var animationProp = 'animation'; var animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined ) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined ) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } // binding to window is necessary to make hot reload work in IE in strict mode var raf = inBrowser && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout; function nextFrame (fn) { raf(function () { raf(fn); }); } function addTransitionClass (el, cls) { (el._transitionClasses || (el._transitionClasses = [])).push(cls); addClass(el, cls); } function removeTransitionClass (el, cls) { if (el._transitionClasses) { remove(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds ( el, expectedType, cb ) { var ref = getTransitionInfo(el, expectedType); var type = ref.type; var timeout = ref.timeout; var propCount = ref.propCount; if (!type) { return cb() } var event = type === TRANSITION ? transitionEndEvent : animationEndEvent; var ended = 0; var end = function () { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function (e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function () { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } var transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); var transitionDelays = styles[transitionProp + 'Delay'].split(', '); var transitionDurations = styles[transitionProp + 'Duration'].split(', '); var transitionTimeout = getTimeout(transitionDelays, transitionDurations); var animationDelays = styles[animationProp + 'Delay'].split(', '); var animationDurations = styles[animationProp + 'Duration'].split(', '); var animationTimeout = getTimeout(animationDelays, animationDurations); var type; var timeout = 0; var propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type: type, timeout: timeout, propCount: propCount, hasTransform: hasTransform } } function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function (d, i) { return toMs(d) + toMs(delays[i]) })) } function toMs (s) { return Number(s.slice(0, -1)) * 1000 } /* */ function enter (vnode, toggleDisplay) { var el = vnode.elm; // call leave callback now if (isDef(el._leaveCb)) { el._leaveCb.cancelled = true; el._leaveCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return } /* istanbul ignore if */ if (isDef(el._enterCb) || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var enterClass = data.enterClass; var enterToClass = data.enterToClass; var enterActiveClass = data.enterActiveClass; var appearClass = data.appearClass; var appearToClass = data.appearToClass; var appearActiveClass = data.appearActiveClass; var beforeEnter = data.beforeEnter; var enter = data.enter; var afterEnter = data.afterEnter; var enterCancelled = data.enterCancelled; var beforeAppear = data.beforeAppear; var appear = data.appear; var afterAppear = data.afterAppear; var appearCancelled = data.appearCancelled; var duration = data.duration; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. var context = activeInstance; var transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { transitionNode = transitionNode.parent; context = transitionNode.context; } var isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return } var startClass = isAppear && appearClass ? appearClass : enterClass; var activeClass = isAppear && appearActiveClass ? appearActiveClass : enterActiveClass; var toClass = isAppear && appearToClass ? appearToClass : enterToClass; var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; var explicitEnterDuration = toNumber( isObject(duration) ? duration.enter : duration ); if (process.env.NODE_ENV !== 'production' && explicitEnterDuration != null) { checkDuration(explicitEnterDuration, 'enter', vnode); } var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(enterHook); var cb = el._enterCb = once(function () { if (expectsCSS) { removeTransitionClass(el, toClass); removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () { var parent = el.parentNode; var pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb ) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function () { addTransitionClass(el, toClass); removeTransitionClass(el, startClass); if (!cb.cancelled && !userWantsControl) { if (isValidDuration(explicitEnterDuration)) { setTimeout(cb, explicitEnterDuration); } else { whenTransitionEnds(el, type, cb); } } }); } if (vnode.data.show) { toggleDisplay && toggleDisplay(); enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave (vnode, rm) { var el = vnode.elm; // call enter callback now if (isDef(el._enterCb)) { el._enterCb.cancelled = true; el._enterCb(); } var data = resolveTransition(vnode.data.transition); if (isUndef(data)) { return rm() } /* istanbul ignore if */ if (isDef(el._leaveCb) || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var leaveClass = data.leaveClass; var leaveToClass = data.leaveToClass; var leaveActiveClass = data.leaveActiveClass; var beforeLeave = data.beforeLeave; var leave = data.leave; var afterLeave = data.afterLeave; var leaveCancelled = data.leaveCancelled; var delayLeave = data.delayLeave; var duration = data.duration; var expectsCSS = css !== false && !isIE9; var userWantsControl = getHookArgumentsLength(leave); var explicitLeaveDuration = toNumber( isObject(duration) ? duration.leave : duration ); if (process.env.NODE_ENV !== 'production' && isDef(explicitLeaveDuration)) { checkDuration(explicitLeaveDuration, 'leave', vnode); } var cb = el._leaveCb = once(function () { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave () { // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show) { (el.parentNode._pending || (el.parentNode._pending = {}))[(vnode.key)] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function () { addTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveClass); if (!cb.cancelled && !userWantsControl) { if (isValidDuration(explicitLeaveDuration)) { setTimeout(cb, explicitLeaveDuration); } else { whenTransitionEnds(el, type, cb); } } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } // only used in dev mode function checkDuration (val, name, vnode) { if (typeof val !== 'number') { warn( "<transition> explicit " + name + " duration is not a valid number - " + "got " + (JSON.stringify(val)) + ".", vnode.context ); } else if (isNaN(val)) { warn( "<transition> explicit " + name + " duration is NaN - " + 'the duration expression might be incorrect.', vnode.context ); } } function isValidDuration (val) { return typeof val === 'number' && !isNaN(val) } /** * Normalize a transition hook's argument length. The hook may be: * - a merged hook (invoker) with the original in .fns * - a wrapped component method (check ._length) * - a plain function (.length) */ function getHookArgumentsLength (fn) { if (isUndef(fn)) { return false } var invokerFns = fn.fns; if (isDef(invokerFns)) { // invoker return getHookArgumentsLength( Array.isArray(invokerFns) ? invokerFns[0] : invokerFns ) } else { return (fn._length || fn.length) > 1 } } function _enter (_, vnode) { if (vnode.data.show !== true) { enter(vnode); } } var transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove$$1 (vnode, rm) { /* istanbul ignore else */ if (vnode.data.show !== true) { leave(vnode, rm); } else { rm(); } } } : {}; var platformModules = [ attrs, klass, events, domProps, style, transition ]; /* */ // the directive module should be applied last, after all // built-in modules have been applied. var modules = platformModules.concat(baseModules); var patch = createPatchFunction({ nodeOps: nodeOps, modules: modules }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function () { var el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } var model$1 = { inserted: function inserted (el, binding, vnode) { if (vnode.tag === 'select') { var cb = function () { setSelected(el, binding, vnode.context); }; cb(); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(cb, 0); } } else if (vnode.tag === 'textarea' || el.type === 'text' || el.type === 'password') { el._vModifiers = binding.modifiers; if (!binding.modifiers.lazy) { // Safari < 10.2 & UIWebView doesn't fire compositionend when // switching focus before confirming composition choice // this also fixes the issue where some browsers e.g. iOS Chrome // fires "change" instead of "input" on autocomplete. el.addEventListener('change', onCompositionEnd); if (!isAndroid) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); } /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } } }, componentUpdated: function componentUpdated (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. var needReset = el.multiple ? binding.value.some(function (v) { return hasNoMatchingOption(v, el.options); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, el.options); if (needReset) { trigger(el, 'change'); } } } }; function setSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { process.env.NODE_ENV !== 'production' && warn( "<select multiple v-model=\"" + (binding.expression) + "\"> " + "expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return } var selected, option; for (var i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption (value, options) { for (var i = 0, l = options.length; i < l; i++) { if (looseEqual(getValue(options[i]), value)) { return false } } return true } function getValue (option) { return '_value' in option ? option._value : option.value } function onCompositionStart (e) { e.target.composing = true; } function onCompositionEnd (e) { // prevent triggering an input event for no reason if (!e.target.composing) { return } e.target.composing = false; trigger(e.target, 'input'); } function trigger (el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode (vnode) { return vnode.componentInstance && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.componentInstance._vnode) : vnode } var show = { bind: function bind (el, ref, vnode) { var value = ref.value; vnode = locateNode(vnode); var transition = vnode.data && vnode.data.transition; var originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display; if (value && transition && !isIE9) { vnode.data.show = true; enter(vnode, function () { el.style.display = originalDisplay; }); } else { el.style.display = value ? originalDisplay : 'none'; } }, update: function update (el, ref, vnode) { var value = ref.value; var oldValue = ref.oldValue; /* istanbul ignore if */ if (value === oldValue) { return } vnode = locateNode(vnode); var transition = vnode.data && vnode.data.transition; if (transition && !isIE9) { vnode.data.show = true; if (value) { enter(vnode, function () { el.style.display = el.__vOriginalDisplay; }); } else { leave(vnode, function () { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } }, unbind: function unbind ( el, binding, vnode, oldVnode, isDestroy ) { if (!isDestroy) { el.style.display = el.__vOriginalDisplay; } } }; var platformDirectives = { model: model$1, show: show }; /* */ // Provides transition support for a single element/component. // supports transition mode (out-in / in-out) var transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterToClass: String, leaveToClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String, appearToClass: String, duration: [Number, String, Object] }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild (vnode) { var compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)) } else { return vnode } } function extractTransitionData (comp) { var data = {}; var options = comp.$options; // props for (var key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods var listeners = options._parentListeners; for (var key$1 in listeners) { data[camelize(key$1)] = listeners[key$1]; } return data } function placeholder (h, rawChild) { if (/\d-keep-alive$/.test(rawChild.tag)) { return h('keep-alive', { props: rawChild.componentOptions.propsData }) } } function hasParentTransition (vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true } } } function isSameChild (child, oldChild) { return oldChild.key === child.key && oldChild.tag === child.tag } var Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render (h) { var this$1 = this; var children = this.$slots.default; if (!children) { return } // filter out text nodes (possible whitespaces) children = children.filter(function (c) { return c.tag; }); /* istanbul ignore if */ if (!children.length) { return } // warn multiple elements if (process.env.NODE_ENV !== 'production' && children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } var mode = this.mode; // warn invalid mode if (process.env.NODE_ENV !== 'production' && mode && mode !== 'in-out' && mode !== 'out-in' ) { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } var rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive var child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild } if (this._leaving) { return placeholder(h, rawChild) } // ensure a key that is unique to the vnode type and to this transition // component instance. This key will be used to remove pending leaving nodes // during entering. var id = "__transition-" + (this._uid) + "-"; child.key = child.key == null ? id + child.tag : isPrimitive(child.key) ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key) : child.key; var data = (child.data || (child.data = {})).transition = extractTransitionData(this); var oldRawChild = this._vnode; var oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) { child.data.show = true; } if (oldChild && oldChild.data && !isSameChild(child, oldChild)) { // replace old child transition data with fresh one // important for dynamic transitions! var oldData = oldChild && (oldChild.data.transition = extend({}, data)); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function () { this$1._leaving = false; this$1.$forceUpdate(); }); return placeholder(h, rawChild) } else if (mode === 'in-out') { var delayedLeave; var performLeave = function () { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave); mergeVNodeHook(data, 'enterCancelled', performLeave); mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; }); } } return rawChild } }; /* */ // Provides transition support for list items. // supports move transitions using the FLIP technique. // Because the vdom's children update algorithm is "unstable" - i.e. // it doesn't guarantee the relative positioning of removed elements, // we force transition-group to update its children into two passes: // in the first pass, we remove all nodes that need to be removed, // triggering their leaving transition; in the second pass, we insert/move // into the final desired state. This way in the second pass removed // nodes will remain where they should be. var props = extend({ tag: String, moveClass: String }, transitionProps); delete props.mode; var TransitionGroup = { props: props, render: function render (h) { var tag = this.tag || this.$vnode.data.tag || 'span'; var map = Object.create(null); var prevChildren = this.prevChildren = this.children; var rawChildren = this.$slots.default || []; var children = this.children = []; var transitionData = extractTransitionData(this); for (var i = 0; i < rawChildren.length; i++) { var c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData; } else if (process.env.NODE_ENV !== 'production') { var opts = c.componentOptions; var name = opts ? (opts.Ctor.options.name || opts.tag || '') : c.tag; warn(("<transition-group> children must be keyed: <" + name + ">")); } } } if (prevChildren) { var kept = []; var removed = []; for (var i$1 = 0; i$1 < prevChildren.length; i$1++) { var c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children) }, beforeUpdate: function beforeUpdate () { // force removing pass this.__patch__( this._vnode, this.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this._vnode = this.kept; }, updated: function updated () { var children = this.prevChildren; var moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position var body = document.body; var f = body.offsetHeight; // eslint-disable-line children.forEach(function (c) { if (c.data.moved) { var el = c.elm; var s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) { if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove (el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false } if (this._hasMove != null) { return this._hasMove } // Detect whether an element with the move class applied has // CSS transitions. Since the element may be inside an entering // transition at this very moment, we make a clone of it and remove // all other transition classes applied to ensure only the move class // is applied. var clone = el.cloneNode(); if (el._transitionClasses) { el._transitionClasses.forEach(function (cls) { removeClass(clone, cls); }); } addClass(clone, moveClass); clone.style.display = 'none'; this.$el.appendChild(clone); var info = getTransitionInfo(clone); this.$el.removeChild(clone); return (this._hasMove = info.hasTransform) } } }; function callPendingCbs (c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition (c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation (c) { var oldPos = c.data.pos; var newPos = c.data.newPos; var dx = oldPos.left - newPos.left; var dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; var s = c.elm.style; s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"; s.transitionDuration = '0s'; } } var platformComponents = { Transition: Transition, TransitionGroup: TransitionGroup }; /* */ // install platform specific utils Vue$3.config.mustUseProp = mustUseProp; Vue$3.config.isReservedTag = isReservedTag; Vue$3.config.isReservedAttr = isReservedAttr; Vue$3.config.getTagNamespace = getTagNamespace; Vue$3.config.isUnknownElement = isUnknownElement; // install platform runtime directives & components extend(Vue$3.options.directives, platformDirectives); extend(Vue$3.options.components, platformComponents); // install platform patch function Vue$3.prototype.__patch__ = inBrowser ? patch : noop; // public mount method Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return mountComponent(this, el, hydrating) }; // devtools global hook /* istanbul ignore next */ setTimeout(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue$3); } else if (process.env.NODE_ENV !== 'production' && isChrome) { console[console.info ? 'info' : 'log']( 'Download the Vue Devtools extension for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } if (process.env.NODE_ENV !== 'production' && config.productionTip !== false && inBrowser && typeof console !== 'undefined' ) { console[console.info ? 'info' : 'log']( "You are running Vue in development mode.\n" + "Make sure to turn on production mode when deploying for production.\n" + "See more tips at https://vuejs.org/guide/deployment.html" ); } }, 0); /* */ // check whether current browser encodes a char inside attribute values function shouldDecode (content, encoded) { var div = document.createElement('div'); div.innerHTML = "<div a=\"" + content + "\">"; return div.innerHTML.indexOf(encoded) > 0 } // #3663 // IE encodes newlines inside attribute values while other browsers don't var shouldDecodeNewlines = inBrowser ? shouldDecode('\n', '&#10;') : false; /* */ var isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr' ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source' ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track' ); /* */ var decoder; function decode (html) { decoder = decoder || document.createElement('div'); decoder.innerHTML = html; return decoder.textContent } /** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By John Resig (ejohn.org) * Modified by Juriy "kangax" Zaytsev * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js */ // Regular Expressions for parsing tags and attributes var singleAttrIdentifier = /([^\s"'<>/=]+)/; var singleAttrAssign = /(?:=)/; var singleAttrValues = [ // attr value double quotes /"([^"]*)"+/.source, // attr value, single quotes /'([^']*)'+/.source, // attr value, no quotes /([^\s"'=<>`]+)/.source ]; var attribute = new RegExp( '^\\s*' + singleAttrIdentifier.source + '(?:\\s*(' + singleAttrAssign.source + ')' + '\\s*(?:' + singleAttrValues.join('|') + '))?' ); // could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName // but for Vue templates we can enforce a simple charset var ncname = '[a-zA-Z_][\\w\\-\\.]*'; var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')'; var startTagOpen = new RegExp('^<' + qnameCapture); var startTagClose = /^\s*(\/?)>/; var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>'); var doctype = /^<!DOCTYPE [^>]+>/i; var comment = /^<!--/; var conditionalComment = /^<!\[/; var IS_REGEX_CAPTURING_BROKEN = false; 'x'.replace(/x(.)?/g, function (m, g) { IS_REGEX_CAPTURING_BROKEN = g === ''; }); // Special Elements (can contain anything) var isPlainTextElement = makeMap('script,style,textarea', true); var reCache = {}; var decodingMap = { '&lt;': '<', '&gt;': '>', '&quot;': '"', '&amp;': '&', '&#10;': '\n' }; var encodedAttr = /&(?:lt|gt|quot|amp);/g; var encodedAttrWithNewLines = /&(?:lt|gt|quot|amp|#10);/g; function decodeAttr (value, shouldDecodeNewlines) { var re = shouldDecodeNewlines ? encodedAttrWithNewLines : encodedAttr; return value.replace(re, function (match) { return decodingMap[match]; }) } function parseHTML (html, options) { var stack = []; var expectHTML = options.expectHTML; var isUnaryTag$$1 = options.isUnaryTag || no; var canBeLeftOpenTag$$1 = options.canBeLeftOpenTag || no; var index = 0; var last, lastTag; while (html) { last = html; // Make sure we're not in a plaintext content element like script/style if (!lastTag || !isPlainTextElement(lastTag)) { var textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { advance(commentEnd + 3); continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue } } // Doctype: var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue } // End tag: var endTagMatch = html.match(endTag); if (endTagMatch) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); continue } } var text = (void 0), rest$1 = (void 0), next = (void 0); if (textEnd >= 0) { rest$1 = html.slice(textEnd); while ( !endTag.test(rest$1) && !startTagOpen.test(rest$1) && !comment.test(rest$1) && !conditionalComment.test(rest$1) ) { // < in plain text, be forgiving and treat it as text next = rest$1.indexOf('<', 1); if (next < 0) { break } textEnd += next; rest$1 = html.slice(textEnd); } text = html.substring(0, textEnd); advance(textEnd); } if (textEnd < 0) { text = html; html = ''; } if (options.chars && text) { options.chars(text); } } else { var stackedTag = lastTag.toLowerCase(); var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); var endTagLength = 0; var rest = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (!isPlainTextElement(stackedTag) && stackedTag !== 'noscript') { text = text .replace(/<!--([\s\S]*?)-->/g, '$1') .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (options.chars) { options.chars(text); } return '' }); index += html.length - rest.length; html = rest; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last) { options.chars && options.chars(html); if (process.env.NODE_ENV !== 'production' && !stack.length && options.warn) { options.warn(("Mal-formatted tag at end of template: \"" + html + "\"")); } break } } // Clean up any remaining tags parseEndTag(); function advance (n) { index += n; html = html.substring(n); } function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); var end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) { advance(attr[0].length); match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match } } } function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag$$1(tagName) && lastTag === tagName) { parseEndTag(tagName); } } var unary = isUnaryTag$$1(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); for (var i = 0; i < l; i++) { var args = match.attrs[i]; // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { if (args[3] === '') { delete args[3]; } if (args[4] === '') { delete args[4]; } if (args[5] === '') { delete args[5]; } } var value = args[3] || args[4] || args[5] || ''; attrs[i] = { name: args[1], value: decodeAttr( value, options.shouldDecodeNewlines ) }; } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs }); lastTag = tagName; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag (tagName, start, end) { var pos, lowerCasedTagName; if (start == null) { start = index; } if (end == null) { end = index; } if (tagName) { lowerCasedTagName = tagName.toLowerCase(); } // Find the closest opened tag of the same type if (tagName) { for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { if (process.env.NODE_ENV !== 'production' && (i > pos || !tagName) && options.warn ) { options.warn( ("tag <" + (stack[i].tag) + "> has no matching end tag.") ); } if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g; var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var buildRegex = cached(function (delimiters) { var open = delimiters[0].replace(regexEscapeRE, '\\$&'); var close = delimiters[1].replace(regexEscapeRE, '\\$&'); return new RegExp(open + '((?:.|\\n)+?)' + close, 'g') }); function parseText ( text, delimiters ) { var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { return } var tokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index; while ((match = tagRE.exec(text))) { index = match.index; // push text token if (index > lastIndex) { tokens.push(JSON.stringify(text.slice(lastIndex, index))); } // tag token var exp = parseFilters(match[1].trim()); tokens.push(("_s(" + exp + ")")); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push(JSON.stringify(text.slice(lastIndex))); } return tokens.join('+') } /* */ var onRE = /^@|^v-on:/; var dirRE = /^v-|^@|^:/; var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/; var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/; var argRE = /:(.*)$/; var bindRE = /^:|^v-bind:/; var modifierRE = /\.[^.]+/g; var decodeHTMLCached = cached(decode); // configurable state var warn$2; var delimiters; var transforms; var preTransforms; var postTransforms; var platformIsPreTag; var platformMustUseProp; var platformGetTagNamespace; /** * Convert HTML string to AST. */ function parse ( template, options ) { warn$2 = options.warn || baseWarn; platformGetTagNamespace = options.getTagNamespace || no; platformMustUseProp = options.mustUseProp || no; platformIsPreTag = options.isPreTag || no; preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); transforms = pluckModuleFunction(options.modules, 'transformNode'); postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; var stack = []; var preserveWhitespace = options.preserveWhitespace !== false; var root; var currentParent; var inVPre = false; var inPre = false; var warned = false; function warnOnce (msg) { if (!warned) { warned = true; warn$2(msg); } } function endPre (element) { // check pre state if (element.pre) { inVPre = false; } if (platformIsPreTag(element.tag)) { inPre = false; } } parseHTML(template, { warn: warn$2, expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, canBeLeftOpenTag: options.canBeLeftOpenTag, shouldDecodeNewlines: options.shouldDecodeNewlines, start: function start (tag, attrs, unary) { // check namespace. // inherit parent ns if there is one var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } var element = { type: 1, tag: tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), parent: currentParent, children: [] }; if (ns) { element.ns = ns; } if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; process.env.NODE_ENV !== 'production' && warn$2( 'Templates should only be responsible for mapping the state to the ' + 'UI. Avoid placing tags with side-effects in your templates, such as ' + "<" + tag + ">" + ', as they will not be parsed.' ); } // apply pre-transforms for (var i = 0; i < preTransforms.length; i++) { preTransforms[i](element, options); } if (!inVPre) { processPre(element); if (element.pre) { inVPre = true; } } if (platformIsPreTag(element.tag)) { inPre = true; } if (inVPre) { processRawAttrs(element); } else { processFor(element); processIf(element); processOnce(element); processKey(element); // determine whether this is a plain element after // removing structural attributes element.plain = !element.key && !attrs.length; processRef(element); processSlot(element); processComponent(element); for (var i$1 = 0; i$1 < transforms.length; i$1++) { transforms[i$1](element, options); } processAttrs(element); } function checkRootConstraints (el) { if (process.env.NODE_ENV !== 'production') { if (el.tag === 'slot' || el.tag === 'template') { warnOnce( "Cannot use <" + (el.tag) + "> as component root element because it may " + 'contain multiple nodes.' ); } if (el.attrsMap.hasOwnProperty('v-for')) { warnOnce( 'Cannot use v-for on stateful component root element because ' + 'it renders multiple elements.' ); } } } // tree management if (!root) { root = element; checkRootConstraints(root); } else if (!stack.length) { // allow root elements with v-if, v-else-if and v-else if (root.if && (element.elseif || element.else)) { checkRootConstraints(element); addIfCondition(root, { exp: element.elseif, block: element }); } else if (process.env.NODE_ENV !== 'production') { warnOnce( "Component template should contain exactly one root element. " + "If you are using v-if on multiple elements, " + "use v-else-if to chain them instead." ); } } if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); } else if (element.slotScope) { // scoped slot currentParent.plain = false; var name = element.slotTarget || '"default"';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } else { currentParent.children.push(element); element.parent = currentParent; } } if (!unary) { currentParent = element; stack.push(element); } else { endPre(element); } // apply post-transforms for (var i$2 = 0; i$2 < postTransforms.length; i$2++) { postTransforms[i$2](element, options); } }, end: function end () { // remove trailing whitespace var element = stack[stack.length - 1]; var lastNode = element.children[element.children.length - 1]; if (lastNode && lastNode.type === 3 && lastNode.text === ' ' && !inPre) { element.children.pop(); } // pop stack stack.length -= 1; currentParent = stack[stack.length - 1]; endPre(element); }, chars: function chars (text) { if (!currentParent) { if (process.env.NODE_ENV !== 'production') { if (text === template) { warnOnce( 'Component template requires a root element, rather than just text.' ); } else if ((text = text.trim())) { warnOnce( ("text \"" + text + "\" outside root element will be ignored.") ); } } return } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text ) { return } var children = currentParent.children; text = inPre || text.trim() ? isTextTag(currentParent) ? text : decodeHTMLCached(text) // only preserve whitespace if its not right after a starting tag : preserveWhitespace && children.length ? ' ' : ''; if (text) { var expression; if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) { children.push({ type: 2, expression: expression, text: text }); } else if (text !== ' ' || !children.length || children[children.length - 1].text !== ' ') { children.push({ type: 3, text: text }); } } } }); return root } function processPre (el) { if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } function processRawAttrs (el) { var l = el.attrsList.length; if (l) { var attrs = el.attrs = new Array(l); for (var i = 0; i < l; i++) { attrs[i] = { name: el.attrsList[i].name, value: JSON.stringify(el.attrsList[i].value) }; } } else if (!el.pre) { // non root node in pre blocks with no attributes el.plain = true; } } function processKey (el) { var exp = getBindingAttr(el, 'key'); if (exp) { if (process.env.NODE_ENV !== 'production' && el.tag === 'template') { warn$2("<template> cannot be keyed. Place the key on real elements instead."); } el.key = exp; } } function processRef (el) { var ref = getBindingAttr(el, 'ref'); if (ref) { el.ref = ref; el.refInFor = checkInFor(el); } } function processFor (el) { var exp; if ((exp = getAndRemoveAttr(el, 'v-for'))) { var inMatch = exp.match(forAliasRE); if (!inMatch) { process.env.NODE_ENV !== 'production' && warn$2( ("Invalid v-for expression: " + exp) ); return } el.for = inMatch[2].trim(); var alias = inMatch[1].trim(); var iteratorMatch = alias.match(forIteratorRE); if (iteratorMatch) { el.alias = iteratorMatch[1].trim(); el.iterator1 = iteratorMatch[2].trim(); if (iteratorMatch[3]) { el.iterator2 = iteratorMatch[3].trim(); } } else { el.alias = alias; } } } function processIf (el) { var exp = getAndRemoveAttr(el, 'v-if'); if (exp) { el.if = exp; addIfCondition(el, { exp: exp, block: el }); } else { if (getAndRemoveAttr(el, 'v-else') != null) { el.else = true; } var elseif = getAndRemoveAttr(el, 'v-else-if'); if (elseif) { el.elseif = elseif; } } } function processIfConditions (el, parent) { var prev = findPrevElement(parent.children); if (prev && prev.if) { addIfCondition(prev, { exp: el.elseif, block: el }); } else if (process.env.NODE_ENV !== 'production') { warn$2( "v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " + "used on element <" + (el.tag) + "> without corresponding v-if." ); } } function findPrevElement (children) { var i = children.length; while (i--) { if (children[i].type === 1) { return children[i] } else { if (process.env.NODE_ENV !== 'production' && children[i].text !== ' ') { warn$2( "text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " + "will be ignored." ); } children.pop(); } } } function addIfCondition (el, condition) { if (!el.ifConditions) { el.ifConditions = []; } el.ifConditions.push(condition); } function processOnce (el) { var once$$1 = getAndRemoveAttr(el, 'v-once'); if (once$$1 != null) { el.once = true; } } function processSlot (el) { if (el.tag === 'slot') { el.slotName = getBindingAttr(el, 'name'); if (process.env.NODE_ENV !== 'production' && el.key) { warn$2( "`key` does not work on <slot> because slots are abstract outlets " + "and can possibly expand into multiple elements. " + "Use the key on a wrapping element instead." ); } } else { var slotTarget = getBindingAttr(el, 'slot'); if (slotTarget) { el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget; } if (el.tag === 'template') { el.slotScope = getAndRemoveAttr(el, 'scope'); } } } function processComponent (el) { var binding; if ((binding = getBindingAttr(el, 'is'))) { el.component = binding; } if (getAndRemoveAttr(el, 'inline-template') != null) { el.inlineTemplate = true; } } function processAttrs (el) { var list = el.attrsList; var i, l, name, rawName, value, modifiers, isProp; for (i = 0, l = list.length; i < l; i++) { name = rawName = list[i].name; value = list[i].value; if (dirRE.test(name)) { // mark element as dynamic el.hasBindings = true; // modifiers modifiers = parseModifiers(name); if (modifiers) { name = name.replace(modifierRE, ''); } if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, ''); value = parseFilters(value); isProp = false; if (modifiers) { if (modifiers.prop) { isProp = true; name = camelize(name); if (name === 'innerHtml') { name = 'innerHTML'; } } if (modifiers.camel) { name = camelize(name); } if (modifiers.sync) { addHandler( el, ("update:" + (camelize(name))), genAssignmentCode(value, "$event") ); } } if (isProp || platformMustUseProp(el.tag, el.attrsMap.type, name)) { addProp(el, name, value); } else { addAttr(el, name, value); } } else if (onRE.test(name)) { // v-on name = name.replace(onRE, ''); addHandler(el, name, value, modifiers, false, warn$2); } else { // normal directives name = name.replace(dirRE, ''); // parse arg var argMatch = name.match(argRE); var arg = argMatch && argMatch[1]; if (arg) { name = name.slice(0, -(arg.length + 1)); } addDirective(el, name, rawName, value, arg, modifiers); if (process.env.NODE_ENV !== 'production' && name === 'model') { checkForAliasModel(el, value); } } } else { // literal attribute if (process.env.NODE_ENV !== 'production') { var expression = parseText(value, delimiters); if (expression) { warn$2( name + "=\"" + value + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div id="{{ val }}">, use <div :id="val">.' ); } } addAttr(el, name, JSON.stringify(value)); } } } function checkInFor (el) { var parent = el; while (parent) { if (parent.for !== undefined) { return true } parent = parent.parent; } return false } function parseModifiers (name) { var match = name.match(modifierRE); if (match) { var ret = {}; match.forEach(function (m) { ret[m.slice(1)] = true; }); return ret } } function makeAttrsMap (attrs) { var map = {}; for (var i = 0, l = attrs.length; i < l; i++) { if ( process.env.NODE_ENV !== 'production' && map[attrs[i].name] && !isIE && !isEdge ) { warn$2('duplicate attribute: ' + attrs[i].name); } map[attrs[i].name] = attrs[i].value; } return map } // for script (e.g. type="x/template") or style, do not decode content function isTextTag (el) { return el.tag === 'script' || el.tag === 'style' } function isForbiddenTag (el) { return ( el.tag === 'style' || (el.tag === 'script' && ( !el.attrsMap.type || el.attrsMap.type === 'text/javascript' )) ) } var ieNSBug = /^xmlns:NS\d+/; var ieNSPrefix = /^NS\d+:/; /* istanbul ignore next */ function guardIESVGBug (attrs) { var res = []; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (!ieNSBug.test(attr.name)) { attr.name = attr.name.replace(ieNSPrefix, ''); res.push(attr); } } return res } function checkForAliasModel (el, value) { var _el = el; while (_el) { if (_el.for && _el.alias === value) { warn$2( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "You are binding v-model directly to a v-for iteration alias. " + "This will not be able to modify the v-for source array because " + "writing to the alias is like modifying a function local variable. " + "Consider using an array of objects and use v-model on an object property instead." ); } _el = _el.parent; } } /* */ var isStaticKey; var isPlatformReservedTag; var genStaticKeysCached = cached(genStaticKeys$1); /** * Goal of the optimizer: walk the generated template AST tree * and detect sub-trees that are purely static, i.e. parts of * the DOM that never needs to change. * * Once we detect these sub-trees, we can: * * 1. Hoist them into constants, so that we no longer need to * create fresh nodes for them on each re-render; * 2. Completely skip them in the patching process. */ function optimize (root, options) { if (!root) { return } isStaticKey = genStaticKeysCached(options.staticKeys || ''); isPlatformReservedTag = options.isReservedTag || no; // first pass: mark all non-static nodes. markStatic$1(root); // second pass: mark static roots. markStaticRoots(root, false); } function genStaticKeys$1 (keys) { return makeMap( 'type,tag,attrsList,attrsMap,plain,parent,children,attrs' + (keys ? ',' + keys : '') ) } function markStatic$1 (node) { node.static = isStatic(node); if (node.type === 1) { // do not make component slot content static. this avoids // 1. components not able to mutate slot nodes // 2. static slot content fails for hot-reloading if ( !isPlatformReservedTag(node.tag) && node.tag !== 'slot' && node.attrsMap['inline-template'] == null ) { return } for (var i = 0, l = node.children.length; i < l; i++) { var child = node.children[i]; markStatic$1(child); if (!child.static) { node.static = false; } } } } function markStaticRoots (node, isInFor) { if (node.type === 1) { if (node.static || node.once) { node.staticInFor = isInFor; } // For a node to qualify as a static root, it should have children that // are not just static text. Otherwise the cost of hoisting out will // outweigh the benefits and it's better off to just always render it fresh. if (node.static && node.children.length && !( node.children.length === 1 && node.children[0].type === 3 )) { node.staticRoot = true; return } else { node.staticRoot = false; } if (node.children) { for (var i = 0, l = node.children.length; i < l; i++) { markStaticRoots(node.children[i], isInFor || !!node.for); } } if (node.ifConditions) { walkThroughConditionsBlocks(node.ifConditions, isInFor); } } } function walkThroughConditionsBlocks (conditionBlocks, isInFor) { for (var i = 1, len = conditionBlocks.length; i < len; i++) { markStaticRoots(conditionBlocks[i].block, isInFor); } } function isStatic (node) { if (node.type === 2) { // expression return false } if (node.type === 3) { // text return true } return !!(node.pre || ( !node.hasBindings && // no dynamic bindings !node.if && !node.for && // not v-if or v-for or v-else !isBuiltInTag(node.tag) && // not a built-in isPlatformReservedTag(node.tag) && // not a component !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )) } function isDirectChildOfTemplateFor (node) { while (node.parent) { node = node.parent; if (node.tag !== 'template') { return false } if (node.for) { return true } } return false } /* */ var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/; // keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, up: 38, left: 37, right: 39, down: 40, 'delete': [8, 46] }; // #4868: modifiers that prevent the execution of the listener // need to explicitly return null so that we can determine whether to remove // the listener for .once var genGuard = function (condition) { return ("if(" + condition + ")return null;"); }; var modifierCode = { stop: '$event.stopPropagation();', prevent: '$event.preventDefault();', self: genGuard("$event.target !== $event.currentTarget"), ctrl: genGuard("!$event.ctrlKey"), shift: genGuard("!$event.shiftKey"), alt: genGuard("!$event.altKey"), meta: genGuard("!$event.metaKey"), left: genGuard("'button' in $event && $event.button !== 0"), middle: genGuard("'button' in $event && $event.button !== 1"), right: genGuard("'button' in $event && $event.button !== 2") }; function genHandlers ( events, isNative, warn ) { var res = isNative ? 'nativeOn:{' : 'on:{'; for (var name in events) { var handler = events[name]; // #5330: warn click.right, since right clicks do not actually fire click events. if (process.env.NODE_ENV !== 'production' && name === 'click' && handler && handler.modifiers && handler.modifiers.right ) { warn( "Use \"contextmenu\" instead of \"click.right\" since right clicks " + "do not actually fire \"click\" events." ); } res += "\"" + name + "\":" + (genHandler(name, handler)) + ","; } return res.slice(0, -1) + '}' } function genHandler ( name, handler ) { if (!handler) { return 'function(){}' } if (Array.isArray(handler)) { return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]") } var isMethodPath = simplePathRE.test(handler.value); var isFunctionExpression = fnExpRE.test(handler.value); if (!handler.modifiers) { return isMethodPath || isFunctionExpression ? handler.value : ("function($event){" + (handler.value) + "}") // inline statement } else { var code = ''; var genModifierCode = ''; var keys = []; for (var key in handler.modifiers) { if (modifierCode[key]) { genModifierCode += modifierCode[key]; // left/right if (keyCodes[key]) { keys.push(key); } } else { keys.push(key); } } if (keys.length) { code += genKeyFilter(keys); } // Make sure modifiers like prevent and stop get executed after key filtering if (genModifierCode) { code += genModifierCode; } var handlerCode = isMethodPath ? handler.value + '($event)' : isFunctionExpression ? ("(" + (handler.value) + ")($event)") : handler.value; return ("function($event){" + code + handlerCode + "}") } } function genKeyFilter (keys) { return ("if(!('button' in $event)&&" + (keys.map(genFilterCode).join('&&')) + ")return null;") } function genFilterCode (key) { var keyVal = parseInt(key, 10); if (keyVal) { return ("$event.keyCode!==" + keyVal) } var alias = keyCodes[key]; return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")") } /* */ function bind$1 (el, dir) { el.wrapData = function (code) { return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + ")") }; } /* */ var baseDirectives = { bind: bind$1, cloak: noop }; /* */ // configurable state var warn$3; var transforms$1; var dataGenFns; var platformDirectives$1; var isPlatformReservedTag$1; var staticRenderFns; var onceCount; var currentOptions; function generate ( ast, options ) { // save previous staticRenderFns so generate calls can be nested var prevStaticRenderFns = staticRenderFns; var currentStaticRenderFns = staticRenderFns = []; var prevOnceCount = onceCount; onceCount = 0; currentOptions = options; warn$3 = options.warn || baseWarn; transforms$1 = pluckModuleFunction(options.modules, 'transformCode'); dataGenFns = pluckModuleFunction(options.modules, 'genData'); platformDirectives$1 = options.directives || {}; isPlatformReservedTag$1 = options.isReservedTag || no; var code = ast ? genElement(ast) : '_c("div")'; staticRenderFns = prevStaticRenderFns; onceCount = prevOnceCount; return { render: ("with(this){return " + code + "}"), staticRenderFns: currentStaticRenderFns } } function genElement (el) { if (el.staticRoot && !el.staticProcessed) { return genStatic(el) } else if (el.once && !el.onceProcessed) { return genOnce(el) } else if (el.for && !el.forProcessed) { return genFor(el) } else if (el.if && !el.ifProcessed) { return genIf(el) } else if (el.tag === 'template' && !el.slotTarget) { return genChildren(el) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el) } else { // component or element var code; if (el.component) { code = genComponent(el.component, el); } else { var data = el.plain ? undefined : genData(el); var children = el.inlineTemplate ? null : genChildren(el, true); code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")"; } // module transforms for (var i = 0; i < transforms$1.length; i++) { code = transforms$1[i](el, code); } return code } } // hoist static sub-trees out function genStatic (el) { el.staticProcessed = true; staticRenderFns.push(("with(this){return " + (genElement(el)) + "}")); return ("_m(" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")") } // v-once function genOnce (el) { el.onceProcessed = true; if (el.if && !el.ifProcessed) { return genIf(el) } else if (el.staticInFor) { var key = ''; var parent = el.parent; while (parent) { if (parent.for) { key = parent.key; break } parent = parent.parent; } if (!key) { process.env.NODE_ENV !== 'production' && warn$3( "v-once can only be used inside v-for that is keyed. " ); return genElement(el) } return ("_o(" + (genElement(el)) + "," + (onceCount++) + (key ? ("," + key) : "") + ")") } else { return genStatic(el) } } function genIf (el) { el.ifProcessed = true; // avoid recursion return genIfConditions(el.ifConditions.slice()) } function genIfConditions (conditions) { if (!conditions.length) { return '_e()' } var condition = conditions.shift(); if (condition.exp) { return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions))) } else { return ("" + (genTernaryExp(condition.block))) } // v-if with v-once should generate code like (a)?_m(0):_m(1) function genTernaryExp (el) { return el.once ? genOnce(el) : genElement(el) } } function genFor (el) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; if ( process.env.NODE_ENV !== 'production' && maybeComponent(el) && el.tag !== 'slot' && el.tag !== 'template' && !el.key ) { warn$3( "<" + (el.tag) + " v-for=\"" + alias + " in " + exp + "\">: component lists rendered with " + "v-for should have explicit keys. " + "See https://vuejs.org/guide/list.html#key for more info.", true /* tip */ ); } el.forProcessed = true; // avoid recursion return "_l((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + (genElement(el)) + '})' } function genData (el) { var data = '{'; // directives first. // directives may mutate the el's other properties before they are generated. var dirs = genDirectives(el); if (dirs) { data += dirs + ','; } // key if (el.key) { data += "key:" + (el.key) + ","; } // ref if (el.ref) { data += "ref:" + (el.ref) + ","; } if (el.refInFor) { data += "refInFor:true,"; } // pre if (el.pre) { data += "pre:true,"; } // record original tag name for components using "is" attribute if (el.component) { data += "tag:\"" + (el.tag) + "\","; } // module data generation functions for (var i = 0; i < dataGenFns.length; i++) { data += dataGenFns[i](el); } // attributes if (el.attrs) { data += "attrs:{" + (genProps(el.attrs)) + "},"; } // DOM props if (el.props) { data += "domProps:{" + (genProps(el.props)) + "},"; } // event handlers if (el.events) { data += (genHandlers(el.events, false, warn$3)) + ","; } if (el.nativeEvents) { data += (genHandlers(el.nativeEvents, true, warn$3)) + ","; } // slot target if (el.slotTarget) { data += "slot:" + (el.slotTarget) + ","; } // scoped slots if (el.scopedSlots) { data += (genScopedSlots(el.scopedSlots)) + ","; } // component v-model if (el.model) { data += "model:{value:" + (el.model.value) + ",callback:" + (el.model.callback) + ",expression:" + (el.model.expression) + "},"; } // inline-template if (el.inlineTemplate) { var inlineTemplate = genInlineTemplate(el); if (inlineTemplate) { data += inlineTemplate + ","; } } data = data.replace(/,$/, '') + '}'; // v-bind data wrap if (el.wrapData) { data = el.wrapData(data); } return data } function genDirectives (el) { var dirs = el.directives; if (!dirs) { return } var res = 'directives:['; var hasRuntime = false; var i, l, dir, needRuntime; for (i = 0, l = dirs.length; i < l; i++) { dir = dirs[i]; needRuntime = true; var gen = platformDirectives$1[dir.name] || baseDirectives[dir.name]; if (gen) { // compile-time directive that manipulates AST. // returns true if it also needs a runtime counterpart. needRuntime = !!gen(el, dir, warn$3); } if (needRuntime) { hasRuntime = true; res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},"; } } if (hasRuntime) { return res.slice(0, -1) + ']' } } function genInlineTemplate (el) { var ast = el.children[0]; if (process.env.NODE_ENV !== 'production' && ( el.children.length > 1 || ast.type !== 1 )) { warn$3('Inline-template components must have exactly one child element.'); } if (ast.type === 1) { var inlineRenderFns = generate(ast, currentOptions); return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}") } } function genScopedSlots (slots) { return ("scopedSlots:_u([" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + "])") } function genScopedSlot (key, el) { if (el.for && !el.forProcessed) { return genForScopedSlot(key, el) } return "{key:" + key + ",fn:function(" + (String(el.attrsMap.scope)) + "){" + "return " + (el.tag === 'template' ? genChildren(el) || 'void 0' : genElement(el)) + "}}" } function genForScopedSlot (key, el) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; el.forProcessed = true; // avoid recursion return "_l((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + (genScopedSlot(key, el)) + '})' } function genChildren (el, checkSkip) { var children = el.children; if (children.length) { var el$1 = children[0]; // optimize single v-for if (children.length === 1 && el$1.for && el$1.tag !== 'template' && el$1.tag !== 'slot' ) { return genElement(el$1) } var normalizationType = checkSkip ? getNormalizationType(children) : 0; return ("[" + (children.map(genNode).join(',')) + "]" + (normalizationType ? ("," + normalizationType) : '')) } } // determine the normalization needed for the children array. // 0: no normalization needed // 1: simple normalization needed (possible 1-level deep nested array) // 2: full normalization needed function getNormalizationType (children) { var res = 0; for (var i = 0; i < children.length; i++) { var el = children[i]; if (el.type !== 1) { continue } if (needsNormalization(el) || (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) { res = 2; break } if (maybeComponent(el) || (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) { res = 1; } } return res } function needsNormalization (el) { return el.for !== undefined || el.tag === 'template' || el.tag === 'slot' } function maybeComponent (el) { return !isPlatformReservedTag$1(el.tag) } function genNode (node) { if (node.type === 1) { return genElement(node) } else { return genText(node) } } function genText (text) { return ("_v(" + (text.type === 2 ? text.expression // no need for () because already wrapped in _s() : transformSpecialNewlines(JSON.stringify(text.text))) + ")") } function genSlot (el) { var slotName = el.slotName || '"default"'; var children = genChildren(el); var res = "_t(" + slotName + (children ? ("," + children) : ''); var attrs = el.attrs && ("{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}"); var bind$$1 = el.attrsMap['v-bind']; if ((attrs || bind$$1) && !children) { res += ",null"; } if (attrs) { res += "," + attrs; } if (bind$$1) { res += (attrs ? '' : ',null') + "," + bind$$1; } return res + ')' } // componentName is el.component, take it as argument to shun flow's pessimistic refinement function genComponent (componentName, el) { var children = el.inlineTemplate ? null : genChildren(el, true); return ("_c(" + componentName + "," + (genData(el)) + (children ? ("," + children) : '') + ")") } function genProps (props) { var res = ''; for (var i = 0; i < props.length; i++) { var prop = props[i]; res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ","; } return res.slice(0, -1) } // #3895, #4268 function transformSpecialNewlines (text) { return text .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') } /* */ // these keywords should not appear inside expressions, but operators like // typeof, instanceof and in are allowed var prohibitedKeywordRE = new RegExp('\\b' + ( 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' + 'super,throw,while,yield,delete,export,import,return,switch,default,' + 'extends,finally,continue,debugger,function,arguments' ).split(',').join('\\b|\\b') + '\\b'); // these unary operators should not be used as property/method names var unaryOperatorsRE = new RegExp('\\b' + ( 'delete,typeof,void' ).split(',').join('\\s*\\([^\\)]*\\)|\\b') + '\\s*\\([^\\)]*\\)'); // check valid identifier for v-for var identRE = /[A-Za-z_$][\w$]*/; // strip strings in expressions var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g; // detect problematic expressions in a template function detectErrors (ast) { var errors = []; if (ast) { checkNode(ast, errors); } return errors } function checkNode (node, errors) { if (node.type === 1) { for (var name in node.attrsMap) { if (dirRE.test(name)) { var value = node.attrsMap[name]; if (value) { if (name === 'v-for') { checkFor(node, ("v-for=\"" + value + "\""), errors); } else if (onRE.test(name)) { checkEvent(value, (name + "=\"" + value + "\""), errors); } else { checkExpression(value, (name + "=\"" + value + "\""), errors); } } } } if (node.children) { for (var i = 0; i < node.children.length; i++) { checkNode(node.children[i], errors); } } } else if (node.type === 2) { checkExpression(node.expression, node.text, errors); } } function checkEvent (exp, text, errors) { var stipped = exp.replace(stripStringRE, ''); var keywordMatch = stipped.match(unaryOperatorsRE); if (keywordMatch && stipped.charAt(keywordMatch.index - 1) !== '$') { errors.push( "avoid using JavaScript unary operator as property name: " + "\"" + (keywordMatch[0]) + "\" in expression " + (text.trim()) ); } checkExpression(exp, text, errors); } function checkFor (node, text, errors) { checkExpression(node.for || '', text, errors); checkIdentifier(node.alias, 'v-for alias', text, errors); checkIdentifier(node.iterator1, 'v-for iterator', text, errors); checkIdentifier(node.iterator2, 'v-for iterator', text, errors); } function checkIdentifier (ident, type, text, errors) { if (typeof ident === 'string' && !identRE.test(ident)) { errors.push(("invalid " + type + " \"" + ident + "\" in expression: " + (text.trim()))); } } function checkExpression (exp, text, errors) { try { new Function(("return " + exp)); } catch (e) { var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE); if (keywordMatch) { errors.push( "avoid using JavaScript keyword as property name: " + "\"" + (keywordMatch[0]) + "\" in expression " + (text.trim()) ); } else { errors.push(("invalid expression: " + (text.trim()))); } } } /* */ function baseCompile ( template, options ) { var ast = parse(template.trim(), options); optimize(ast, options); var code = generate(ast, options); return { ast: ast, render: code.render, staticRenderFns: code.staticRenderFns } } function makeFunction (code, errors) { try { return new Function(code) } catch (err) { errors.push({ err: err, code: code }); return noop } } function createCompiler (baseOptions) { var functionCompileCache = Object.create(null); function compile ( template, options ) { var finalOptions = Object.create(baseOptions); var errors = []; var tips = []; finalOptions.warn = function (msg, tip$$1) { (tip$$1 ? tips : errors).push(msg); }; if (options) { // merge custom modules if (options.modules) { finalOptions.modules = (baseOptions.modules || []).concat(options.modules); } // merge custom directives if (options.directives) { finalOptions.directives = extend( Object.create(baseOptions.directives), options.directives ); } // copy other options for (var key in options) { if (key !== 'modules' && key !== 'directives') { finalOptions[key] = options[key]; } } } var compiled = baseCompile(template, finalOptions); if (process.env.NODE_ENV !== 'production') { errors.push.apply(errors, detectErrors(compiled.ast)); } compiled.errors = errors; compiled.tips = tips; return compiled } function compileToFunctions ( template, options, vm ) { options = options || {}; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { // detect possible CSP restriction try { new Function('return 1'); } catch (e) { if (e.toString().match(/unsafe-eval|CSP/)) { warn( 'It seems you are using the standalone build of Vue.js in an ' + 'environment with Content Security Policy that prohibits unsafe-eval. ' + 'The template compiler cannot work in this environment. Consider ' + 'relaxing the policy to allow unsafe-eval or pre-compiling your ' + 'templates into render functions.' ); } } } // check cache var key = options.delimiters ? String(options.delimiters) + template : template; if (functionCompileCache[key]) { return functionCompileCache[key] } // compile var compiled = compile(template, options); // check compilation errors/tips if (process.env.NODE_ENV !== 'production') { if (compiled.errors && compiled.errors.length) { warn( "Error compiling template:\n\n" + template + "\n\n" + compiled.errors.map(function (e) { return ("- " + e); }).join('\n') + '\n', vm ); } if (compiled.tips && compiled.tips.length) { compiled.tips.forEach(function (msg) { return tip(msg, vm); }); } } // turn code into functions var res = {}; var fnGenErrors = []; res.render = makeFunction(compiled.render, fnGenErrors); var l = compiled.staticRenderFns.length; res.staticRenderFns = new Array(l); for (var i = 0; i < l; i++) { res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i], fnGenErrors); } // check function generation errors. // this should only happen if there is a bug in the compiler itself. // mostly for codegen development use /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if ((!compiled.errors || !compiled.errors.length) && fnGenErrors.length) { warn( "Failed to generate render function:\n\n" + fnGenErrors.map(function (ref) { var err = ref.err; var code = ref.code; return ((err.toString()) + " in\n\n" + code + "\n"); }).join('\n'), vm ); } } return (functionCompileCache[key] = res) } return { compile: compile, compileToFunctions: compileToFunctions } } /* */ function transformNode (el, options) { var warn = options.warn || baseWarn; var staticClass = getAndRemoveAttr(el, 'class'); if (process.env.NODE_ENV !== 'production' && staticClass) { var expression = parseText(staticClass, options.delimiters); if (expression) { warn( "class=\"" + staticClass + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.' ); } } if (staticClass) { el.staticClass = JSON.stringify(staticClass); } var classBinding = getBindingAttr(el, 'class', false /* getStatic */); if (classBinding) { el.classBinding = classBinding; } } function genData$1 (el) { var data = ''; if (el.staticClass) { data += "staticClass:" + (el.staticClass) + ","; } if (el.classBinding) { data += "class:" + (el.classBinding) + ","; } return data } var klass$1 = { staticKeys: ['staticClass'], transformNode: transformNode, genData: genData$1 }; /* */ function transformNode$1 (el, options) { var warn = options.warn || baseWarn; var staticStyle = getAndRemoveAttr(el, 'style'); if (staticStyle) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { var expression = parseText(staticStyle, options.delimiters); if (expression) { warn( "style=\"" + staticStyle + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.' ); } } el.staticStyle = JSON.stringify(parseStyleText(staticStyle)); } var styleBinding = getBindingAttr(el, 'style', false /* getStatic */); if (styleBinding) { el.styleBinding = styleBinding; } } function genData$2 (el) { var data = ''; if (el.staticStyle) { data += "staticStyle:" + (el.staticStyle) + ","; } if (el.styleBinding) { data += "style:(" + (el.styleBinding) + "),"; } return data } var style$1 = { staticKeys: ['staticStyle'], transformNode: transformNode$1, genData: genData$2 }; var modules$1 = [ klass$1, style$1 ]; /* */ function text (el, dir) { if (dir.value) { addProp(el, 'textContent', ("_s(" + (dir.value) + ")")); } } /* */ function html (el, dir) { if (dir.value) { addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")")); } } var directives$1 = { model: model, text: text, html: html }; /* */ var baseOptions = { expectHTML: true, modules: modules$1, directives: directives$1, isPreTag: isPreTag, isUnaryTag: isUnaryTag, mustUseProp: mustUseProp, canBeLeftOpenTag: canBeLeftOpenTag, isReservedTag: isReservedTag, getTagNamespace: getTagNamespace, staticKeys: genStaticKeys(modules$1) }; var ref$1 = createCompiler(baseOptions); var compileToFunctions = ref$1.compileToFunctions; /* */ var idToTemplate = cached(function (id) { var el = query(id); return el && el.innerHTML }); var mount = Vue$3.prototype.$mount; Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && query(el); /* istanbul ignore if */ if (el === document.body || el === document.documentElement) { process.env.NODE_ENV !== 'production' && warn( "Do not mount Vue to <html> or <body> - mount to normal elements instead." ); return this } var options = this.$options; // resolve template/el and convert to render function if (!options.render) { var template = options.template; if (template) { if (typeof template === 'string') { if (template.charAt(0) === '#') { template = idToTemplate(template); /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && !template) { warn( ("Template element not found or is empty: " + (options.template)), this ); } } } else if (template.nodeType) { template = template.innerHTML; } else { if (process.env.NODE_ENV !== 'production') { warn('invalid template option:' + template, this); } return this } } else if (el) { template = getOuterHTML(el); } if (template) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { mark('compile'); } var ref = compileToFunctions(template, { shouldDecodeNewlines: shouldDecodeNewlines, delimiters: options.delimiters }, this); var render = ref.render; var staticRenderFns = ref.staticRenderFns; options.render = render; options.staticRenderFns = staticRenderFns; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { mark('compile end'); measure(((this._name) + " compile"), 'compile', 'compile end'); } } } return mount.call(this, el, hydrating) }; /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */ function getOuterHTML (el) { if (el.outerHTML) { return el.outerHTML } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML } } Vue$3.compile = compileToFunctions; /* harmony default export */ __webpack_exports__["default"] = (Vue$3); /* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(0), __webpack_require__(5))) /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _vue = __webpack_require__(3); var _vue2 = _interopRequireDefault(_vue); var _vueRouter = __webpack_require__(2); var _vueRouter2 = _interopRequireDefault(_vueRouter); var _vueResource = __webpack_require__(1); var _vueResource2 = _interopRequireDefault(_vueResource); var _header = __webpack_require__(7); var _header2 = _interopRequireDefault(_header); var _chain = __webpack_require__(21); var _chain2 = _interopRequireDefault(_chain); var _english = __webpack_require__(22); var _english2 = _interopRequireDefault(_english); var _jp = __webpack_require__(25); var _jp2 = _interopRequireDefault(_jp); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } //引入vue-resource,类似ajax var Foo = { template: '<div>foo</div>' }; var Bar = { template: '<div>bar</div>' }; console.log(Foo); _vue2.default.use(_vueRouter2.default); _vue2.default.use(_vueResource2.default); var router = new _vueRouter2.default({ routes: [{ path: '/', name: 'headHtml', component: _header2.default, redirect: '/Ch' }, // { path: '/Ch', component: Ch, name: "Ch" }, { path: '/En', component: _english2.default }, { path: '/Jp', component: _jp2.default }] }); var vm = new _vue2.default({ el: "#app", router: router, data: function data() { return {}; }, template: '<div><headHtml /></div>', components: { 'headHtml': _header2.default } }); /***/ }), /* 5 */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || Function("return this")() || (1,eval)("this"); } catch(e) { // This works if the window reference is available if(typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /* 6 */ /***/ (function(module, exports) { /* (ignored) */ /***/ }), /* 7 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_header_vue__ = __webpack_require__(8); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_bec82480_node_modules_vue_loader_lib_selector_type_template_index_0_header_vue__ = __webpack_require__(12); var disposed = false function injectStyle (ssrContext) { if (disposed) return __webpack_require__(13) } var normalizeComponent = __webpack_require__(11) /* script */ /* template */ /* styles */ var __vue_styles__ = injectStyle /* scopeId */ var __vue_scopeId__ = null /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = normalizeComponent( __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_header_vue__["a" /* default */], __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_bec82480_node_modules_vue_loader_lib_selector_type_template_index_0_header_vue__["a" /* default */], __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "myGit/vue/components/header.vue" if (Component.esModule && Object.keys(Component.esModule).some(function (key) {return key !== "default" && key.substr(0, 2) !== "__"})) {console.error("named exports are not supported in *.vue files.")} if (Component.options.functional) {console.error("[vue-loader] header.vue: functional components are not supported with templates, they should use render functions.")} /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-bec82480", Component.options) } else { hotAPI.reload("data-v-bec82480", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} /* harmony default export */ __webpack_exports__["default"] = (Component.exports); /***/ }), /* 8 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // // // // // // // // // /* harmony default export */ __webpack_exports__["a"] = ({}); /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { exports = module.exports = __webpack_require__(10)(); // imports // module exports.push([module.i, "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", ""]); // exports /***/ }), /* 10 */ /***/ (function(module, exports) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ // css base code, injected by the css-loader module.exports = function() { var list = []; // return the list of modules as css string list.toString = function toString() { var result = []; for(var i = 0; i < this.length; i++) { var item = this[i]; if(item[2]) { result.push("@media " + item[2] + "{" + item[1] + "}"); } else { result.push(item[1]); } } return result.join(""); }; // import a list of modules into the list list.i = function(modules, mediaQuery) { if(typeof modules === "string") modules = [[null, modules, ""]]; var alreadyImportedModules = {}; for(var i = 0; i < this.length; i++) { var id = this[i][0]; if(typeof id === "number") alreadyImportedModules[id] = true; } for(i = 0; i < modules.length; i++) { var item = modules[i]; // skip already imported module // this implementation is not 100% perfect for weird media query combinations // when a module is imported multiple times with different media queries. // I hope this will never occur (Hey this way we have smaller bundles) if(typeof item[0] !== "number" || !alreadyImportedModules[item[0]]) { if(mediaQuery && !item[2]) { item[2] = mediaQuery; } else if(mediaQuery) { item[2] = "(" + item[2] + ") and (" + mediaQuery + ")"; } list.push(item); } } }; return list; }; /***/ }), /* 11 */ /***/ (function(module, exports) { /* globals __VUE_SSR_CONTEXT__ */ // this module is a runtime utility for cleaner component module output and will // be included in the final webpack user bundle module.exports = function normalizeComponent ( rawScriptExports, compiledTemplate, injectStyles, scopeId, moduleIdentifier /* server only */ ) { var esModule var scriptExports = rawScriptExports = rawScriptExports || {} // ES6 modules interop var type = typeof rawScriptExports.default if (type === 'object' || type === 'function') { esModule = rawScriptExports scriptExports = rawScriptExports.default } // Vue.extend constructor export interop var options = typeof scriptExports === 'function' ? scriptExports.options : scriptExports // render functions if (compiledTemplate) { options.render = compiledTemplate.render options.staticRenderFns = compiledTemplate.staticRenderFns } // scopedId if (scopeId) { options._scopeId = scopeId } var hook if (moduleIdentifier) { // server build hook = function (context) { // 2.3 injection context = context || // cached call (this.$vnode && this.$vnode.ssrContext) || // stateful (this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional // 2.2 with runInNewContext: true if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') { context = __VUE_SSR_CONTEXT__ } // inject component styles if (injectStyles) { injectStyles.call(this, context) } // register component module identifier for async chunk inferrence if (context && context._registeredComponents) { context._registeredComponents.add(moduleIdentifier) } } // used by ssr in case component is cached and beforeCreate // never gets called options._ssrRegister = hook } else if (injectStyles) { hook = injectStyles } if (hook) { var functional = options.functional var existing = functional ? options.render : options.beforeCreate if (!functional) { // inject component registration as beforeCreate hook options.beforeCreate = existing ? [].concat(existing, hook) : [hook] } else { // register for functioal component in vue file options.render = function renderWithStyleInjection (h, context) { hook.call(context) return existing(h, context) } } } return { esModule: esModule, exports: scriptExports, options: options } } /***/ }), /* 12 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('aside', [_c('router-link', { attrs: { "to": "/Ch" } }, [_vm._v("汉语")]), _vm._v(" "), _c('router-link', { attrs: { "to": "/En" } }, [_vm._v("英语课")]), _vm._v(" "), _c('router-link', { attrs: { "to": "/Jp" } }, [_vm._v("日语")]), _vm._v(" "), _c('router-view')], 1) } var staticRenderFns = [] render._withStripped = true /* harmony default export */ __webpack_exports__["a"] = ({ render: render, staticRenderFns: staticRenderFns }); if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-bec82480", module.exports) } } /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { // style-loader: Adds some css to the DOM by adding a <style> tag // load the styles var content = __webpack_require__(9); if(typeof content === 'string') content = [[module.i, content, '']]; if(content.locals) module.exports = content.locals; // add the styles to the DOM var update = __webpack_require__(14)("37f4116b", content, false); // Hot Module Replacement if(false) { // When the styles change, update the <style> tags if(!content.locals) { module.hot.accept("!!../../../node_modules/css-loader/index.js!../../../node_modules/vue-loader/lib/style-compiler/index.js?{\"vue\":true,\"id\":\"data-v-bec82480\",\"scoped\":false,\"hasInlineConfig\":false}!../../../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./header.vue", function() { var newContent = require("!!../../../node_modules/css-loader/index.js!../../../node_modules/vue-loader/lib/style-compiler/index.js?{\"vue\":true,\"id\":\"data-v-bec82480\",\"scoped\":false,\"hasInlineConfig\":false}!../../../node_modules/vue-loader/lib/selector.js?type=styles&index=0!./header.vue"); if(typeof newContent === 'string') newContent = [[module.id, newContent, '']]; update(newContent); }); } // When the module is disposed, remove the <style> tags module.hot.dispose(function() { update(); }); } /***/ }), /* 14 */ /***/ (function(module, exports, __webpack_require__) { /* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra Modified by Evan You @yyx990803 */ var hasDocument = typeof document !== 'undefined' if (typeof DEBUG !== 'undefined' && DEBUG) { if (!hasDocument) { throw new Error( 'vue-style-loader cannot be used in a non-browser environment. ' + "Use { target: 'node' } in your Webpack config to indicate a server-rendering environment." ) } } var listToStyles = __webpack_require__(15) /* type StyleObject = { id: number; parts: Array<StyleObjectPart> } type StyleObjectPart = { css: string; media: string; sourceMap: ?string } */ var stylesInDom = {/* [id: number]: { id: number, refs: number, parts: Array<(obj?: StyleObjectPart) => void> } */} var head = hasDocument && (document.head || document.getElementsByTagName('head')[0]) var singletonElement = null var singletonCounter = 0 var isProduction = false var noop = function () {} // Force single-tag solution on IE6-9, which has a hard limit on the # of <style> // tags it will allow on a page var isOldIE = typeof navigator !== 'undefined' && /msie [6-9]\b/.test(navigator.userAgent.toLowerCase()) module.exports = function (parentId, list, _isProduction) { isProduction = _isProduction var styles = listToStyles(parentId, list) addStylesToDom(styles) return function update (newList) { var mayRemove = [] for (var i = 0; i < styles.length; i++) { var item = styles[i] var domStyle = stylesInDom[item.id] domStyle.refs-- mayRemove.push(domStyle) } if (newList) { styles = listToStyles(parentId, newList) addStylesToDom(styles) } else { styles = [] } for (var i = 0; i < mayRemove.length; i++) { var domStyle = mayRemove[i] if (domStyle.refs === 0) { for (var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j]() } delete stylesInDom[domStyle.id] } } } } function addStylesToDom (styles /* Array<StyleObject> */) { for (var i = 0; i < styles.length; i++) { var item = styles[i] var domStyle = stylesInDom[item.id] if (domStyle) { domStyle.refs++ for (var j = 0; j < domStyle.parts.length; j++) { domStyle.parts[j](item.parts[j]) } for (; j < item.parts.length; j++) { domStyle.parts.push(addStyle(item.parts[j])) } if (domStyle.parts.length > item.parts.length) { domStyle.parts.length = item.parts.length } } else { var parts = [] for (var j = 0; j < item.parts.length; j++) { parts.push(addStyle(item.parts[j])) } stylesInDom[item.id] = { id: item.id, refs: 1, parts: parts } } } } function createStyleElement () { var styleElement = document.createElement('style') styleElement.type = 'text/css' head.appendChild(styleElement) return styleElement } function addStyle (obj /* StyleObjectPart */) { var update, remove var styleElement = document.querySelector('style[data-vue-ssr-id~="' + obj.id + '"]') if (styleElement) { if (isProduction) { // has SSR styles and in production mode. // simply do nothing. return noop } else { // has SSR styles but in dev mode. // for some reason Chrome can't handle source map in server-rendered // style tags - source maps in <style> only works if the style tag is // created and inserted dynamically. So we remove the server rendered // styles and inject new ones. styleElement.parentNode.removeChild(styleElement) } } if (isOldIE) { // use singleton mode for IE9. var styleIndex = singletonCounter++ styleElement = singletonElement || (singletonElement = createStyleElement()) update = applyToSingletonTag.bind(null, styleElement, styleIndex, false) remove = applyToSingletonTag.bind(null, styleElement, styleIndex, true) } else { // use multi-style-tag mode in all other cases styleElement = createStyleElement() update = applyToTag.bind(null, styleElement) remove = function () { styleElement.parentNode.removeChild(styleElement) } } update(obj) return function updateStyle (newObj /* StyleObjectPart */) { if (newObj) { if (newObj.css === obj.css && newObj.media === obj.media && newObj.sourceMap === obj.sourceMap) { return } update(obj = newObj) } else { remove() } } } var replaceText = (function () { var textStore = [] return function (index, replacement) { textStore[index] = replacement return textStore.filter(Boolean).join('\n') } })() function applyToSingletonTag (styleElement, index, remove, obj) { var css = remove ? '' : obj.css if (styleElement.styleSheet) { styleElement.styleSheet.cssText = replaceText(index, css) } else { var cssNode = document.createTextNode(css) var childNodes = styleElement.childNodes if (childNodes[index]) styleElement.removeChild(childNodes[index]) if (childNodes.length) { styleElement.insertBefore(cssNode, childNodes[index]) } else { styleElement.appendChild(cssNode) } } } function applyToTag (styleElement, obj) { var css = obj.css var media = obj.media var sourceMap = obj.sourceMap if (media) { styleElement.setAttribute('media', media) } if (sourceMap) { // https://developer.chrome.com/devtools/docs/javascript-debugging // this makes source maps inside style tags work properly in Chrome css += '\n/*# sourceURL=' + sourceMap.sources[0] + ' */' // http://stackoverflow.com/a/26603875 css += '\n/*# sourceMappingURL=data:application/json;base64,' + btoa(unescape(encodeURIComponent(JSON.stringify(sourceMap)))) + ' */' } if (styleElement.styleSheet) { styleElement.styleSheet.cssText = css } else { while (styleElement.firstChild) { styleElement.removeChild(styleElement.firstChild) } styleElement.appendChild(document.createTextNode(css)) } } /***/ }), /* 15 */ /***/ (function(module, exports) { /** * Translates the list format produced by css-loader into something * easier to manipulate. */ module.exports = function listToStyles (parentId, list) { var styles = [] var newStyles = {} for (var i = 0; i < list.length; i++) { var item = list[i] var id = item[0] var css = item[1] var media = item[2] var sourceMap = item[3] var part = { id: parentId + ':' + i, css: css, media: media, sourceMap: sourceMap } if (!newStyles[id]) { styles.push(newStyles[id] = { id: id, parts: [part] }) } else { newStyles[id].parts.push(part) } } return styles } /***/ }), /* 16 */, /* 17 */, /* 18 */, /* 19 */, /* 20 */, /* 21 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_template_compiler_index_id_data_v_373d7a9c_node_modules_vue_loader_lib_selector_type_template_index_0_chain_vue__ = __webpack_require__(23); var disposed = false var normalizeComponent = __webpack_require__(11) /* script */ var __vue_script__ = null /* template */ /* styles */ var __vue_styles__ = null /* scopeId */ var __vue_scopeId__ = null /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = normalizeComponent( __vue_script__, __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_template_compiler_index_id_data_v_373d7a9c_node_modules_vue_loader_lib_selector_type_template_index_0_chain_vue__["a" /* default */], __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "myGit/vue/components/header/chain.vue" if (Component.esModule && Object.keys(Component.esModule).some(function (key) {return key !== "default" && key.substr(0, 2) !== "__"})) {console.error("named exports are not supported in *.vue files.")} if (Component.options.functional) {console.error("[vue-loader] chain.vue: functional components are not supported with templates, they should use render functions.")} /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-373d7a9c", Component.options) } else { hotAPI.reload("data-v-373d7a9c", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} /* harmony default export */ __webpack_exports__["default"] = (Component.exports); /***/ }), /* 22 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_english_vue__ = __webpack_require__(27); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_523584a1_node_modules_vue_loader_lib_selector_type_template_index_0_english_vue__ = __webpack_require__(24); var disposed = false var normalizeComponent = __webpack_require__(11) /* script */ /* template */ /* styles */ var __vue_styles__ = null /* scopeId */ var __vue_scopeId__ = null /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = normalizeComponent( __WEBPACK_IMPORTED_MODULE_0__babel_loader_node_modules_vue_loader_lib_selector_type_script_index_0_english_vue__["a" /* default */], __WEBPACK_IMPORTED_MODULE_1__node_modules_vue_loader_lib_template_compiler_index_id_data_v_523584a1_node_modules_vue_loader_lib_selector_type_template_index_0_english_vue__["a" /* default */], __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "myGit/vue/components/header/english.vue" if (Component.esModule && Object.keys(Component.esModule).some(function (key) {return key !== "default" && key.substr(0, 2) !== "__"})) {console.error("named exports are not supported in *.vue files.")} if (Component.options.functional) {console.error("[vue-loader] english.vue: functional components are not supported with templates, they should use render functions.")} /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-523584a1", Component.options) } else { hotAPI.reload("data-v-523584a1", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} /* harmony default export */ __webpack_exports__["default"] = (Component.exports); /***/ }), /* 23 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', [_vm._v("1")]) } var staticRenderFns = [] render._withStripped = true /* harmony default export */ __webpack_exports__["a"] = ({ render: render, staticRenderFns: staticRenderFns }); if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-373d7a9c", module.exports) } } /***/ }), /* 24 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', [_vm._v("2")]) } var staticRenderFns = [] render._withStripped = true /* harmony default export */ __webpack_exports__["a"] = ({ render: render, staticRenderFns: staticRenderFns }); if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-523584a1", module.exports) } } /***/ }), /* 25 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_template_compiler_index_id_data_v_61a6a1a5_node_modules_vue_loader_lib_selector_type_template_index_0_jp_vue__ = __webpack_require__(26); var disposed = false var normalizeComponent = __webpack_require__(11) /* script */ var __vue_script__ = null /* template */ /* styles */ var __vue_styles__ = null /* scopeId */ var __vue_scopeId__ = null /* moduleIdentifier (server only) */ var __vue_module_identifier__ = null var Component = normalizeComponent( __vue_script__, __WEBPACK_IMPORTED_MODULE_0__node_modules_vue_loader_lib_template_compiler_index_id_data_v_61a6a1a5_node_modules_vue_loader_lib_selector_type_template_index_0_jp_vue__["a" /* default */], __vue_styles__, __vue_scopeId__, __vue_module_identifier__ ) Component.options.__file = "myGit/vue/components/header/jp.vue" if (Component.esModule && Object.keys(Component.esModule).some(function (key) {return key !== "default" && key.substr(0, 2) !== "__"})) {console.error("named exports are not supported in *.vue files.")} if (Component.options.functional) {console.error("[vue-loader] jp.vue: functional components are not supported with templates, they should use render functions.")} /* hot reload */ if (false) {(function () { var hotAPI = require("vue-hot-reload-api") hotAPI.install(require("vue"), false) if (!hotAPI.compatible) return module.hot.accept() if (!module.hot.data) { hotAPI.createRecord("data-v-61a6a1a5", Component.options) } else { hotAPI.reload("data-v-61a6a1a5", Component.options) } module.hot.dispose(function (data) { disposed = true }) })()} /* harmony default export */ __webpack_exports__["default"] = (Component.exports); /***/ }), /* 26 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var render = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h; return _c('div', [_vm._v("3")]) } var staticRenderFns = [] render._withStripped = true /* harmony default export */ __webpack_exports__["a"] = ({ render: render, staticRenderFns: staticRenderFns }); if (false) { module.hot.accept() if (module.hot.data) { require("vue-hot-reload-api").rerender("data-v-61a6a1a5", module.exports) } } /***/ }), /* 27 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // // // /* harmony default export */ __webpack_exports__["a"] = ({}); /***/ }) /******/ ]);
appqian/vue
src/index.js
JavaScript
gpl-2.0
390,912
<?php /** * OG behavior handler. */ class OgBehaviorHandler extends EntityReference_BehaviorHandler_Abstract { /** * Implements EntityReference_BehaviorHandler_Abstract::access(). */ public function access($field, $instance) { return $field['settings']['handler'] == 'og' || strpos($field['settings']['handler'], 'og_') === 0; } /** * Implements EntityReference_BehaviorHandler_Abstract::load(). */ public function load($entity_type, $entities, $field, $instances, $langcode, &$items) { // Get the OG memberships from the field. $field_name = $field['field_name']; $target_type = $field['settings']['target_type']; foreach ($entities as $entity) { $wrapper = entity_metadata_wrapper($entity_type, $entity); if (empty($wrapper->{$field_name})) { // If the entity belongs to a bundle that was deleted, return early. continue; } $id = $wrapper->getIdentifier(); $items[$id] = array(); $gids = og_get_entity_groups($entity_type, $entity, array(), $field_name); if (empty($gids[$target_type])) { continue; } foreach ($gids[$target_type] as $gid) { $items[$id][] = array( 'target_id' => $gid, ); } } } /** * Implements EntityReference_BehaviorHandler_Abstract::insert(). */ public function insert($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!empty($entity->skip_og_membership)) { return; } $this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items); $items = array(); } /** * Implements EntityReference_BehaviorHandler_Abstract::access(). */ public function update($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!empty($entity->skip_og_membership)) { return; } $this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items); $items = array(); } /** * Implements EntityReference_BehaviorHandler_Abstract::Delete() * * CRUD memberships from field, or if entity is marked for deleteing, * delete all the OG membership related to it. * * @see og_entity_delete(). */ public function delete($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!empty($entity->skip_og_membership)) { return; } if (!empty($entity->delete_og_membership)) { // Delete all OG memberships related to this entity. $og_memberships = array(); foreach (og_get_entity_groups($entity_type, $entity) as $group_type => $ids) { $og_memberships = array_merge($og_memberships, array_keys($ids)); } if ($og_memberships) { og_membership_delete_multiple($og_memberships); } } else { $this->OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, $items); } } /** * Create, update or delete OG membership based on field values. */ public function OgMembershipCrud($entity_type, $entity, $field, $instance, $langcode, &$items) { if (!user_access('administer group') && !field_access('edit', $field, $entity_type, $entity)) { // User has no access to field. return; } if (!$diff = $this->groupAudiencegetDiff($entity_type, $entity, $field, $instance, $langcode, $items)) { return; } $field_name = $field['field_name']; $group_type = $field['settings']['target_type']; $diff += array('insert' => array(), 'delete' => array()); // Delete first, so we don't trigger cardinality errors. if ($diff['delete']) { og_membership_delete_multiple($diff['delete']); } if (!$diff['insert']) { return; } // Prepare an array with the membership state, if it was provided in the widget. $states = array(); foreach ($items as $item) { $gid = $item['target_id']; if (empty($item['state']) || !in_array($gid, $diff['insert'])) { // State isn't provided, or not an "insert" operation. continue; } $states[$gid] = $item['state']; } foreach ($diff['insert'] as $gid) { $values = array( 'entity_type' => $entity_type, 'entity' => $entity, 'field_name' => $field_name, ); if (!empty($states[$gid])) { $values['state'] = $states[$gid]; } og_group($group_type, $gid, $values); } } /** * Get the difference in group audience for a saved field. * * @return * Array with all the differences, or an empty array if none found. */ public function groupAudiencegetDiff($entity_type, $entity, $field, $instance, $langcode, $items) { $return = FALSE; $field_name = $field['field_name']; $wrapper = entity_metadata_wrapper($entity_type, $entity); $og_memberships = $wrapper->{$field_name . '__og_membership'}->value(); $new_memberships = array(); foreach ($items as $item) { $new_memberships[$item['target_id']] = TRUE; } foreach ($og_memberships as $og_membership) { $gid = $og_membership->gid; if (empty($new_memberships[$gid])) { // Membership was deleted. if ($og_membership->entity_type == 'user') { // Make sure this is not the group manager, if exists. $group = entity_load_single($og_membership->group_type, $og_membership->gid); if (!empty($group->uid) && $group->uid == $og_membership->etid) { continue; } } $return['delete'][] = $og_membership->id; unset($new_memberships[$gid]); } else { // Existing membership. unset($new_memberships[$gid]); } } if ($new_memberships) { // New memberships. $return['insert'] = array_keys($new_memberships); } return $return; } /** * Implements EntityReference_BehaviorHandler_Abstract::views_data_alter(). */ public function views_data_alter(&$data, $field) { // We need to override the default EntityReference table settings when OG // behavior is being used. if (og_is_group_audience_field($field['field_name'])) { $entity_types = array_keys($field['bundles']); // We need to join the base table for the entities // that this field is attached to. foreach ($entity_types as $entity_type) { $entity_info = entity_get_info($entity_type); $data['og_membership'] = array( 'table' => array( 'join' => array( $entity_info['base table'] => array( // Join entity base table on its id field with left_field. 'left_field' => $entity_info['entity keys']['id'], 'field' => 'etid', 'extra' => array( 0 => array( 'field' => 'entity_type', 'value' => $entity_type, ), ), ), ), ), // Copy the original config from the table definition. $field['field_name'] => $data['field_data_' . $field['field_name']][$field['field_name']], $field['field_name'] . '_target_id' => $data['field_data_' . $field['field_name']][$field['field_name'] . '_target_id'], ); // Change config with settings from og_membership table. foreach (array('filter', 'argument', 'sort') as $op) { $data['og_membership'][$field['field_name'] . '_target_id'][$op]['field'] = 'gid'; $data['og_membership'][$field['field_name'] . '_target_id'][$op]['table'] = 'og_membership'; unset($data['og_membership'][$field['field_name'] . '_target_id'][$op]['additional fields']); } } // Get rid of the original table configs. unset($data['field_data_' . $field['field_name']]); unset($data['field_revision_' . $field['field_name']]); } } /** * Implements EntityReference_BehaviorHandler_Abstract::validate(). * * Re-build $errors array to be keyed correctly by "default" and "admin" field * modes. * * @todo: Try to get the correct delta so we can highlight the invalid * reference. * * @see entityreference_field_validate(). */ public function validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) { $new_errors = array(); $values = array('default' => array(), 'admin' => array()); $item = reset($items); if (!empty($item['field_mode'])) { // This is a complex widget with "default" and "admin" field modes. foreach ($items as $item) { $values[$item['field_mode']][] = $item['target_id']; } } else { foreach ($items as $item) { if (!entityreference_field_is_empty($item, $field) && $item['target_id'] !== NULL) { $values['default'][] = $item['target_id']; } } } $field_name = $field['field_name']; foreach ($values as $field_mode => $ids) { if (!$ids) { continue; } if ($field_mode == 'admin' && !user_access('administer group')) { // No need to validate the admin, as the user has no access to it. continue; } $instance['field_mode'] = $field_mode; $valid_ids = entityreference_get_selection_handler($field, $instance, $entity_type, $entity)->validateReferencableEntities($ids); if ($invalid_entities = array_diff($ids, $valid_ids)) { foreach ($invalid_entities as $id) { $new_errors[$field_mode][] = array( 'error' => 'og_invalid_entity', 'message' => t('The referenced group (@type: @id) is invalid.', array('@type' => $field['settings']['target_type'], '@id' => $id)), ); } } } if ($new_errors) { og_field_widget_register_errors($field_name, $new_errors); // We throw an exception ourself, as we unset the $errors array. throw new FieldValidationException($new_errors); } // Errors for this field now handled, removing from the referenced array. unset($errors[$field_name]); } }
codifi/mukurtucms
sites/all/modules/contrib/og/plugins/entityreference/behavior/OgBehaviorHandler.class.php
PHP
gpl-2.0
10,070
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Spoodle class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. config.time_zone = 'Bern' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
ASE-2014/spoodle
config/application.rb
Ruby
gpl-2.0
954
using System; using System.Diagnostics; namespace Lumpn.Profiling { public sealed class Recorder { private readonly Stopwatch stopwatch = new Stopwatch(); private readonly string name; public Recorder(string name) { this.name = name; } public void Reset() { stopwatch.Reset(); } public void Begin() { stopwatch.Start(); } public void End() { stopwatch.Stop(); } public void Submit() { Profiler.AddSample(name, stopwatch.ElapsedTicks); } } }
lumpn/infinite-zelda
Lumpn.Profiling/Recorder.cs
C#
gpl-2.0
658
<?php /** * * */ /** * Import SQL data. * * @param string $args as the queries of sql data , you could use file get contents to read data args * @param string/array $tables_whitelist 'all' = all tables; array('tbl1',...) = only listet tables * @param string $dbhost database host * @param string $dbuser database user * @param string $dbpass database password * @param string $dbname database name * * @return string complete if complete */ function database_import( $args, $tables_whitelist, $dbhost, $dbuser, $dbpass, $dbname ) { // check mysqli extension installed if ( !function_exists('mysqli_connect') ) { die('This scripts need mysql extension to be running properly! Please resolve!'); } $mysqli = @new mysqli( $dbhost, $dbuser, $dbpass, $dbname ); if ( $mysqli->connect_error ) { print_r( $mysqli->connect_error ); return false; } // DROP all tables (be carefull...) $mysqli->query('SET foreign_key_checks = 0'); if ( $result = $mysqli->query("SHOW TABLES") ) { while ( $row = $result->fetch_array(MYSQLI_NUM) ) { if ( $tables_whitelist=='all' || in_array($row[0], (array)$tables_whitelist) ) { $mysqli->query('DROP TABLE IF EXISTS '.$row[0]); } } } $mysqli->query('SET foreign_key_checks = 1'); $querycount = 11; $queryerrors = ''; $lines = (array) $args; if ( is_string( $args ) ) { $lines = array( $args ) ; } if ( ! $lines ) { return 'cannot execute ' . $args; } $scriptfile = false; foreach ($lines as $line) { $line = trim( $line ); // if have -- comments add enters if (substr( $line, 0, 2 ) == '--') { $line = "\n" . $line; } if (substr( $line, 0, 2 ) != '--') { $scriptfile .= ' ' . $line; continue; } } $queries = explode( ';', $scriptfile ); foreach ($queries as $query) { $query = trim( $query ); ++$querycount; if ( $query == '' ) { continue; } if ( ! $mysqli->query( $query ) ) { $queryerrors .= 'Line ' . $querycount . ' - ' . $mysqli->error . '<br />'; continue; } } if ( $queryerrors ) { return 'There was an error on File: ' . $filename . '<br />' . $queryerrors; } if( $mysqli && ! $mysqli->error ) { @$mysqli->close(); } return 'Complete dumping database!'; } /** * Export SQL data. * * if directory writable will be make directory inside of directory if not exist, else will be die * * @param string directory, as the directory to put file * @param string $outname as file name just the name * @param string/array $tables_whitelist 'all' = all tables; array('tbl1',...) = only listet tables * @param string $dbhost database host * @param string $dbuser database user * @param string $dbpass database password * @param string $dbname database name * */ function database_backup( $directory, $outname, $tables_whitelist, $dbhost, $dbuser, $dbpass, $dbname ) { // check mysqli extension installed if ( !function_exists('mysqli_connect') ) { die('This scripts need mysql extension to be running properly! Please resolve!'); } $mysqli = @new mysqli($dbhost, $dbuser, $dbpass, $dbname); if ( $mysqli->connect_error ) { print_r( $mysqli->connect_error ); return false; } $dir = $directory; $result = '<p>Could not create backup directory on :'.$dir.' Please Please make sure you have set Directory on 755 or 777 for a while.</p>'; $res = true; if ( !is_dir( $dir ) ) { if( !@mkdir( $dir, 755 ) ) { $res = false; } } $n = 1; if ( $res ) { $name = $outname.'_'.date('Y-m-d-H-i-s'); $fullname = $dir.'/'.$name.'.sql'; # full structures if ( !$mysqli->error ) { $sql = "SHOW TABLES"; $show = $mysqli->query($sql); while ( $row = $show->fetch_array() ) { if ( $tables_whitelist=='all' || in_array($row[0], (array)$tables_whitelist) ) { $tables[] = $row[0]; } } if ( !empty( $tables ) ) { // Cycle through $return = ''; foreach ( $tables as $table ) { $result = $mysqli->query('SELECT * FROM '.$table); $num_fields = $result->field_count; $row2 = $mysqli->query('SHOW CREATE TABLE '.$table ); $row2 = $row2->fetch_row(); $return .= "\n -- --------------------------------------------------------- -- -- Table structure for table : `{$table}` -- -- --------------------------------------------------------- ".$row2[1].";\n"; for ($i = 0; $i < $num_fields; $i++) { $n = 1 ; while ( $row = $result->fetch_row() ) { if ( $n++ == 1 ) { # set the first statements $return .= " -- -- Dumping data for table `{$table}` -- "; /** * Get structural of fields each tables */ $array_field = array(); #reset ! important to resetting when loop while ( $field = $result->fetch_field() ) # get field { $array_field[] = '`'.$field->name.'`'; } $array_f[$table] = $array_field; // $array_f = $array_f; # endwhile $array_field = implode(', ', $array_f[$table]); #implode arrays $return .= "INSERT INTO `{$table}` ({$array_field}) VALUES\n("; } else { $return .= '('; } for ($j=0; $j<$num_fields; $j++) { $row[$j] = str_replace('\'','\'\'', preg_replace("/\n/","\\n", $row[$j] ) ); if ( isset( $row[$j] ) ) { $return .= is_numeric( $row[$j] ) ? $row[$j] : '\''.$row[$j].'\'' ; } else { $return.= '\'\''; } if ( $j<($num_fields-1) ) { $return.= ', '; } } $return.= "),\n"; } # check matching @preg_match("/\),\n/", $return, $match, false, -3); # check match if ( isset( $match[0] ) ) { $return = substr_replace( $return, ";\n", -2); } } $return .= "\n"; } $return = "-- --------------------------------------------------------- -- -- Simple SQL Dump -- -- -- Host Connection Info: ".$mysqli->host_info." -- Generation Time: ".date('F d, Y \a\t H:i A ( e )')." -- Server version: ".$mysqli->server_info." -- PHP Version: ".PHP_VERSION." -- -- ---------------------------------------------------------\n\n SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\"; SET time_zone = \"+00:00\"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; ".$return." /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;"; # end values result if( @file_put_contents( $fullname, $return ) ) { # 9 as compression levels $result = $name.'.sql'; # show the name } else { $result = '<p>Error when saving the export.</p>'; } } else { $result = '<p>Error when executing database query to export.</p>'.$mysqli->error; } } } else { $result = '<p>Wrong mysqli input</p>'; } if( $mysqli && ! $mysqli->error ) { @$mysqli->close(); } return $result; }
Vegvisir/Nami
tools/db/database.func.php
PHP
gpl-2.0
6,970
<?php /** * Uses the Porter Stemmer algorithm to find word roots. * * Adapted from Joomla com_finder component. * Based on the Porter stemmer algorithm: * <https://tartarus.org/martin/PorterStemmer/c.txt> * * @author Lee Garner <lee@leegarner.com> * @copyright Copyright (C) 2017 Lee Garner <lee@leegarner.com> * @copyright Copyright (C) 2005 - 2017 Open Source Matters, Inc. All rights reserved. * @package searcher * @version 0.0.1 * @license http://opensource.org/licenses/gpl-2.0.php * GNU Public License v2 or later * @filesource */ namespace Searcher; /** * Porter English stemmer class for the Finder indexer package. * * This class was adapted from one written by Richard Heyes. * See copyright and link information above. */ class StemmerPorter_en extends Stemmer { /** * Regex for matching a consonant. * @var string */ private static $regex_consonant = '(?:[bcdfghjklmnpqrstvwxz]|(?<=[aeiou])y|^y)'; /** * Regex for matching a vowel * @var string */ private static $regex_vowel = '(?:[aeiou]|(?<![aeiou])y)'; /** * Method to stem a token and return the root. * * @param string $token The token to stem. * @param string $lang The language of the token. * @return string The root token. */ public function stem($token, $lang='en') { global $_CONF; // Check if the token is long enough to merit stemming. if (strlen($token) <= self::$min_word_len) { return $token; } // Check if the language is English or All. /*if ($lang !== 'en' && $lang != '*') { return $token; }*/ // Stem the token if it is not in the cache. if (!isset($this->cache[$lang][$token])) { // Stem the token. $result = trim($token); $result = self::step1ab($result); $result = self::step1c($result); $result = self::step2($result); $result = self::step3($result); $result = self::step4($result); $result = self::step5($result); $result = trim($result); // Add the token to the cache. $this->cache[$lang][$token] = $result; } return $this->cache[$lang][$token]; } /** * step1ab() gets rid of plurals and -ed or -ing. e.g. * * caresses -> caress * ponies -> poni * ties -> ti * caress -> caress * cats -> cat * * feed -> feed * agreed -> agree * disabled -> disable * * matting -> mat * mating -> mate * meeting -> meet * milling -> mill * messing -> mess * meetings -> meet * * @param string $word The token to stem. * @return string */ private static function step1ab($word) { // Part a if (substr($word, -1) == 's') { self::replace($word, 'sses', 'ss') or self::replace($word, 'ies', 'i') or self::replace($word, 'ss', 'ss') or self::replace($word, 's', ''); } // Part b if (substr($word, -2, 1) != 'e' or !self::replace($word, 'eed', 'ee', 0)) { // First rule $v = self::$regex_vowel; // Words ending with ing and ed // Note use of && and OR, for precedence reasons if (preg_match("#$v+#", substr($word, 0, -3)) && self::replace($word, 'ing', '') or preg_match("#$v+#", substr($word, 0, -2)) && self::replace($word, 'ed', '')) { // If one of above two test successful if (!self::replace($word, 'at', 'ate') and !self::replace($word, 'bl', 'ble') and !self::replace($word, 'iz', 'ize')) { // Double consonant ending if (self::doubleConsonant($word) and substr($word, -2) != 'll' and substr($word, -2) != 'ss' and substr($word, -2) != 'zz') { $word = substr($word, 0, -1); } elseif (self::m($word) == 1 and self::cvc($word)) { $word .= 'e'; } } } } return $word; } /** * step1c() turns terminal y to i when there is another vowel in the stem. * * @param string $word The token to stem. * @return string */ private static function step1c($word) { $v = self::$regex_vowel; if (substr($word, -1) == 'y' && preg_match("#$v+#", substr($word, 0, -1))) { self::replace($word, 'y', 'i'); } return $word; } /** * step2() maps double suffices to single ones. so -izationi * ( = -ize plus -ation) maps to -ize etc. * Note that the string before the suffix must give m() > 0. * * @param string $word The token to stem. * @return string */ private static function step2($word) { switch (substr($word, -2, 1)) { case 'a': self::replace($word, 'ational', 'ate', 0) or self::replace($word, 'tional', 'tion', 0); break; case 'c': self::replace($word, 'enci', 'ence', 0) or self::replace($word, 'anci', 'ance', 0); break; case 'e': self::replace($word, 'izer', 'ize', 0); break; case 'g': self::replace($word, 'logi', 'log', 0); break; case 'l': self::replace($word, 'entli', 'ent', 0) or self::replace($word, 'ousli', 'ous', 0) or self::replace($word, 'alli', 'al', 0) or self::replace($word, 'bli', 'ble', 0) or self::replace($word, 'eli', 'e', 0); break; case 'o': self::replace($word, 'ization', 'ize', 0) or self::replace($word, 'ation', 'ate', 0) or self::replace($word, 'ator', 'ate', 0); break; case 's': self::replace($word, 'iveness', 'ive', 0) or self::replace($word, 'fulness', 'ful', 0) or self::replace($word, 'ousness', 'ous', 0) or self::replace($word, 'alism', 'al', 0); break; case 't': self::replace($word, 'biliti', 'ble', 0) or self::replace($word, 'aliti', 'al', 0) or self::replace($word, 'iviti', 'ive', 0); break; } return $word; } /** * step3() deals with -ic-, -full, -ness etc. similar strategy to step2. * * @param string $word The token to stem. * @return string */ private static function step3($word) { switch (substr($word, -2, 1)) { case 'a': self::replace($word, 'ical', 'ic', 0); break; case 's': self::replace($word, 'ness', '', 0); break; case 't': self::replace($word, 'icate', 'ic', 0) or self::replace($word, 'iciti', 'ic', 0); break; case 'u': self::replace($word, 'ful', '', 0); break; case 'v': self::replace($word, 'ative', '', 0); break; case 'z': self::replace($word, 'alize', 'al', 0); break; } return $word; } /** * step4() takes off -ant, -ence etc., in context <c>vcvc<v>. * * @param string $word The token to stem. * @return string */ private static function step4($word) { switch (substr($word, -2, 1)) { case 'a': self::replace($word, 'al', '', 1); break; case 'c': self::replace($word, 'ance', '', 1) or self::replace($word, 'ence', '', 1); break; case 'e': self::replace($word, 'er', '', 1); break; case 'i': self::replace($word, 'ic', '', 1); break; case 'l': self::replace($word, 'able', '', 1) or self::replace($word, 'ible', '', 1); break; case 'n': self::replace($word, 'ant', '', 1) or self::replace($word, 'ement', '', 1) or self::replace($word, 'ment', '', 1) or self::replace($word, 'ent', '', 1); break; case 'o': if (substr($word, -4) == 'tion' or substr($word, -4) == 'sion') { self::replace($word, 'ion', '', 1); } else { self::replace($word, 'ou', '', 1); } break; case 's': self::replace($word, 'ism', '', 1); break; case 't': self::replace($word, 'ate', '', 1) or self::replace($word, 'iti', '', 1); break; case 'u': self::replace($word, 'ous', '', 1); break; case 'v': self::replace($word, 'ive', '', 1); break; case 'z': self::replace($word, 'ize', '', 1); break; } return $word; } /** * step5() removes a final -e if m() > 1, and changes -ll to -l if m() > 1. * * @param string $word The token to stem. * @return string */ private static function step5($word) { // Part a if (substr($word, -1) == 'e') { if (self::m(substr($word, 0, -1)) > 1) { self::replace($word, 'e', ''); } elseif (self::m(substr($word, 0, -1)) == 1) { if (!self::cvc(substr($word, 0, -1))) { self::replace($word, 'e', ''); } } } // Part b if (self::m($word) > 1 and self::doubleConsonant($word) and substr($word, -1) == 'l') { $word = substr($word, 0, -1); } return $word; } /** * Replaces the first string with the second, at the end of the string. If * third arg is given, then the preceding string must match that m count * at least. * * @param string &$str String to check * @param string $check Ending to check for * @param string $repl Replacement string * @param integer $m Optional minimum number of m() to meet * * @return boolean Whether the $check string was at the end * of the $str string. True does not necessarily mean * that it was replaced. */ private static function replace(&$str, $check, $repl, $m = null) { $len = 0 - strlen($check); if (substr($str, $len) == $check) { $substr = substr($str, 0, $len); if (is_null($m) or self::m($substr) > $m) { $str = $substr . $repl; } return true; } return false; } /** * m() - measures the number of consonant sequences in $str. if c is * a consonant sequence and v a vowel sequence, and <..> indicates * arbitrary presence, * * <c><v> gives 0 * <c>vc<v> gives 1 * <c>vcvc<v> gives 2 * <c>vcvcvc<v> gives 3 * * @param string $str The string to return the m count for * @return integer The m count */ private static function m($str) { $c = self::$regex_consonant; $v = self::$regex_vowel; $str = preg_replace("#^$c+#", '', $str); $str = preg_replace("#$v+$#", '', $str); preg_match_all("#($v+$c+)#", $str, $matches); return count($matches[1]); } /** * Returns true/false as to whether the given string contains two * of the same consonant next to each other at the end of the string. * * @param string $str String to check * @return boolean Result */ private static function doubleConsonant($str) { $c = self::$regex_consonant; return preg_match("#$c{2}$#", $str, $matches) and $matches[0]{0} == $matches[0]{1}; } /** * Checks for ending CVC sequence where second C is not W, X or Y * * @param string $str String to check * @return boolean Result */ private static function cvc($str) { $c = self::$regex_consonant; $v = self::$regex_vowel; return preg_match("#($c$v$c)$#", $str, $matches) && strlen($matches[1]) == 3 && $matches[1]{2} != 'w' && $matches[1]{2} != 'x' && $matches[1]{2} != 'y'; } } ?>
glFusion/searcher
classes/stemmer/Porter_en.class.php
PHP
gpl-2.0
13,378
package ch.logixisland.anuto.view.game; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import java.util.List; import ch.logixisland.anuto.AnutoApplication; import ch.logixisland.anuto.GameFactory; import ch.logixisland.anuto.R; import ch.logixisland.anuto.business.tower.TowerControl; import ch.logixisland.anuto.business.tower.TowerInfo; import ch.logixisland.anuto.business.tower.TowerSelector; import ch.logixisland.anuto.entity.tower.TowerInfoValue; import ch.logixisland.anuto.entity.tower.TowerStrategy; import ch.logixisland.anuto.util.StringUtils; import ch.logixisland.anuto.view.AnutoFragment; public class TowerInfoFragment extends AnutoFragment implements View.OnClickListener, TowerSelector.TowerInfoView { private final TowerSelector mTowerSelector; private final TowerControl mTowerControl; private Handler mHandler; private TextView txt_level; private TextView[] txt_property = new TextView[5]; private TextView[] txt_property_text = new TextView[5]; private Button btn_strategy; private Button btn_lock_target; private Button btn_enhance; private Button btn_upgrade; private Button btn_sell; private boolean mVisible = true; public TowerInfoFragment() { GameFactory factory = AnutoApplication.getInstance().getGameFactory(); mTowerSelector = factory.getTowerSelector(); mTowerControl = factory.getTowerControl(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_tower_info, container, false); txt_level = (TextView) v.findViewById(R.id.txt_level); txt_property[0] = (TextView) v.findViewById(R.id.txt_property1); txt_property[1] = (TextView) v.findViewById(R.id.txt_property2); txt_property[2] = (TextView) v.findViewById(R.id.txt_property3); txt_property[3] = (TextView) v.findViewById(R.id.txt_property4); txt_property[4] = (TextView) v.findViewById(R.id.txt_property5); TextView txt_level_text = (TextView) v.findViewById(R.id.txt_level_text); txt_level_text.setText(getResources().getString(R.string.level) + ":"); txt_property_text[0] = (TextView) v.findViewById(R.id.txt_property_text1); txt_property_text[1] = (TextView) v.findViewById(R.id.txt_property_text2); txt_property_text[2] = (TextView) v.findViewById(R.id.txt_property_text3); txt_property_text[3] = (TextView) v.findViewById(R.id.txt_property_text4); txt_property_text[4] = (TextView) v.findViewById(R.id.txt_property_text5); btn_strategy = (Button) v.findViewById(R.id.btn_strategy); btn_lock_target = (Button) v.findViewById(R.id.btn_lock_target); btn_upgrade = (Button) v.findViewById(R.id.btn_upgrade); btn_enhance = (Button) v.findViewById(R.id.btn_enhance); btn_sell = (Button) v.findViewById(R.id.btn_sell); btn_strategy.setOnClickListener(this); btn_lock_target.setOnClickListener(this); btn_enhance.setOnClickListener(this); btn_upgrade.setOnClickListener(this); btn_sell.setOnClickListener(this); mHandler = new Handler(); return v; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); TowerInfo towerInfo = mTowerSelector.getTowerInfo(); if (towerInfo != null) { refresh(towerInfo); show(); } } @Override public void onAttach(Activity activity) { super.onAttach(activity); mTowerSelector.setTowerInfoView(this); hide(); } @Override public void onDetach() { super.onDetach(); mTowerSelector.setTowerInfoView(null); mHandler.removeCallbacksAndMessages(null); } @Override public void onClick(View v) { if (v == btn_strategy) { mTowerControl.cycleTowerStrategy(); } if (v == btn_lock_target) { mTowerControl.toggleLockTarget(); } if (v == btn_enhance) { mTowerControl.enhanceTower(); } if (v == btn_upgrade) { mTowerControl.upgradeTower(); } if (v == btn_sell) { mTowerControl.sellTower(); } } @Override public void showTowerInfo(final TowerInfo towerInfo) { mHandler.post(new Runnable() { @Override public void run() { show(); refresh(towerInfo); } }); } @Override public void hideTowerInfo() { mHandler.post(new Runnable() { @Override public void run() { hide(); } }); } private void show() { if (!mVisible) { updateMenuTransparency(); getFragmentManager().beginTransaction() .show(this) .commitAllowingStateLoss(); mVisible = true; } } private void hide() { if (mVisible) { getFragmentManager().beginTransaction() .hide(this) .commitAllowingStateLoss(); mVisible = false; } } private void refresh(TowerInfo towerInfo) { txt_level.setText(towerInfo.getLevel() + " / " + towerInfo.getLevelMax()); List<TowerInfoValue> properties = towerInfo.getProperties(); for (int i = 0; i < properties.size(); i++) { TowerInfoValue property = properties.get(i); txt_property_text[i].setText(getString(property.getTextId()) + ":"); txt_property[i].setText(StringUtils.formatSuffix(property.getValue())); } for (int i = properties.size(); i < txt_property.length; i++) { txt_property_text[i].setText(""); txt_property[i].setText(""); } if (towerInfo.getEnhanceCost() > 0) { btn_enhance.setText(StringUtils.formatSwitchButton( getString(R.string.enhance), StringUtils.formatSuffix(towerInfo.getEnhanceCost())) ); } else { btn_enhance.setText(getString(R.string.enhance)); } if (towerInfo.getUpgradeCost() > 0) { btn_upgrade.setText(StringUtils.formatSwitchButton( getString(R.string.upgrade), StringUtils.formatSuffix(towerInfo.getUpgradeCost())) ); } else { btn_upgrade.setText(getString(R.string.upgrade)); } btn_sell.setText(StringUtils.formatSwitchButton( getString(R.string.sell), StringUtils.formatSuffix(towerInfo.getValue())) ); btn_upgrade.setEnabled(towerInfo.isUpgradeable()); btn_enhance.setEnabled(towerInfo.isEnhanceable()); btn_sell.setEnabled(towerInfo.isSellable()); if (towerInfo.canLockTarget()) { btn_lock_target.setText(StringUtils.formatSwitchButton( getString(R.string.lock_target), StringUtils.formatBoolean(towerInfo.doesLockTarget(), getResources())) ); btn_lock_target.setEnabled(true); } else { btn_lock_target.setText(getString(R.string.lock_target)); btn_lock_target.setEnabled(false); } if (towerInfo.hasStrategy()) { btn_strategy.setText(StringUtils.formatSwitchButton( getString(R.string.strategy), getStrategyString(towerInfo.getStrategy())) ); btn_strategy.setEnabled(true); } else { btn_strategy.setText(getString(R.string.strategy)); btn_strategy.setEnabled(false); } } private String getStrategyString(TowerStrategy strategy) { switch (strategy) { case Closest: return getString(R.string.strategy_closest); case Weakest: return getString(R.string.strategy_weakest); case Strongest: return getString(R.string.strategy_strongest); case First: return getString(R.string.strategy_first); case Last: return getString(R.string.strategy_last); } throw new RuntimeException("Unknown strategy!"); } }
oojeiph/android-anuto
app/src/main/java/ch/logixisland/anuto/view/game/TowerInfoFragment.java
Java
gpl-2.0
8,699
<?php /** * Created by PhpStorm. * User: mglaman * Date: 9/2/15 * Time: 12:39 AM */ namespace mglaman\Docker; /** * Class Docker * @package mglaman\Docker */ class Docker extends DockerBase { /** * {@inheritdoc} */ public static function command() { return 'docker'; } /** * @return bool */ public static function exists() { return self::runCommand('-v')->isSuccessful(); } /** * @return bool * @throws \Exception */ public static function available() { return self::runCommand('ps')->isSuccessful(); } /** * @param $name * @param $port * @param string $protocol * * @return string */ public static function getContainerPort($name, $port, $protocol = 'tcp') { // Easier to run this than dig through JSON object. $cmd = self::runCommand('inspect', [ "--format='{{(index (index .NetworkSettings.Ports \"{$port}/{$protocol}\") 0).HostPort}}", $name ]); return preg_replace('/[^0-9,.]+/i', '', $cmd->getOutput()); } /** * Run a command in a new container. * * @param array $args * @param null $callback * @return \Symfony\Component\Process\Process * @throws \Exception */ public static function run(array $args, $callback = null) { return self::runCommand('run', $args, $callback); } /** * Start one or more stopped containers. * * @param array $args * @param null $callback * @return \Symfony\Component\Process\Process * @throws \Exception */ public static function start(array $args, $callback = null) { return self::runCommand('start', $args, $callback); } /** * Stop a running container. * * @param array $args * @param null $callback * @return \Symfony\Component\Process\Process * @throws \Exception */ public static function stop(array $args, $callback = null) { return self::runCommand('stop', $args, $callback); } /** * Removes a container. * * @param array $args * @param null $callback * * @return \Symfony\Component\Process\Process * @throws \Exception */ public static function rm(array $args, $callback = null) { return self::runCommand('rm', $args, $callback); } /** * Pull image or repository from registry. * * @param array $args * @param null $callback * * @return \Symfony\Component\Process\Process * @throws \Exception */ public static function pull(array $args, $callback = null) { return self::runCommand('pull', $args, $callback); } /** * Return low-level information on a container or image. * * @param array $args * @param bool|false $raw * @param null $callback * @return mixed|\Symfony\Component\Process\Process * @throws \Exception */ public static function inspect(array $args, $raw = false, $callback = null) { $process = self::runCommand('inspect', $args, $callback); if ($process->isSuccessful() && !$raw) { $decoded = json_decode($process->getOutput()); return reset($decoded); } return $process; } }
mglaman/docker-helper
src/Docker.php
PHP
gpl-2.0
3,379
/* * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.nodes.cfg; import com.oracle.graal.compiler.common.LocationIdentity; import com.oracle.graal.compiler.common.cfg.Loop; import com.oracle.graal.nodes.LoopBeginNode; public final class HIRLoop extends Loop<Block> { private LocationSet killLocations; protected HIRLoop(Loop<Block> parent, int index, Block header) { super(parent, index, header); } @Override public long numBackedges() { return ((LoopBeginNode) getHeader().getBeginNode()).loopEnds().count(); } public LocationSet getKillLocations() { if (killLocations == null) { killLocations = new LocationSet(); for (Block b : this.getBlocks()) { if (b.getLoop() == this) { killLocations.addAll(b.getKillLocations()); if (killLocations.isAny()) { break; } } } } for (Loop<Block> child : this.getChildren()) { if (killLocations.isAny()) { break; } killLocations.addAll(((HIRLoop) child).getKillLocations()); } return killLocations; } public boolean canKill(LocationIdentity location) { return getKillLocations().contains(location); } }
zapster/graal-core
graal/com.oracle.graal.nodes/src/com/oracle/graal/nodes/cfg/HIRLoop.java
Java
gpl-2.0
2,382
/**************************************************************************** ** ** 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 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 "qpainter.h" #include "qevent.h" #include "qdrawutil.h" #include "qapplication.h" #include "qabstractbutton.h" #include "qstyle.h" #include "qstyleoption.h" #include <limits.h> #include "qaction.h" #include "qclipboard.h" #include <qdebug.h> #include <qurl.h> #include "qlabel_p.h" #include "private/qstylesheetstyle_p.h" QT_BEGIN_NAMESPACE /*! \class QLabel \brief The QLabel widget provides a text or image display. \ingroup basicwidgets \ingroup text \mainclass QLabel is used for displaying text or an image. No user interaction functionality is provided. The visual appearance of the label can be configured in various ways, and it can be used for specifying a focus mnemonic key for another widget. A QLabel can contain any of the following content types: \table \header \o Content \o Setting \row \o Plain text \o Pass a QString to setText(). \row \o Rich text \o Pass a QString that contains rich text to setText(). \row \o A pixmap \o Pass a QPixmap to setPixmap(). \row \o A movie \o Pass a QMovie to setMovie(). \row \o A number \o Pass an \e int or a \e double to setNum(), which converts the number to plain text. \row \o Nothing \o The same as an empty plain text. This is the default. Set by clear(). \endtable When the content is changed using any of these functions, any previous content is cleared. By default, labels display \l{alignment}{left-aligned, vertically-centered} text and images, where any tabs in the text to be displayed are \l{Qt::TextExpandTabs}{automatically expanded}. However, the look of a QLabel can be adjusted and fine-tuned in several ways. The positioning of the content within the QLabel widget area can be tuned with setAlignment() and setIndent(). Text content can also wrap lines along word boundaries with setWordWrap(). For example, this code sets up a sunken panel with a two-line text in the bottom right corner (both lines being flush with the right side of the label): \snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 0 The properties and functions QLabel inherits from QFrame can also be used to specify the widget frame to be used for any given label. A QLabel is often used as a label for an interactive widget. For this use QLabel provides a useful mechanism for adding an mnemonic (see QKeySequence) that will set the keyboard focus to the other widget (called the QLabel's "buddy"). For example: \snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 1 In this example, keyboard focus is transferred to the label's buddy (the QLineEdit) when the user presses Alt+P. If the buddy was a button (inheriting from QAbstractButton), triggering the mnemonic would emulate a button click. \table 100% \row \o \inlineimage macintosh-label.png Screenshot of a Macintosh style label \o A label shown in the \l{Macintosh Style Widget Gallery}{Macintosh widget style}. \row \o \inlineimage plastique-label.png Screenshot of a Plastique style label \o A label shown in the \l{Plastique Style Widget Gallery}{Plastique widget style}. \row \o \inlineimage windowsxp-label.png Screenshot of a Windows XP style label \o A label shown in the \l{Windows XP Style Widget Gallery}{Windows XP widget style}. \endtable \sa QLineEdit, QTextEdit, QPixmap, QMovie, {fowler}{GUI Design Handbook: Label} */ #ifndef QT_NO_PICTURE /*! Returns the label's picture or 0 if the label doesn't have a picture. */ const QPicture *QLabel::picture() const { Q_D(const QLabel); return d->picture; } #endif /*! Constructs an empty label. The \a parent and widget flag \a f, arguments are passed to the QFrame constructor. \sa setAlignment(), setFrameStyle(), setIndent() */ QLabel::QLabel(QWidget *parent, Qt::WindowFlags f) : QFrame(*new QLabelPrivate(), parent, f) { Q_D(QLabel); d->init(); } /*! Constructs a label that displays the text, \a text. The \a parent and widget flag \a f, arguments are passed to the QFrame constructor. \sa setText(), setAlignment(), setFrameStyle(), setIndent() */ QLabel::QLabel(const QString &text, QWidget *parent, Qt::WindowFlags f) : QFrame(*new QLabelPrivate(), parent, f) { Q_D(QLabel); d->init(); setText(text); } #ifdef QT3_SUPPORT /*! \obsolete Constructs an empty label. The \a parent, \a name and widget flag \a f, arguments are passed to the QFrame constructor. \sa setAlignment(), setFrameStyle(), setIndent() */ QLabel::QLabel(QWidget *parent, const char *name, Qt::WindowFlags f) : QFrame(*new QLabelPrivate(), parent, f) { Q_D(QLabel); if (name) setObjectName(QString::fromAscii(name)); d->init(); } /*! \obsolete Constructs a label that displays the text, \a text. The \a parent, \a name and widget flag \a f, arguments are passed to the QFrame constructor. \sa setText(), setAlignment(), setFrameStyle(), setIndent() */ QLabel::QLabel(const QString &text, QWidget *parent, const char *name, Qt::WindowFlags f) : QFrame(*new QLabelPrivate(), parent, f) { Q_D(QLabel); if (name) setObjectName(QString::fromAscii(name)); d->init(); setText(text); } /*! \obsolete Constructs a label that displays the text \a text. The label has a buddy widget, \a buddy. If the \a text contains an underlined letter (a letter preceded by an ampersand, \&), when the user presses Alt+ the underlined letter, focus is passed to the buddy widget. The \a parent, \a name and widget flag, \a f, arguments are passed to the QFrame constructor. \sa setText(), setBuddy(), setAlignment(), setFrameStyle(), setIndent() */ QLabel::QLabel(QWidget *buddy, const QString &text, QWidget *parent, const char *name, Qt::WindowFlags f) : QFrame(*new QLabelPrivate(), parent, f) { Q_D(QLabel); if (name) setObjectName(QString::fromAscii(name)); d->init(); #ifndef QT_NO_SHORTCUT setBuddy(buddy); #endif setText(text); } #endif //QT3_SUPPORT /*! Destroys the label. */ QLabel::~QLabel() { Q_D(QLabel); d->clearContents(); } void QLabelPrivate::init() { Q_Q(QLabel); valid_hints = false; margin = 0; #ifndef QT_NO_MOVIE movie = 0; #endif #ifndef QT_NO_SHORTCUT shortcutId = 0; #endif pixmap = 0; scaledpixmap = 0; cachedimage = 0; #ifndef QT_NO_PICTURE picture = 0; #endif align = Qt::AlignLeft | Qt::AlignVCenter | Qt::TextExpandTabs; indent = -1; scaledcontents = false; textLayoutDirty = false; textDirty = false; textformat = Qt::AutoText; control = 0; textInteractionFlags = Qt::LinksAccessibleByMouse; isRichText = false; isTextLabel = false; q->setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred, QSizePolicy::Label)); #ifndef QT_NO_CURSOR validCursor = false; onAnchor = false; #endif openExternalLinks = false; setLayoutItemMargins(QStyle::SE_LabelLayoutItem); } /*! \property QLabel::text \brief the label's text If no text has been set this will return an empty string. Setting the text clears any previous content. The text will be interpreted either as plain text or as rich text, depending on the text format setting; see setTextFormat(). The default setting is Qt::AutoText; i.e. QLabel will try to auto-detect the format of the text set. If a buddy has been set, the buddy mnemonic key is updated from the new text. Note that QLabel is well-suited to display small rich text documents, such as small documents that get their document specific settings (font, text color, link color) from the label's palette and font properties. For large documents, use QTextEdit in read-only mode instead. QTextEdit can also provide a scroll bar when necessary. \note This function enables mouse tracking if \a text contains rich text. \sa setTextFormat(), setBuddy(), alignment */ void QLabel::setText(const QString &text) { Q_D(QLabel); if (d->text == text) return; QTextControl *oldControl = d->control; d->control = 0; d->clearContents(); d->text = text; d->isTextLabel = true; d->textDirty = true; d->isRichText = d->textformat == Qt::RichText || (d->textformat == Qt::AutoText && Qt::mightBeRichText(d->text)); d->control = oldControl; if (d->needTextControl()) { d->ensureTextControl(); } else { delete d->control; d->control = 0; } if (d->isRichText) { setMouseTracking(true); } else { // Note: mouse tracking not disabled intentionally } #ifndef QT_NO_SHORTCUT if (d->buddy) d->updateShortcut(); #endif d->updateLabel(); } QString QLabel::text() const { Q_D(const QLabel); return d->text; } /*! Clears any label contents. */ void QLabel::clear() { Q_D(QLabel); d->clearContents(); d->updateLabel(); } /*! \property QLabel::pixmap \brief the label's pixmap If no pixmap has been set this will return 0. Setting the pixmap clears any previous content. The buddy shortcut, if any, is disabled. */ void QLabel::setPixmap(const QPixmap &pixmap) { Q_D(QLabel); if (!d->pixmap || d->pixmap->cacheKey() != pixmap.cacheKey()) { d->clearContents(); d->pixmap = new QPixmap(pixmap); } if (d->pixmap->depth() == 1 && !d->pixmap->mask()) d->pixmap->setMask(*((QBitmap *)d->pixmap)); d->updateLabel(); } const QPixmap *QLabel::pixmap() const { Q_D(const QLabel); return d->pixmap; } #ifndef QT_NO_PICTURE /*! Sets the label contents to \a picture. Any previous content is cleared. The buddy shortcut, if any, is disabled. \sa picture(), setBuddy() */ void QLabel::setPicture(const QPicture &picture) { Q_D(QLabel); d->clearContents(); d->picture = new QPicture(picture); d->updateLabel(); } #endif // QT_NO_PICTURE /*! Sets the label contents to plain text containing the textual representation of integer \a num. Any previous content is cleared. Does nothing if the integer's string representation is the same as the current contents of the label. The buddy shortcut, if any, is disabled. \sa setText(), QString::setNum(), setBuddy() */ void QLabel::setNum(int num) { QString str; str.setNum(num); setText(str); } /*! \overload Sets the label contents to plain text containing the textual representation of double \a num. Any previous content is cleared. Does nothing if the double's string representation is the same as the current contents of the label. The buddy shortcut, if any, is disabled. \sa setText(), QString::setNum(), setBuddy() */ void QLabel::setNum(double num) { QString str; str.setNum(num); setText(str); } /*! \property QLabel::alignment \brief the alignment of the label's contents By default, the contents of the label are left-aligned and vertically-centered. \sa text */ void QLabel::setAlignment(Qt::Alignment alignment) { Q_D(QLabel); if (alignment == (d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask))) return; d->align = (d->align & ~(Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask)) | (alignment & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask)); d->updateLabel(); } #ifdef QT3_SUPPORT /*! Use setAlignment(Qt::Alignment) instead. If \a alignment specifies text flags as well, use setTextFormat() to set those. */ void QLabel::setAlignment(int alignment) { Q_D(QLabel); d->align = alignment & ~(Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask|Qt::TextWordWrap); setAlignment(Qt::Alignment(QFlag(alignment))); } #endif Qt::Alignment QLabel::alignment() const { Q_D(const QLabel); return QFlag(d->align & (Qt::AlignVertical_Mask|Qt::AlignHorizontal_Mask)); } /*! \property QLabel::wordWrap \brief the label's word-wrapping policy If this property is true then label text is wrapped where necessary at word-breaks; otherwise it is not wrapped at all. By default, word wrap is disabled. \sa text */ void QLabel::setWordWrap(bool on) { Q_D(QLabel); if (on) d->align |= Qt::TextWordWrap; else d->align &= ~Qt::TextWordWrap; d->updateLabel(); } bool QLabel::wordWrap() const { Q_D(const QLabel); return d->align & Qt::TextWordWrap; } /*! \property QLabel::indent \brief the label's text indent in pixels If a label displays text, the indent applies to the left edge if alignment() is Qt::AlignLeft, to the right edge if alignment() is Qt::AlignRight, to the top edge if alignment() is Qt::AlignTop, and to to the bottom edge if alignment() is Qt::AlignBottom. If indent is negative, or if no indent has been set, the label computes the effective indent as follows: If frameWidth() is 0, the effective indent becomes 0. If frameWidth() is greater than 0, the effective indent becomes half the width of the "x" character of the widget's current font(). By default, the indent is -1, meaning that an effective indent is calculating in the manner described above. \sa alignment, margin, frameWidth(), font() */ void QLabel::setIndent(int indent) { Q_D(QLabel); d->indent = indent; d->updateLabel(); } int QLabel::indent() const { Q_D(const QLabel); return d->indent; } /*! \property QLabel::margin \brief the width of the margin The margin is the distance between the innermost pixel of the frame and the outermost pixel of contents. The default margin is 0. \sa indent */ int QLabel::margin() const { Q_D(const QLabel); return d->margin; } void QLabel::setMargin(int margin) { Q_D(QLabel); if (d->margin == margin) return; d->margin = margin; d->updateLabel(); } /*! Returns the size that will be used if the width of the label is \a w. If \a w is -1, the sizeHint() is returned. If \a w is 0 minimumSizeHint() is returned */ QSize QLabelPrivate::sizeForWidth(int w) const { Q_Q(const QLabel); if(q->minimumWidth() > 0) w = qMax(w, q->minimumWidth()); QSize contentsMargin(leftmargin + rightmargin, topmargin + bottommargin); QRect br; int hextra = 2 * margin; int vextra = hextra; QFontMetrics fm = q->fontMetrics(); if (pixmap && !pixmap->isNull()) br = pixmap->rect(); #ifndef QT_NO_PICTURE else if (picture && !picture->isNull()) br = picture->boundingRect(); #endif #ifndef QT_NO_MOVIE else if (movie && !movie->currentPixmap().isNull()) br = movie->currentPixmap().rect(); #endif else if (isTextLabel) { int align = QStyle::visualAlignment(q->layoutDirection(), QFlag(this->align)); // Add indentation int m = indent; if (m < 0 && q->frameWidth()) // no indent, but we do have a frame m = fm.width(QLatin1Char('x')) - margin*2; if (m > 0) { if ((align & Qt::AlignLeft) || (align & Qt::AlignRight)) hextra += m; if ((align & Qt::AlignTop) || (align & Qt::AlignBottom)) vextra += m; } if (control) { ensureTextLayouted(); const qreal oldTextWidth = control->textWidth(); // Calculate the length of document if w is the width if (align & Qt::TextWordWrap) { if (w >= 0) { w = qMax(w-hextra-contentsMargin.width(), 0); // strip margin and indent control->setTextWidth(w); } else { control->adjustSize(); } } else { control->setTextWidth(-1); } br = QRect(QPoint(0, 0), control->size().toSize()); // restore state control->setTextWidth(oldTextWidth); } else { // Turn off center alignment in order to avoid rounding errors for centering, // since centering involves a division by 2. At the end, all we want is the size. int flags = align & ~(Qt::AlignVCenter | Qt::AlignHCenter); if (hasShortcut) { flags |= Qt::TextShowMnemonic; QStyleOption opt; opt.initFrom(q); if (!q->style()->styleHint(QStyle::SH_UnderlineShortcut, &opt, q)) flags |= Qt::TextHideMnemonic; } bool tryWidth = (w < 0) && (align & Qt::TextWordWrap); if (tryWidth) w = fm.averageCharWidth() * 80; else if (w < 0) w = 2000; w -= (hextra + contentsMargin.width()); br = fm.boundingRect(0, 0, w ,2000, flags, text); if (tryWidth && br.height() < 4*fm.lineSpacing() && br.width() > w/2) br = fm.boundingRect(0, 0, w/2, 2000, flags, text); if (tryWidth && br.height() < 2*fm.lineSpacing() && br.width() > w/4) br = fm.boundingRect(0, 0, w/4, 2000, flags, text); } } else { br = QRect(QPoint(0, 0), QSize(fm.averageCharWidth(), fm.lineSpacing())); } const QSize contentsSize(br.width() + hextra, br.height() + vextra); return (contentsSize + contentsMargin).expandedTo(q->minimumSize()); } /*! \reimp */ int QLabel::heightForWidth(int w) const { Q_D(const QLabel); if (d->isTextLabel) return d->sizeForWidth(w).height(); return QWidget::heightForWidth(w); } /*! \property QLabel::openExternalLinks \since 4.2 Specifies whether QLabel should automatically open links using QDesktopServices::openUrl() instead of emitting the linkActivated() signal. \bold{Note:} The textInteractionFlags set on the label need to include either LinksAccessibleByMouse or LinksAccessibleByKeyboard. The default value is false. \sa textInteractionFlags() */ bool QLabel::openExternalLinks() const { Q_D(const QLabel); return d->openExternalLinks; } void QLabel::setOpenExternalLinks(bool open) { Q_D(QLabel); d->openExternalLinks = open; if (d->control) d->control->setOpenExternalLinks(open); } /*! \property QLabel::textInteractionFlags \since 4.2 Specifies how the label should interact with user input if it displays text. If the flags contain Qt::LinksAccessibleByKeyboard the focus policy is also automatically set to Qt::StrongFocus. If Qt::TextSelectableByKeyboard is set then the focus policy is set to Qt::ClickFocus. The default value is Qt::LinksAccessibleByMouse. */ void QLabel::setTextInteractionFlags(Qt::TextInteractionFlags flags) { Q_D(QLabel); if (d->textInteractionFlags == flags) return; d->textInteractionFlags = flags; if (flags & Qt::LinksAccessibleByKeyboard) setFocusPolicy(Qt::StrongFocus); else if (flags & (Qt::TextSelectableByKeyboard | Qt::TextSelectableByMouse)) setFocusPolicy(Qt::ClickFocus); else setFocusPolicy(Qt::NoFocus); if (d->needTextControl()) { d->ensureTextControl(); } else { delete d->control; d->control = 0; } if (d->control) d->control->setTextInteractionFlags(d->textInteractionFlags); } Qt::TextInteractionFlags QLabel::textInteractionFlags() const { Q_D(const QLabel); return d->textInteractionFlags; } /*!\reimp */ QSize QLabel::sizeHint() const { Q_D(const QLabel); if (!d->valid_hints) (void) QLabel::minimumSizeHint(); return d->sh; } /*! \reimp */ QSize QLabel::minimumSizeHint() const { Q_D(const QLabel); if (d->valid_hints) { if (d->sizePolicy == sizePolicy()) return d->msh; } ensurePolished(); d->valid_hints = true; d->sh = d->sizeForWidth(-1); // wrap ? golden ratio : min doc size QSize msh(-1, -1); if (!d->isTextLabel) { msh = d->sh; } else { msh.rheight() = d->sizeForWidth(QWIDGETSIZE_MAX).height(); // height for one line msh.rwidth() = d->sizeForWidth(0).width(); // wrap ? size of biggest word : min doc size if (d->sh.height() < msh.height()) msh.rheight() = d->sh.height(); } d->msh = msh; d->sizePolicy = sizePolicy(); return msh; } /*!\reimp */ void QLabel::mousePressEvent(QMouseEvent *ev) { Q_D(QLabel); d->sendControlEvent(ev); } /*!\reimp */ void QLabel::mouseMoveEvent(QMouseEvent *ev) { Q_D(QLabel); d->sendControlEvent(ev); } /*!\reimp */ void QLabel::mouseReleaseEvent(QMouseEvent *ev) { Q_D(QLabel); d->sendControlEvent(ev); } /*!\reimp */ void QLabel::contextMenuEvent(QContextMenuEvent *ev) { #ifdef QT_NO_CONTEXTMENU Q_UNUSED(ev); #else Q_D(QLabel); if (!d->isTextLabel) { ev->ignore(); return; } QMenu *menu = d->createStandardContextMenu(ev->pos()); if (!menu) { ev->ignore(); return; } ev->accept(); menu->exec(ev->globalPos()); delete menu; #endif } /*! \reimp */ void QLabel::focusInEvent(QFocusEvent *ev) { Q_D(QLabel); if (d->isTextLabel) { d->ensureTextControl(); d->sendControlEvent(ev); } QFrame::focusInEvent(ev); } /*! \reimp */ void QLabel::focusOutEvent(QFocusEvent *ev) { Q_D(QLabel); d->sendControlEvent(ev); QFrame::focusOutEvent(ev); } /*!\reimp */ bool QLabel::focusNextPrevChild(bool next) { Q_D(QLabel); if (d->control && d->control->setFocusToNextOrPreviousAnchor(next)) return true; return QFrame::focusNextPrevChild(next); } /*!\reimp */ void QLabel::keyPressEvent(QKeyEvent *ev) { Q_D(QLabel); d->sendControlEvent(ev); } /*!\reimp */ bool QLabel::event(QEvent *e) { Q_D(QLabel); QEvent::Type type = e->type(); #ifndef QT_NO_SHORTCUT if (type == QEvent::Shortcut) { QShortcutEvent *se = static_cast<QShortcutEvent *>(e); if (se->shortcutId() == d->shortcutId) { QWidget * w = d->buddy; QAbstractButton *button = qobject_cast<QAbstractButton *>(w); if (w->focusPolicy() != Qt::NoFocus) w->setFocus(Qt::ShortcutFocusReason); if (button && !se->isAmbiguous()) button->animateClick(); else window()->setAttribute(Qt::WA_KeyboardFocusChange); return true; } } else #endif if (type == QEvent::Resize) { if (d->control) d->textLayoutDirty = true; } else if (e->type() == QEvent::StyleChange #ifdef Q_WS_MAC || e->type() == QEvent::MacSizeChange #endif ) { d->setLayoutItemMargins(QStyle::SE_LabelLayoutItem); d->updateLabel(); } return QFrame::event(e); } /*!\reimp */ void QLabel::paintEvent(QPaintEvent *) { Q_D(QLabel); QStyle *style = QWidget::style(); QPainter painter(this); drawFrame(&painter); QRect cr = contentsRect(); cr.adjust(d->margin, d->margin, -d->margin, -d->margin); int align = QStyle::visualAlignment(layoutDirection(), QFlag(d->align)); #ifndef QT_NO_MOVIE if (d->movie) { if (d->scaledcontents) style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap().scaled(cr.size())); else style->drawItemPixmap(&painter, cr, align, d->movie->currentPixmap()); } else #endif if (d->isTextLabel) { QRectF lr = d->layoutRect(); if (d->control) { #ifndef QT_NO_SHORTCUT const bool underline = (bool)style->styleHint(QStyle::SH_UnderlineShortcut, 0, this, 0); if (d->shortcutId != 0 && underline != d->shortcutCursor.charFormat().fontUnderline()) { QTextCharFormat fmt; fmt.setFontUnderline(underline); d->shortcutCursor.mergeCharFormat(fmt); } #endif d->ensureTextLayouted(); QAbstractTextDocumentLayout::PaintContext context; QStyleOption opt(0); opt.init(this); if (!isEnabled() && style->styleHint(QStyle::SH_EtchDisabledText, &opt, this)) { context.palette = palette(); context.palette.setColor(QPalette::Text, context.palette.light().color()); painter.save(); painter.translate(lr.x() + 1, lr.y() + 1); painter.setClipRect(lr.translated(-lr.x() - 1, -lr.y() - 1)); QAbstractTextDocumentLayout *layout = d->control->document()->documentLayout(); layout->draw(&painter, context); painter.restore(); } // Adjust the palette context.palette = palette(); #ifndef QT_NO_STYLE_STYLESHEET if (QStyleSheetStyle* cssStyle = qobject_cast<QStyleSheetStyle*>(style)) { cssStyle->focusPalette(this, &opt, &context.palette); } #endif if (foregroundRole() != QPalette::Text && isEnabled()) context.palette.setColor(QPalette::Text, context.palette.color(foregroundRole())); painter.save(); painter.translate(lr.topLeft()); painter.setClipRect(lr.translated(-lr.x(), -lr.y())); d->control->setPalette(context.palette); d->control->drawContents(&painter, QRectF(), this); painter.restore(); } else { int flags = align; if (d->hasShortcut) { flags |= Qt::TextShowMnemonic; QStyleOption opt; opt.initFrom(this); if (!style->styleHint(QStyle::SH_UnderlineShortcut, &opt, this)) flags |= Qt::TextHideMnemonic; } style->drawItemText(&painter, lr.toRect(), flags, palette(), isEnabled(), d->text, foregroundRole()); } } else #ifndef QT_NO_PICTURE if (d->picture) { QRect br = d->picture->boundingRect(); int rw = br.width(); int rh = br.height(); if (d->scaledcontents) { painter.save(); painter.translate(cr.x(), cr.y()); painter.scale((double)cr.width()/rw, (double)cr.height()/rh); painter.drawPicture(-br.x(), -br.y(), *d->picture); painter.restore(); } else { int xo = 0; int yo = 0; if (align & Qt::AlignVCenter) yo = (cr.height()-rh)/2; else if (align & Qt::AlignBottom) yo = cr.height()-rh; if (align & Qt::AlignRight) xo = cr.width()-rw; else if (align & Qt::AlignHCenter) xo = (cr.width()-rw)/2; painter.drawPicture(cr.x()+xo-br.x(), cr.y()+yo-br.y(), *d->picture); } } else #endif if (d->pixmap && !d->pixmap->isNull()) { QPixmap pix; if (d->scaledcontents) { if (!d->scaledpixmap || d->scaledpixmap->size() != cr.size()) { if (!d->cachedimage) d->cachedimage = new QImage(d->pixmap->toImage()); delete d->scaledpixmap; d->scaledpixmap = new QPixmap(QPixmap::fromImage(d->cachedimage->scaled(cr.size(),Qt::IgnoreAspectRatio,Qt::SmoothTransformation))); } pix = *d->scaledpixmap; } else pix = *d->pixmap; QStyleOption opt; opt.initFrom(this); if (!isEnabled()) pix = style->generatedIconPixmap(QIcon::Disabled, pix, &opt); style->drawItemPixmap(&painter, cr, align, pix); } } /*! Updates the label, but not the frame. */ void QLabelPrivate::updateLabel() { Q_Q(QLabel); valid_hints = false; if (isTextLabel) { QSizePolicy policy = q->sizePolicy(); const bool wrap = align & Qt::TextWordWrap; policy.setHeightForWidth(wrap); if (policy != q->sizePolicy()) // ### should be replaced by WA_WState_OwnSizePolicy idiom q->setSizePolicy(policy); textLayoutDirty = true; } q->updateGeometry(); q->update(q->contentsRect()); } #ifndef QT_NO_SHORTCUT /*! Sets this label's buddy to \a buddy. When the user presses the shortcut key indicated by this label, the keyboard focus is transferred to the label's buddy widget. The buddy mechanism is only available for QLabels that contain text in which one character is prefixed with an ampersand, '&'. This character is set as the shortcut key. See the \l QKeySequence::mnemonic() documentation for details (to display an actual ampersand, use '&&'). In a dialog, you might create two data entry widgets and a label for each, and set up the geometry layout so each label is just to the left of its data entry widget (its "buddy"), for example: \snippet doc/src/snippets/code/src_gui_widgets_qlabel.cpp 2 With the code above, the focus jumps to the Name field when the user presses Alt+N, and to the Phone field when the user presses Alt+P. To unset a previously set buddy, call this function with \a buddy set to 0. \sa buddy(), setText(), QShortcut, setAlignment() */ void QLabel::setBuddy(QWidget *buddy) { Q_D(QLabel); d->buddy = buddy; if (d->isTextLabel) { if (d->shortcutId) releaseShortcut(d->shortcutId); d->shortcutId = 0; d->textDirty = true; if (buddy) d->updateShortcut(); // grab new shortcut d->updateLabel(); } } /*! Returns this label's buddy, or 0 if no buddy is currently set. \sa setBuddy() */ QWidget * QLabel::buddy() const { Q_D(const QLabel); return d->buddy; } void QLabelPrivate::updateShortcut() { Q_Q(QLabel); Q_ASSERT(shortcutId == 0); // Introduce an extra boolean to indicate the presence of a shortcut in the // text. We cannot use the shortcutId itself because on the mac mnemonics are // off by default, so QKeySequence::mnemonic always returns an empty sequence. // But then we do want to hide the ampersands, so we can't use shortcutId. hasShortcut = false; if (control) { ensureTextPopulated(); // Underline the first character that follows an ampersand shortcutCursor = control->document()->find(QLatin1String("&")); if (shortcutCursor.isNull()) return; hasShortcut = true; shortcutId = q->grabShortcut(QKeySequence::mnemonic(text)); shortcutCursor.deleteChar(); // remove the ampersand shortcutCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); } else { if (!text.contains(QLatin1String("&"))) return; hasShortcut = true; shortcutId = q->grabShortcut(QKeySequence::mnemonic(text)); } } #endif // QT_NO_SHORTCUT #ifndef QT_NO_MOVIE void QLabelPrivate::_q_movieUpdated(const QRect& rect) { Q_Q(QLabel); if (movie && movie->isValid()) { QRect r; if (scaledcontents) { QRect cr = q->contentsRect(); QRect pixmapRect(cr.topLeft(), movie->currentPixmap().size()); if (pixmapRect.isEmpty()) return; r.setRect(cr.left(), cr.top(), (rect.width() * cr.width()) / pixmapRect.width(), (rect.height() * cr.height()) / pixmapRect.height()); } else { r = q->style()->itemPixmapRect(q->contentsRect(), align, movie->currentPixmap()); r.translate(rect.x(), rect.y()); r.setWidth(qMin(r.width(), rect.width())); r.setHeight(qMin(r.height(), rect.height())); } q->update(r); } } void QLabelPrivate::_q_movieResized(const QSize& size) { Q_Q(QLabel); q->update(); //we need to refresh the whole background in case the new size is smaler valid_hints = false; _q_movieUpdated(QRect(QPoint(0,0), size)); q->updateGeometry(); } /*! Sets the label contents to \a movie. Any previous content is cleared. The label does NOT take ownership of the movie. The buddy shortcut, if any, is disabled. \sa movie(), setBuddy() */ void QLabel::setMovie(QMovie *movie) { Q_D(QLabel); d->clearContents(); if (!movie) return; d->movie = movie; connect(movie, SIGNAL(resized(QSize)), this, SLOT(_q_movieResized(QSize))); connect(movie, SIGNAL(updated(QRect)), this, SLOT(_q_movieUpdated(QRect))); // Assume that if the movie is running, // resize/update signals will come soon enough if (movie->state() != QMovie::Running) d->updateLabel(); } #endif // QT_NO_MOVIE /*! \internal Clears any contents, without updating/repainting the label. */ void QLabelPrivate::clearContents() { delete control; control = 0; isTextLabel = false; hasShortcut = false; #ifndef QT_NO_PICTURE delete picture; picture = 0; #endif delete scaledpixmap; scaledpixmap = 0; delete cachedimage; cachedimage = 0; delete pixmap; pixmap = 0; text.clear(); Q_Q(QLabel); #ifndef QT_NO_SHORTCUT if (shortcutId) q->releaseShortcut(shortcutId); shortcutId = 0; #endif #ifndef QT_NO_MOVIE if (movie) { QObject::disconnect(movie, SIGNAL(resized(QSize)), q, SLOT(_q_movieResized(QSize))); QObject::disconnect(movie, SIGNAL(updated(QRect)), q, SLOT(_q_movieUpdated(QRect))); } movie = 0; #endif #ifndef QT_NO_CURSOR if (onAnchor) { if (validCursor) q->setCursor(cursor); else q->unsetCursor(); } validCursor = false; onAnchor = false; #endif } #ifndef QT_NO_MOVIE /*! Returns a pointer to the label's movie, or 0 if no movie has been set. \sa setMovie() */ QMovie *QLabel::movie() const { Q_D(const QLabel); return d->movie; } #endif // QT_NO_MOVIE /*! \property QLabel::textFormat \brief the label's text format See the Qt::TextFormat enum for an explanation of the possible options. The default format is Qt::AutoText. \sa text() */ Qt::TextFormat QLabel::textFormat() const { Q_D(const QLabel); return d->textformat; } void QLabel::setTextFormat(Qt::TextFormat format) { Q_D(QLabel); if (format != d->textformat) { d->textformat = format; QString t = d->text; if (!t.isNull()) { d->text.clear(); setText(t); } } } /*! \reimp */ void QLabel::changeEvent(QEvent *ev) { Q_D(QLabel); if(ev->type() == QEvent::FontChange || ev->type() == QEvent::ApplicationFontChange) { if (d->isTextLabel) { if (d->control) d->control->document()->setDefaultFont(font()); d->updateLabel(); } } else if (ev->type() == QEvent::PaletteChange && d->control) { d->control->setPalette(palette()); } else if (ev->type() == QEvent::ContentsRectChange) { d->updateLabel(); } else if (ev->type() == QEvent::LayoutDirectionChange) { if (d->isTextLabel && d->control) { d->sendControlEvent(ev); } } QFrame::changeEvent(ev); } /*! \property QLabel::scaledContents \brief whether the label will scale its contents to fill all available space. When enabled and the label shows a pixmap, it will scale the pixmap to fill the available space. This property's default is false. */ bool QLabel::hasScaledContents() const { Q_D(const QLabel); return d->scaledcontents; } void QLabel::setScaledContents(bool enable) { Q_D(QLabel); if ((bool)d->scaledcontents == enable) return; d->scaledcontents = enable; if (!enable) { delete d->scaledpixmap; d->scaledpixmap = 0; delete d->cachedimage; d->cachedimage = 0; } update(contentsRect()); } /*! \fn void QLabel::setAlignment(Qt::AlignmentFlag flag) \internal Without this function, a call to e.g. setAlignment(Qt::AlignTop) results in the \c QT3_SUPPORT function setAlignment(int) being called, rather than setAlignment(Qt::Alignment). */ // Returns the rect that is available for us to draw the document QRect QLabelPrivate::documentRect() const { Q_Q(const QLabel); Q_ASSERT_X(isTextLabel, "documentRect", "document rect called for label that is not a text label!"); QRect cr = q->contentsRect(); cr.adjust(margin, margin, -margin, -margin); const int align = QStyle::visualAlignment(q->layoutDirection(), QFlag(this->align)); int m = indent; if (m < 0 && q->frameWidth()) // no indent, but we do have a frame m = q->fontMetrics().width(QLatin1Char('x')) / 2 - margin; if (m > 0) { if (align & Qt::AlignLeft) cr.setLeft(cr.left() + m); if (align & Qt::AlignRight) cr.setRight(cr.right() - m); if (align & Qt::AlignTop) cr.setTop(cr.top() + m); if (align & Qt::AlignBottom) cr.setBottom(cr.bottom() - m); } return cr; } void QLabelPrivate::ensureTextPopulated() const { if (!textDirty) return; if (control) { QTextDocument *doc = control->document(); if (textDirty) { #ifndef QT_NO_TEXTHTMLPARSER if (isRichText) doc->setHtml(text); else doc->setPlainText(text); #else doc->setPlainText(text); #endif doc->setUndoRedoEnabled(false); } } textDirty = false; } void QLabelPrivate::ensureTextLayouted() const { if (!textLayoutDirty) return; ensureTextPopulated(); Q_Q(const QLabel); if (control) { QTextDocument *doc = control->document(); QTextOption opt = doc->defaultTextOption(); opt.setAlignment(QFlag(this->align)); if (this->align & Qt::TextWordWrap) opt.setWrapMode(QTextOption::WordWrap); else opt.setWrapMode(QTextOption::ManualWrap); opt.setTextDirection(q->layoutDirection()); doc->setDefaultTextOption(opt); QTextFrameFormat fmt = doc->rootFrame()->frameFormat(); fmt.setMargin(0); doc->rootFrame()->setFrameFormat(fmt); doc->setTextWidth(documentRect().width()); } textLayoutDirty = false; } void QLabelPrivate::ensureTextControl() const { Q_Q(const QLabel); if (!isTextLabel) return; if (!control) { control = new QTextControl(const_cast<QLabel *>(q)); control->document()->setUndoRedoEnabled(false); control->document()->setDefaultFont(q->font()); control->setTextInteractionFlags(textInteractionFlags); control->setOpenExternalLinks(openExternalLinks); control->setPalette(q->palette()); control->setFocus(q->hasFocus()); QObject::connect(control, SIGNAL(updateRequest(QRectF)), q, SLOT(update())); QObject::connect(control, SIGNAL(linkHovered(QString)), q, SLOT(_q_linkHovered(QString))); QObject::connect(control, SIGNAL(linkActivated(QString)), q, SIGNAL(linkActivated(QString))); textLayoutDirty = true; textDirty = true; } } void QLabelPrivate::sendControlEvent(QEvent *e) { Q_Q(QLabel); if (!isTextLabel || !control || textInteractionFlags == Qt::NoTextInteraction) { e->ignore(); return; } control->processEvent(e, -layoutRect().topLeft(), q); } void QLabelPrivate::_q_linkHovered(const QString &anchor) { Q_Q(QLabel); #ifndef QT_NO_CURSOR if (anchor.isEmpty()) { // restore cursor if (validCursor) q->setCursor(cursor); else q->unsetCursor(); onAnchor = false; } else if (!onAnchor) { validCursor = q->testAttribute(Qt::WA_SetCursor); if (validCursor) { cursor = q->cursor(); } q->setCursor(Qt::PointingHandCursor); onAnchor = true; } #endif emit q->linkHovered(anchor); } // Return the layout rect - this is the rect that is given to the layout painting code // This may be different from the document rect since vertical alignment is not // done by the text layout code QRectF QLabelPrivate::layoutRect() const { QRectF cr = documentRect(); if (!control) return cr; ensureTextLayouted(); // Caculate y position manually qreal rh = control->document()->documentLayout()->documentSize().height(); qreal yo = 0; if (align & Qt::AlignVCenter) yo = qMax((cr.height()-rh)/2, qreal(0)); else if (align & Qt::AlignBottom) yo = qMax(cr.height()-rh, qreal(0)); return QRectF(cr.x(), yo + cr.y(), cr.width(), cr.height()); } // Returns the point in the document rect adjusted with p QPoint QLabelPrivate::layoutPoint(const QPoint& p) const { QRect lr = layoutRect().toRect(); return p - lr.topLeft(); } #ifndef QT_NO_CONTEXTMENU QMenu *QLabelPrivate::createStandardContextMenu(const QPoint &pos) { QString linkToCopy; QPoint p; if (control && isRichText) { p = layoutPoint(pos); linkToCopy = control->document()->documentLayout()->anchorAt(p); } if (linkToCopy.isEmpty() && !control) return 0; return control->createStandardContextMenu(p, q_func()); } #endif /*! \fn void QLabel::linkHovered(const QString &link) \since 4.2 This signal is emitted when the user hovers over a link. The URL referred to by the anchor is passed in \a link. \sa linkActivated() */ /*! \fn void QLabel::linkActivated(const QString &link) \since 4.2 This signal is emitted when the user clicks a link. The URL referred to by the anchor is passed in \a link. \sa linkHovered() */ QT_END_NAMESPACE #include "moc_qlabel.cpp"
librelab/qtmoko-test
qtopiacore/qt/src/gui/widgets/qlabel.cpp
C++
gpl-2.0
44,261
<?php /** * DmMediaTable * * This class has been auto-generated by the Doctrine ORM Framework */ class DmMediaTable extends PluginDmMediaTable { /** * Returns an instance of this class. * * @return DmMediaTable The table object */ public static function getInstance() { return Doctrine_Core::getTable('DmMedia'); } }
Teplitsa/bquest.ru
lib/model/doctrine/dmCorePlugin/DmMediaTable.class.php
PHP
gpl-2.0
366
/* * Copyright by iNet Solutions 2008. * * http://www.truthinet.com.vn/licenses */ Ext.onReady(function(){ var activeMenu; function createMenu(name){ var el = Ext.get(name+'-link'); if (!el) return; var tid = 0, menu, doc = Ext.getDoc(); var handleOver = function(e, t){ if(t != el.dom && t != menu.dom && !e.within(el) && !e.within(menu)){ hideMenu(); } }; var hideMenu = function(){ if(menu){ menu.hide(); el.setStyle('text-decoration', ''); doc.un('mouseover', handleOver); doc.un('mousedown', handleDown); } } var handleDown = function(e){ if(!e.within(menu)){ hideMenu(); } } var showMenu = function(){ clearTimeout(tid); tid = 0; if (!menu) { menu = new Ext.Layer({shadow:'sides',hideMode: 'display'}, name+'-menu'); } menu.hideMenu = hideMenu; menu.el = el; if(activeMenu && menu != activeMenu){ activeMenu.hideMenu(); } activeMenu = menu; if (!menu.isVisible()) { menu.show(); menu.alignTo(el, 'tl-bl?'); menu.sync(); el.setStyle('text-decoration', 'underline'); doc.on('mouseover', handleOver, null, {buffer:150}); doc.on('mousedown', handleDown); } } el.on('mouseover', function(e){ if(!tid){ tid = showMenu.defer(150); } }); el.on('mouseout', function(e){ if(tid && !e.within(el, true)){ clearTimeout(tid); tid = 0; } }); } createMenu('iwebos'); createMenu('home'); createMenu('document'); createMenu('calendar'); createMenu('mail'); createMenu('administrator'); createMenu('contact'); createMenu('paperwork'); // expanders Ext.getBody().on('click', function(e, t){ t = Ext.get(t); e.stopEvent(); var bd = t.next('div.expandable-body'); bd.enableDisplayMode(); var bdi = bd.first(); var expanded = bd.isVisible(); if(expanded){ bd.hide(); }else{ bdi.hide(); bd.show(); bdi.slideIn('l', {duration:0.2, stopFx: true, easing:'easeOut'}); } t.update(!expanded ? 'Hide details' : 'Show details'); }, null, {delegate:'a.expander'}); });
inetcloud/iMail
source/mail-admin/js/inet/ui/common/menu/Menu.js
JavaScript
gpl-2.0
2,082
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved # d$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from openerp.osv import fields, osv from openerp.tools.translate import _ class stock_incoterms(osv.Model): """ stock_incoterm """ _inherit = 'stock.incoterms' _columns = { 'description': fields.text('Description', help='Formal description for this incoterm.'), }
3dfxsoftware/cbss-addons
incoterm_ext/incoterm.py
Python
gpl-2.0
1,298
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package oscar.oscarWaitingList.util; import java.util.Date; import java.util.List; import org.oscarehr.common.dao.WaitingListDao; import org.oscarehr.common.model.WaitingList; import org.oscarehr.util.MiscUtils; import org.oscarehr.util.SpringUtils; import oscar.util.ConversionUtils; public class WLWaitingListUtil { // Modified this method in Feb 2007 to ensure that all records cannot be deleted except hidden. static public synchronized void removeFromWaitingList(String waitingListID, String demographicNo) { MiscUtils.getLogger().debug("WLWaitingListUtil.removeFromWaitingList(): removing waiting list: " + waitingListID + " for patient " + demographicNo); WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class); for (WaitingList wl : dao.findByWaitingListIdAndDemographicId(ConversionUtils.fromIntString(waitingListID), ConversionUtils.fromIntString(demographicNo))) { wl.setHistory(true); dao.merge(wl); } rePositionWaitingList(waitingListID); } static public synchronized void add2WaitingList(String waitingListID, String waitingListNote, String demographicNo, String onListSince) { MiscUtils.getLogger().debug("WLWaitingListUtil.add2WaitingList(): adding to waitingList: " + waitingListID + " for patient " + demographicNo); boolean emptyIds = waitingListID.equalsIgnoreCase("0") || demographicNo.equalsIgnoreCase("0"); if (emptyIds) { MiscUtils.getLogger().debug("Ids are not proper - exiting"); return; } WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class); int maxPosition = dao.getMaxPosition(ConversionUtils.fromIntString(waitingListID)); WaitingList list = new WaitingList(); list.setListId(maxPosition); list.setDemographicNo(ConversionUtils.fromIntString(demographicNo)); list.setNote(waitingListNote); if (onListSince == null || onListSince.length() <= 0) { list.setOnListSince(new Date()); } else { list.setOnListSince(ConversionUtils.fromDateString(onListSince)); } list.setPosition(maxPosition + 1); list.setHistory(false); dao.persist(list); // update the waiting list positions rePositionWaitingList(waitingListID); } /* * This method adds the Waiting List note to the same position in the waitingList table but do not delete previous ones - later on DisplayWaitingList.jsp will display only the most current Waiting List Note record. */ static public synchronized void updateWaitingListRecord(String waitingListID, String waitingListNote, String demographicNo, String onListSince) { MiscUtils.getLogger().debug("WLWaitingListUtil.updateWaitingListRecord(): waitingListID: " + waitingListID + " for patient " + demographicNo); boolean isWatingIdSet = !waitingListID.equalsIgnoreCase("0") && !demographicNo.equalsIgnoreCase("0"); if (!isWatingIdSet) return; WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class); List<WaitingList> waitingLists = dao.findByWaitingListIdAndDemographicId(ConversionUtils.fromIntString(waitingListID), ConversionUtils.fromIntString(demographicNo)); if (waitingLists.isEmpty()) return; long pos = 1; for (WaitingList wl : waitingLists) { pos = wl.getPosition(); } // set all previous records 'is_history' fielf to 'N' --> to keep as record but never display for (WaitingList wl : waitingLists) { wl.setHistory(true); dao.merge(wl); } WaitingList wl = new WaitingList(); wl.setListId(ConversionUtils.fromIntString(waitingListID)); wl.setDemographicNo(ConversionUtils.fromIntString(demographicNo)); wl.setNote(waitingListNote); wl.setPosition(pos); wl.setOnListSince(ConversionUtils.fromDateString(onListSince)); wl.setHistory(false); dao.saveEntity(wl); // update the waiting list positions rePositionWaitingList(waitingListID); } /* * This method adds the Waiting List note to the same position in the waitingList table but do not delete previous ones - later on DisplayWaitingList.jsp will display only the most current Waiting List Note record. */ static public synchronized void updateWaitingList(String id, String waitingListID, String waitingListNote, String demographicNo, String onListSince) { MiscUtils.getLogger().debug("WLWaitingListUtil.updateWaitingList(): waitingListID: " + waitingListID + " for patient " + demographicNo); boolean idsSet = !waitingListID.equalsIgnoreCase("0") && !demographicNo.equalsIgnoreCase("0"); if (!idsSet) { MiscUtils.getLogger().debug("Ids are not set - exiting"); return; } boolean wlIdsSet = (id != null && !id.equals("")); if (!wlIdsSet) { MiscUtils.getLogger().debug("Waiting list id is not set"); return; } WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class); WaitingList waitingListEntry = dao.find(ConversionUtils.fromIntString(id)); if (waitingListEntry == null) { MiscUtils.getLogger().debug("Unable to fetch waiting list with id " + id); return; } waitingListEntry.setListId(ConversionUtils.fromIntString(waitingListID)); waitingListEntry.setNote(waitingListNote); waitingListEntry.setOnListSince(ConversionUtils.fromDateString(onListSince)); dao.merge(waitingListEntry); } public static void rePositionWaitingList(String waitingListID) { int i = 1; WaitingListDao dao = SpringUtils.getBean(WaitingListDao.class); for (WaitingList waitingList : dao.findByWaitingListId(ConversionUtils.fromIntString(waitingListID))) { waitingList.setPosition(i); dao.merge(waitingList); i++; } } }
hexbinary/landing
src/main/java/oscar/oscarWaitingList/util/WLWaitingListUtil.java
Java
gpl-2.0
6,477
<?php $db = mysql_connect("localhost","root",""); mysql_select_db("asterisk"); // Астериск по каким то непонятным причинам сбрасывает в cdr одинаковые записи без forkcdr и т.д. // задача найти их и убрать. //проверка на трансфер $transfer = array(); $q = " select c.id, c.calldate, c.src, c.channel, c.lastdata, c.duration, c.billsec, c.disposition, c.uniqueid from cdr as c left join stat as s on c.id=s.cdrid where c.lastapp='Transferred Call' and c.calldate>='2010-04-01 00:00:00';"; //and // s.id is NULL; //"; $r = mysql_query($q); $n = mysql_num_rows($r); for($i=0;$i<$n;$i++) { list($id,$cd,$src, $ch, $ldata,$dur,$bs,$disp,$uid) = mysql_fetch_array($r); $transfer[$ch] = $id.';;'.$cd.';;'.$src.';;'.$ldata.';;'.$dur.';;'.$bs.';;'.$disp.';;'.$uid; } print_r($transfer); $q = " select c.id as cdrid, c.dcontext as dcontext, c.calldate as calldate, c.src as src, c.dst as dst, c.channel as channel, c.dstchannel as dstchannel, c.duration as duration, c.billsec as billsec, c.disposition as disposition, c.uniqueid as uniqueid, s.id as sid from cdr as c left join stat as s on c.id=s.cdrid where s.id is NULL"; //echo $q."<br>"; $r = mysql_query($q); $n = mysql_num_rows($r); echo date("Y-m-d H:i:s: ").$n."\n"; //$n = 30; $io = ''; $cdrid = 0; $cd = ''; for($i=0;$i<$n;$i++) { $row = mysql_fetch_array($r); //print_r($row); $cdrid = $row['cdrid']; if(substr($row['dcontext'],0,2) == "ip" || $row['dcontext']=='inbound') // ip - old, inbound - new $io = "in"; if(substr($row['dcontext'],0,1) == "c" || substr($row['dcontext'],0,1) == "p") $io = "out"; $cd = $row['calldate']; $src = $row['src']; $dst = $row['dst']; $kod = '-1'; //самая главная штука :) -1 = не обсчитан //$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY); $aa = preg_split('/-/', $row['channel'], -1, PREG_SPLIT_NO_EMPTY); $ch = $aa[0]; $aa = preg_split('/-/', $row['dstchannel'], -1, PREG_SPLIT_NO_EMPTY); $dstch = $aa[0]; $duration = $row['duration']; $billsec = $row['billsec']; $cause = $row['disposition']; $uid = $row['uniqueid']; //$tr = isset($transfer[$row['dstchannel']]); $tr = 0; $qt=''; /*if(isset($transfer[$row['dstchannel']])){ $tch = $row['dstchannel']; $a = str_getcsv($transfer[$tch],';;'); list($tid,$tcd,$tsrc,$tldata,$tdur,$tbs,$tdisp,$tuid) = $a; if($tcd==$cd){ //у нас есть трансфер $qt = "insert into stat values(0,$tid,'tr','$cd',NOW(),'$tsrc','$dst','$kod','$ch','$tldata','$tdur','$tbs','$tdisp','$tuid','0.00','0.00');"; echo $qt."\n"; $kod = -5; } }*/ $qu = "insert into stat values(0,$cdrid,'$io','$cd',NOW(),'$src','$dst','$kod','$ch','$dstch','$duration','$billsec','$cause','$uid','0.00','0.00');"; $ru = mysql_query($qu); if($kod==-5) $rt = mysql_query($qt); //if(isset($transfer[$row['dstchannel']])) echo $qu."\n"; //echo '<br><br>'; } mysql_close($db); function str_getcsv($p,$d) { return preg_split("/$d/", $p); } ?>
Calc86/tel
cron/unique.php
PHP
gpl-2.0
3,241
<?php /* * Styles and scripts registration and enqueuing * * @package mantra * @subpackage Functions */ // Adding the viewport meta if the mobile view has been enabled if($mantra_mobile=="Enable") add_action('wp_head', 'mantra_mobile_meta'); function mantra_mobile_meta() { global $mantra_options; foreach ($mantra_options as $key => $value) { ${"$key"} = $value ; } echo '<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">'; } // Loading mantra css style function mantra_style() { global $mantra_options; foreach ($mantra_options as $key => $value) { ${"$key"} = $value ; } // Loading the style.css wp_register_style( 'mantras', get_stylesheet_uri() ); wp_enqueue_style( 'mantras'); } // Loading google font styles function mantra_google_styles() { global $mantra_options; foreach ($mantra_options as $key => $value) { ${"$key"} = $value ; } wp_register_style( 'mantra_googlefont', esc_attr($mantra_googlefont2 )); wp_register_style( 'mantra_googlefonttitle', esc_attr($mantra_googlefonttitle2 )); wp_register_style( 'mantra_googlefontside',esc_attr($mantra_googlefontside2) ); wp_register_style( 'mantra_googlefontsubheader', esc_attr($mantra_googlefontsubheader2) ); wp_enqueue_style( 'mantra_googlefont'); wp_enqueue_style( 'mantra_googlefonttitle'); wp_enqueue_style( 'mantra_googlefontside'); wp_enqueue_style( 'mantra_googlefontsubheader'); // Loading the style-mobile.css if the mobile view is enabled if($mantra_mobile=="Enable") { wp_register_style( 'mantra-mobile', get_template_directory_uri() . '/style-mobile.css' ); wp_enqueue_style( 'mantra-mobile');} } // CSS loading and hook into wp_enque_scripts add_action('wp_print_styles', 'mantra_style',1 ); add_action('wp_head', 'mantra_custom_styles' ,8); if($mantra_customcss!="/* Mantra Custom CSS */") add_action('wp_head', 'mantra_customcss',9); add_action('wp_head', 'mantra_google_styles'); // JS loading and hook into wp_enque_scripts add_action('wp_head', 'mantra_customjs' ); // Scripts loading and hook into wp_enque_scripts function mantra_scripts_method() { global $mantra_options; foreach ($mantra_options as $key => $value) { ${"$key"} = $value ; } // If frontend - load the js for the menu and the social icons animations if ( !is_admin() ) { wp_register_script('cryout-frontend',get_template_directory_uri() . '/js/frontend.js', array('jquery') ); wp_enqueue_script('cryout-frontend'); // If mantra from page is enabled and the current page is home page - load the nivo slider js if($mantra_frontpage == "Enable" && is_front_page()) { wp_register_script('cryout-nivoSlider',get_template_directory_uri() . '/js/nivo-slider.js', array('jquery')); wp_enqueue_script('cryout-nivoSlider'); } } /* We add some JavaScript to pages with the comment form * to support sites with threaded comments (when in use). */ if ( is_singular() && get_option( 'thread_comments' ) ) wp_enqueue_script( 'comment-reply' ); } add_action('wp_enqueue_scripts', 'mantra_scripts_method'); /** * Adding CSS3 PIE behavior to elements that need it */ function mantra_ie_pie() { echo ' <!--[if lte IE 8]> <style type="text/css" media="screen"> #access ul li, .edit-link a , #footer-widget-area .widget-title, .entry-meta,.entry-meta .comments-link, .short-button-light, .short-button-dark ,.short-button-color ,blockquote { position:relative; behavior: url('.get_template_directory_uri().'/js/PIE/PIE.php); } #access ul ul { -pie-box-shadow:0px 5px 5px #999; } #access ul li.current_page_item, #access ul li.current-menu-item , #access ul li ,#access ul ul ,#access ul ul li, .commentlist li.comment ,.commentlist .avatar, .contentsearch #searchsubmit , .widget_search #s, #search #s , .widget_search #searchsubmit , .nivo-caption, .theme-default .nivoSlider { behavior: url('.get_template_directory_uri().'/js/PIE/PIE.php); } </style> <![endif]--> '; } add_action('wp_head', 'mantra_ie_pie', 10); ?>
DanielMSchmidt/stadtfest-theme
wp-content/themes/mantra/includes/theme-styles.php
PHP
gpl-2.0
4,286
// OGLTexture.cpp // KlayGE OpenGLÎÆÀíÀà ʵÏÖÎļþ // Ver 3.12.0 // °æÈ¨ËùÓÐ(C) ¹¨ÃôÃô, 2003-2007 // Homepage: http://www.klayge.org // // 3.9.0 // Ö§³ÖTexture Array (2009.8.5) // // 3.6.0 // ÓÃpbo¼ÓËÙ (2007.3.13) // // 2.7.0 // Ôö¼ÓÁËAddressingMode, FilteringºÍAnisotropy (2005.6.27) // Ôö¼ÓÁËMaxMipLevelºÍMipMapLodBias (2005.6.28) // // 2.3.0 // Ôö¼ÓÁËCopyToMemory (2005.2.6) // // Ð޸ļǼ ///////////////////////////////////////////////////////////////////////////////// #include <KlayGE/KlayGE.hpp> #include <KFL/ErrorHandling.hpp> #include <KFL/Math.hpp> #include <KlayGE/RenderEngine.hpp> #include <KlayGE/RenderFactory.hpp> #include <KlayGE/Texture.hpp> #include <cstring> #include <glloader/glloader.h> #include <KlayGE/OpenGL/OGLRenderEngine.hpp> #include <KlayGE/OpenGL/OGLUtil.hpp> #include <KlayGE/OpenGL/OGLTexture.hpp> namespace KlayGE { OGLTexture::OGLTexture(TextureType type, uint32_t array_size, uint32_t sample_count, uint32_t sample_quality, uint32_t access_hint) : Texture(type, sample_count, sample_quality, access_hint), hw_res_ready_(false) { array_size_ = array_size; switch (type_) { case TT_1D: if (array_size > 1) { target_type_ = GL_TEXTURE_1D_ARRAY; } else { target_type_ = GL_TEXTURE_1D; } break; case TT_2D: if (array_size > 1) { target_type_ = GL_TEXTURE_2D_ARRAY; } else { target_type_ = GL_TEXTURE_2D; } break; case TT_3D: target_type_ = GL_TEXTURE_3D; break; case TT_Cube: if (array_size > 1) { target_type_ = GL_TEXTURE_CUBE_MAP_ARRAY; } else { target_type_ = GL_TEXTURE_CUBE_MAP; } break; default: KFL_UNREACHABLE("Invalid texture type"); } if (sample_count_ <= 1) { if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access()) { glCreateTextures(target_type_, 1, &texture_); } else if (glloader_GL_EXT_direct_state_access()) { glGenTextures(1, &texture_); } else { glGenTextures(1, &texture_); glBindTexture(target_type_, texture_); } } else { glGenRenderbuffers(1, &texture_); } } OGLTexture::~OGLTexture() { this->DeleteHWResource(); if (Context::Instance().RenderFactoryValid()) { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.DeleteBuffers(1, &pbo_); } else { glDeleteBuffers(1, &pbo_); } if (sample_count_ <= 1) { if (Context::Instance().RenderFactoryValid()) { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.DeleteTextures(1, &texture_); } else { glDeleteTextures(1, &texture_); } } else { glDeleteRenderbuffers(1, &texture_); } } std::wstring const & OGLTexture::Name() const { static const std::wstring name(L"OpenGL Texture"); return name; } uint32_t OGLTexture::Width(uint32_t level) const { KFL_UNUSED(level); BOOST_ASSERT(level < num_mip_maps_); return 1; } uint32_t OGLTexture::Height(uint32_t level) const { KFL_UNUSED(level); BOOST_ASSERT(level < num_mip_maps_); return 1; } uint32_t OGLTexture::Depth(uint32_t level) const { KFL_UNUSED(level); BOOST_ASSERT(level < num_mip_maps_); return 1; } void OGLTexture::CopyToSubTexture1D(Texture& target, uint32_t dst_array_index, uint32_t dst_level, uint32_t dst_x_offset, uint32_t dst_width, uint32_t src_array_index, uint32_t src_level, uint32_t src_x_offset, uint32_t src_width, TextureFilter filter) { KFL_UNUSED(target); KFL_UNUSED(dst_array_index); KFL_UNUSED(dst_level); KFL_UNUSED(dst_x_offset); KFL_UNUSED(dst_width); KFL_UNUSED(src_array_index); KFL_UNUSED(src_level); KFL_UNUSED(src_x_offset); KFL_UNUSED(src_width); KFL_UNUSED(filter); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::CopyToSubTexture2D(Texture& target, uint32_t dst_array_index, uint32_t dst_level, uint32_t dst_x_offset, uint32_t dst_y_offset, uint32_t dst_width, uint32_t dst_height, uint32_t src_array_index, uint32_t src_level, uint32_t src_x_offset, uint32_t src_y_offset, uint32_t src_width, uint32_t src_height, TextureFilter filter) { KFL_UNUSED(target); KFL_UNUSED(dst_array_index); KFL_UNUSED(dst_level); KFL_UNUSED(dst_x_offset); KFL_UNUSED(dst_y_offset); KFL_UNUSED(dst_width); KFL_UNUSED(dst_height); KFL_UNUSED(src_array_index); KFL_UNUSED(src_level); KFL_UNUSED(src_x_offset); KFL_UNUSED(src_y_offset); KFL_UNUSED(src_width); KFL_UNUSED(src_height); KFL_UNUSED(filter); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::CopyToSubTexture3D(Texture& target, uint32_t dst_array_index, uint32_t dst_level, uint32_t dst_x_offset, uint32_t dst_y_offset, uint32_t dst_z_offset, uint32_t dst_width, uint32_t dst_height, uint32_t dst_depth, uint32_t src_array_index, uint32_t src_level, uint32_t src_x_offset, uint32_t src_y_offset, uint32_t src_z_offset, uint32_t src_width, uint32_t src_height, uint32_t src_depth, TextureFilter filter) { KFL_UNUSED(target); KFL_UNUSED(dst_array_index); KFL_UNUSED(dst_level); KFL_UNUSED(dst_x_offset); KFL_UNUSED(dst_y_offset); KFL_UNUSED(dst_z_offset); KFL_UNUSED(dst_width); KFL_UNUSED(dst_height); KFL_UNUSED(dst_depth); KFL_UNUSED(src_array_index); KFL_UNUSED(src_level); KFL_UNUSED(src_x_offset); KFL_UNUSED(src_y_offset); KFL_UNUSED(src_z_offset); KFL_UNUSED(src_width); KFL_UNUSED(src_height); KFL_UNUSED(src_depth); KFL_UNUSED(filter); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::CopyToSubTextureCube(Texture& target, uint32_t dst_array_index, CubeFaces dst_face, uint32_t dst_level, uint32_t dst_x_offset, uint32_t dst_y_offset, uint32_t dst_width, uint32_t dst_height, uint32_t src_array_index, CubeFaces src_face, uint32_t src_level, uint32_t src_x_offset, uint32_t src_y_offset, uint32_t src_width, uint32_t src_height, TextureFilter filter) { KFL_UNUSED(target); KFL_UNUSED(dst_array_index); KFL_UNUSED(dst_face); KFL_UNUSED(dst_level); KFL_UNUSED(dst_x_offset); KFL_UNUSED(dst_y_offset); KFL_UNUSED(dst_width); KFL_UNUSED(dst_height); KFL_UNUSED(src_array_index); KFL_UNUSED(src_face); KFL_UNUSED(src_level); KFL_UNUSED(src_x_offset); KFL_UNUSED(src_y_offset); KFL_UNUSED(src_width); KFL_UNUSED(src_height); KFL_UNUSED(filter); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Map1D(uint32_t array_index, uint32_t level, TextureMapAccess tma, uint32_t x_offset, uint32_t width, void*& data) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(tma); KFL_UNUSED(x_offset); KFL_UNUSED(width); KFL_UNUSED(data); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Map2D(uint32_t array_index, uint32_t level, TextureMapAccess tma, uint32_t x_offset, uint32_t y_offset, uint32_t width, uint32_t height, void*& data, uint32_t& row_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(tma); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Map3D(uint32_t array_index, uint32_t level, TextureMapAccess tma, uint32_t x_offset, uint32_t y_offset, uint32_t z_offset, uint32_t width, uint32_t height, uint32_t depth, void*& data, uint32_t& row_pitch, uint32_t& slice_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(tma); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(z_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(depth); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNUSED(slice_pitch); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::MapCube(uint32_t array_index, CubeFaces face, uint32_t level, TextureMapAccess tma, uint32_t x_offset, uint32_t y_offset, uint32_t width, uint32_t height, void*& data, uint32_t& row_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(face); KFL_UNUSED(level); KFL_UNUSED(tma); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Unmap1D(uint32_t array_index, uint32_t level) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Unmap2D(uint32_t array_index, uint32_t level) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::Unmap3D(uint32_t array_index, uint32_t level) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::UnmapCube(uint32_t array_index, CubeFaces face, uint32_t level) { KFL_UNUSED(array_index); KFL_UNUSED(face); KFL_UNUSED(level); KFL_UNREACHABLE("Can't be called"); } bool OGLTexture::HwBuildMipSubLevels(TextureFilter filter) { if (IsDepthFormat(format_) || (ChannelType<0>(format_) == ECT_UInt) || (ChannelType<0>(format_) == ECT_SInt)) { if (filter != TextureFilter::Point) { return false; } } else { if (filter != TextureFilter::Linear) { return false; } } if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access()) { glGenerateTextureMipmap(texture_); } else if (glloader_GL_EXT_direct_state_access()) { glGenerateTextureMipmapEXT(texture_, target_type_); } else { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.BindTexture(0, target_type_, texture_); glGenerateMipmap(target_type_); } return true; } void OGLTexture::TexParameteri(GLenum pname, GLint param) { auto iter = tex_param_i_.find(pname); if ((iter == tex_param_i_.end()) || (iter->second != param)) { if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access()) { glTextureParameteri(texture_, pname, param); } else if (glloader_GL_EXT_direct_state_access()) { glTextureParameteriEXT(texture_, target_type_, pname, param); } else { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.BindTexture(0, target_type_, texture_); glTexParameteri(target_type_, pname, param); } tex_param_i_[pname] = param; } } void OGLTexture::TexParameterf(GLenum pname, GLfloat param) { auto iter = tex_param_f_.find(pname); if ((iter == tex_param_f_.end()) || (iter->second != param)) { if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access()) { glTextureParameterf(texture_, pname, param); } else if (glloader_GL_EXT_direct_state_access()) { glTextureParameterfEXT(texture_, target_type_, pname, param); } else { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.BindTexture(0, target_type_, texture_); glTexParameterf(target_type_, pname, param); } tex_param_f_[pname] = param; } } void OGLTexture::TexParameterfv(GLenum pname, GLfloat const * param) { float4 const f4_param(param); auto iter = tex_param_fv_.find(pname); if ((iter == tex_param_fv_.end()) || (iter->second != f4_param)) { if (glloader_GL_VERSION_4_5() || glloader_GL_ARB_direct_state_access()) { glTextureParameterfv(texture_, pname, param); } else if (glloader_GL_EXT_direct_state_access()) { glTextureParameterfvEXT(texture_, target_type_, pname, param); } else { auto& re = checked_cast<OGLRenderEngine&>(Context::Instance().RenderFactoryInstance().RenderEngineInstance()); re.BindTexture(0, target_type_, texture_); glTexParameterfv(target_type_, pname, param); } tex_param_fv_[pname] = f4_param; } } ElementFormat OGLTexture::SRGBToRGB(ElementFormat pf) { switch (pf) { case EF_ARGB8_SRGB: return EF_ARGB8; case EF_BC1_SRGB: return EF_BC1; case EF_BC2_SRGB: return EF_BC2; case EF_BC3_SRGB: return EF_BC3; default: return pf; } } void OGLTexture::DeleteHWResource() { hw_res_ready_ = false; } bool OGLTexture::HWResourceReady() const { return hw_res_ready_; } void OGLTexture::UpdateSubresource1D(uint32_t array_index, uint32_t level, uint32_t x_offset, uint32_t width, void const * data) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(x_offset); KFL_UNUSED(width); KFL_UNUSED(data); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::UpdateSubresource2D(uint32_t array_index, uint32_t level, uint32_t x_offset, uint32_t y_offset, uint32_t width, uint32_t height, void const * data, uint32_t row_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::UpdateSubresource3D(uint32_t array_index, uint32_t level, uint32_t x_offset, uint32_t y_offset, uint32_t z_offset, uint32_t width, uint32_t height, uint32_t depth, void const * data, uint32_t row_pitch, uint32_t slice_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(level); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(z_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(depth); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNUSED(slice_pitch); KFL_UNREACHABLE("Can't be called"); } void OGLTexture::UpdateSubresourceCube(uint32_t array_index, Texture::CubeFaces face, uint32_t level, uint32_t x_offset, uint32_t y_offset, uint32_t width, uint32_t height, void const * data, uint32_t row_pitch) { KFL_UNUSED(array_index); KFL_UNUSED(face); KFL_UNUSED(level); KFL_UNUSED(x_offset); KFL_UNUSED(y_offset); KFL_UNUSED(width); KFL_UNUSED(height); KFL_UNUSED(data); KFL_UNUSED(row_pitch); KFL_UNREACHABLE("Can't be called"); } }
gongminmin/KlayGE
KlayGE/Plugins/Src/Render/OpenGL/OGLTexture.cpp
C++
gpl-2.0
14,017
<?php function tzs_front_end_user_products_handler($atts) { // Определяем атрибуты // [tzs-view-user-products user_id="1"] - указываем на странице раздела // [tzs-view-products] - указываем на страницах подразделов extract( shortcode_atts( array( 'user_id' => '0', ), $atts, 'tzs-view-user-products' ) ); ob_start(); $sql1 = ' AND user_id='.$user_id; global $wpdb; $page = current_page_number(); $url = current_page_url(); $pp = TZS_RECORDS_PER_PAGE; $sql = "SELECT COUNT(*) as cnt FROM ".TZS_PRODUCTS_TABLE." WHERE active=1 $sql1 "; $res = $wpdb->get_row($sql); if (count($res) == 0 && $wpdb->last_error != null) { print_error('Не удалось отобразить список товаров. Свяжитесь, пожалуйста, с администрацией сайта -count'); } else { $records = $res->cnt; $pages = ceil($records / $pp); if ($pages == 0) $pages = 1; if ($page > $pages) $page = $pages; $from = ($page-1) * $pp; $sql = "SELECT * FROM ".TZS_PRODUCTS_TABLE." WHERE active=1 $sql1 ORDER BY created DESC LIMIT $from,$pp; "; $res = $wpdb->get_results($sql); if (count($res) == 0 && $wpdb->last_error != null) { print_error('Не удалось отобразить список товаров. Свяжитесь, пожалуйста, с администрацией сайта - record'); } else { if (count($res) == 0) { ?> <div style="clear: both;"></div> <div class="errors"> <div id="info error">По Вашему запросу ничего не найдено.</div> </div> <?php } else { ?> <div> <table id="tbl_products"> <tr> <th id="tbl_products_id">Номер</th> <th id="tbl_products_img">Фото</th> <th id="tbl_products_dtc">Дата размещения</th> <th id="title">Описание товара</th> <th id="price">Стоимость товара</th> <th id="descr">Форма оплаты</th> <th id="cities">Город</th> <th id="comm">Комментарии</th> </tr> <?php foreach ( $res as $row ) { ?> <tr rid="<?php echo $row->id;?>"> <td><?php echo $row->id;?></td> <td> <?php if (strlen($row->image_id_lists) > 0) { //$img_names = explode(';', $row->pictures); $main_image_id = $row->main_image_id; // Вначале выведем главное изображение $attachment_info = wp_get_attachment_image_src($main_image_id, 'thumbnail'); if ($attachment_info !== false) { //if (file_exists(ABSPATH . $img_names[0])) { //echo '<img src="'.get_site_url().'/'.$img_names[0].'" alt="">'; echo '<img src="'.$attachment_info[0].'" alt="">'; // width="50px" height="50px" } else { echo '&nbsp;'; } } else { echo '&nbsp;'; } ?> </td> <td><?php echo convert_date($row->created); ?></td> <td><?php echo htmlspecialchars($row->title);?></td> <td><?php echo $row->price." ".$GLOBALS['tzs_pr_curr'][$row->currency];?></td> <td><?php echo $GLOBALS['tzs_pr_payment'][$row->payment];?></td> <td><?php echo tzs_city_to_str($row->from_cid, $row->from_rid, $row->from_sid, $row->city_from);?></td> <td><?php echo htmlspecialchars($row->comment);?></td> </tr> <?php } ?> </table> </div> <?php } build_pages_footer($page, $pages); } } //// ?> <script src="/wp-content/plugins/tzs/assets/js/search.js"></script> <script> var post = []; <?php echo "// POST dump here\n"; foreach ($_POST as $key => $value) { echo "post[".tzs_encode2($key)."] = ".tzs_encode2($value).";\n"; } if (!isset($_POST['type_id'])) { echo "post[".tzs_encode2("type_id")."] = ".tzs_encode2($p_id).";\n"; } if (!isset($_POST['cur_type_id'])) { echo "post[".tzs_encode2("cur_type_id")."] = ".tzs_encode2($p_id).";\n"; } ?> function showSearchDialog() { doSearchDialog('products', post, null); //doSearchDialog('auctions', post, null); } jQuery(document).ready(function(){ jQuery('#tbl_products').on('click', 'td', function(e) { var nonclickable = 'true' == e.delegateTarget.rows[0].cells[this.cellIndex].getAttribute('nonclickable'); var id = this.parentNode.getAttribute("rid"); if (!nonclickable) document.location = "/account/view-product/?id="+id; }); hijackLinks(post); }); </script> <?php //// $output = ob_get_contents(); ob_end_clean(); return $output; } ?>
serker72/T3S_Old
wp-content/plugins/tzs/front-end/tzs.user.products.php
PHP
gpl-2.0
6,919
<?php /* @author : Giriraj Namachivayam @date : Apr 25, 2013 @demourl : http://ngiriraj.com/socialMedia/oauthlogin/ @license : Free to use, */ include "socialmedia_oauth_connect.php"; $oauth = new socialmedia_oauth_connect(); $oauth->provider="DeviantArt"; $oauth->client_id = "396"; $oauth->client_secret = "xxxxxxxxxxxxxxxxxxxxxxxxx"; $oauth->redirect_uri ="http://ngiriraj.com/socialMedia/oauthlogin/deviantart.php"; $oauth->Initialize(); $code = ($_REQUEST["code"]) ? ($_REQUEST["code"]) : ""; if(empty($code)) { $oauth->Authorize(); }else{ $oauth->code = $code; # $oauth->getAccessToken(); $getData = json_decode($oauth->getUserProfile()); $oauth->debugJson($getData); } ?>
phoenixz/base
data/plugins/socialmedia-oauth-login/deviantart.php
PHP
gpl-2.0
703
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ namespace eZ\Bundle\EzPublishIOBundle\DependencyInjection\Factory; use League\Flysystem\Adapter\Local; /** * Builds a Local Flysystem Adapter instance with the given permissions configuration. */ class LocalAdapterFactory { /** * @param string $rootDir * @param int $filesPermissions Permissions used when creating files. Example: 0640. * @param int $directoriesPermissions Permissions when creating directories. Example: 0750. * * @return Local */ public function build($rootDir, $filesPermissions, $directoriesPermissions) { return new Local( $rootDir, LOCK_EX, Local::DISALLOW_LINKS, ['file' => ['public' => $filesPermissions], 'dir' => ['public' => $directoriesPermissions]] ); } }
ezsystems/ezpublish-kernel
eZ/Bundle/EzPublishIOBundle/DependencyInjection/Factory/LocalAdapterFactory.php
PHP
gpl-2.0
987
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Reflection { public class Student { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public Dictionary<string, int> Grades { get; set; } public Student(string first, string last) { this.FirstName = first; this.LastName = last; this.Grades = new Dictionary<string, int>(); } public void AddGrade(string course, int grade) { this.Grades.Add(course,grade); } } }
Omri27/AfekaTorrent
Reflection/Student.cs
C#
gpl-2.0
689
import os from unipath import Path try: # expect at ~/source/tshilo-dikotla/etc/default.cnf # etc folder is not in the git repo PATH = Path(os.path.dirname(os.path.realpath(__file__))).ancestor( 1).child('etc') if not os.path.exists(PATH): raise TypeError( 'Path to database credentials at \'{}\' does not exist'.format(PATH)) with open(os.path.join(PATH, 'secret_key.txt')) as f: PRODUCTION_SECRET_KEY = f.read().strip() PRODUCTION_POSTGRES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': os.path.join(PATH, 'default.cnf'), }, 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, # 'lab_api': { # 'ENGINE': 'django.db.backends.mysql', # 'OPTIONS': { # 'read_default_file': os.path.join(PATH, 'lab_api.cnf'), # }, # 'HOST': '', # 'PORT': '', # 'ATOMIC_REQUESTS': True, # }, } except TypeError: PRODUCTION_POSTGRES = None PRODUCTION_SECRET_KEY = None print('Path to production database credentials does not exist') TRAVIS_POSTGRES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'td', 'USER': 'travis', 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, 'lab_api': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'td_lab', 'USER': 'travis', 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, 'test_server': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'td_test', 'USER': 'travis', 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, } TEST_HOSTS_POSTGRES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'td', 'USER': 'django', 'PASSWORD': 'django', 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, 'lab_api': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'td_lab', 'USER': 'django', 'PASSWORD': 'django', 'HOST': '', 'PORT': '', 'ATOMIC_REQUESTS': True, }, }
botswana-harvard/tshilo-dikotla
tshilo_dikotla/databases.py
Python
gpl-2.0
2,422
/** * @file * File with JS to initialize jQuery plugins on fields. */ (function($){ Drupal.behaviors.field_timer = { attach: function() { var settings = drupalSettings.field_timer; if ($.countdown != undefined) { $.countdown.setDefaults($.countdown.regionalOptions['']); } for (var key in settings) { var options = settings[key].settings; var $item = $('#' + key); var timestamp = $item.data('timestamp'); switch (settings[key].plugin) { case 'county': $item.once('field-timer').each(function() { $(this).county($.extend({endDateTime: new Date(timestamp * 1000)}, options)); }); break; case 'jquery.countdown': $item.once('field-timer').each(function() { $(this).countdown($.extend( options, { until: (options.until ? new Date(timestamp * 1000) : null), since: (options.since ? new Date(timestamp * 1000) : null) }, $.countdown.regionalOptions[options.regional] )); }); break; case 'jquery.countdown.led': $item.once('field-timer').each(function() { $(this).countdown({ until: (options.until ? new Date(timestamp * 1000) : null), since: (options.since ? new Date(timestamp * 1000) : null), layout: $item.html() }); }); break; } } } } })(jQuery);
blakefrederick/sas-backend
modules/field_timer/js/field_timer.js
JavaScript
gpl-2.0
1,598
/* * (C) 2007-2010 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * * Version: $Id: test_batch_read.cpp 44 2010-11-12 07:43:00Z chuyu@taobao.com $ * * Authors: * qushan <qushan@taobao.com> * - initial release * */ #include "util.h" #include "thread.h" #include "common/func.h" #include "client/tfs_client_api.h" #include <vector> #include <algorithm> #include <functional> using namespace KFS; using namespace tfs::client; using namespace tfs::common; static int32_t m_stop = 0; void sign_handler(int32_t sig) { switch (sig) { case SIGINT: m_stop = 1; break; } } #define FILE_NAME_LEN 18 void* read_worker(void* arg) { ThreadParam param = *(ThreadParam*) (arg); char file_list_name[100]; sprintf(file_list_name, "wf_%d", param.index_); FILE* input_fd = fopen(file_list_name, "rb"); if (NULL == input_fd) { printf("index(%d) open read file failed, exit\n", param.index_); return NULL; } /* param.locker_->lock(); TfsSession session; session.init((char*) param.conf_.c_str()); param.locker_->unlock(); TfsFile tfs_file; tfs_file.set_session(&session); */ printf("init connection to nameserver:%s\n", param.ns_ip_port_.c_str()); TfsClient tfsclient; int iret = tfsclient.initialize(param.ns_ip_port_); if (iret == TFS_ERROR) { return NULL; } Timer timer; Stater stater("read"); const int32_t BUFLEN = 32; char name_buf[BUFLEN]; int32_t failed_count = 0; int32_t zoomed_count = 0; int32_t total_count = 0; int64_t time_start = Func::curr_time(); int64_t time_consumed = 0, min_time_consumed = 0, max_time_consumed = 0, accumlate_time_consumed = 0; // 1M file number, each 18 bit, total 18M vector < std::string > write_file_list; while (fgets(name_buf, BUFLEN, input_fd)) { ssize_t endpos = strlen(name_buf) - 1; while (name_buf[endpos] == '\n') { name_buf[endpos] = 0; --endpos; } write_file_list.push_back(name_buf); } fclose(input_fd); //random read if (param.random_) { vector<std::string>::iterator start = write_file_list.begin(); vector<std::string>::iterator end = write_file_list.end(); random_shuffle(start, end); } bool read_image = false; bool image_scale_random = false; if ((param.max_size_ != 0) && (param.min_size_ != 0)) { read_image = true; } if (param.max_size_ != param.min_size_) { image_scale_random = true; } vector<std::string>::iterator vit = write_file_list.begin(); for (; vit != write_file_list.end(); vit++) { if (m_stop) { break; } if ((param.file_count_ > 0) && (total_count >= param.file_count_)) { break; } timer.start(); int32_t ret = 0; bool zoomed = true; if (read_image) { if (image_scale_random) { srand(time(NULL) + rand() + pthread_self()); int32_t min_width = (param.max_size_ / 6); int32_t min_height = (param.min_size_ / 6); int32_t scale_width = rand() % (param.max_size_ - min_width) + min_width; int32_t scale_height = rand() % (param.min_size_ - min_height) + min_height; ret = copy_file_v3(tfsclient, (char *) (*vit).c_str(), scale_width, scale_height, -1, zoomed); if (zoomed) { ++zoomed_count; } } } else { ret = copy_file_v2(tfsclient, (char *) (*vit).c_str(), -1); } if (ret != TFS_SUCCESS) { printf("read file fail %s ret : %d\n", (*vit).c_str(), ret); ++failed_count; } else { time_consumed = timer.consume(); stater.stat_time_count(time_consumed); if (total_count == 0) { min_time_consumed = time_consumed; } if (time_consumed < min_time_consumed) { min_time_consumed = time_consumed; } if (time_consumed > max_time_consumed) { max_time_consumed = time_consumed; } accumlate_time_consumed += time_consumed; } if (param.profile_) { printf("read file (%s), (%s)\n", (*vit).c_str(), ret == TFS_SUCCESS ? "success" : "failed"); print_rate(ret, time_consumed); } ++total_count; } uint32_t total_succ_count = total_count - failed_count; ((ThreadParam*) arg)->file_count_ = total_succ_count; int64_t time_stop = Func::curr_time(); time_consumed = time_stop - time_start; double iops = static_cast<double> (total_succ_count) / (static_cast<double> (time_consumed) / 1000000); double rate = static_cast<double> (time_consumed) / total_succ_count; double aiops = static_cast<double> (total_succ_count) / (static_cast<double> (accumlate_time_consumed) / 1000000); double arate = static_cast<double> (accumlate_time_consumed) / total_succ_count; printf("thread index:%5d count:%5d failed:%5d, zoomed:%5d, filesize:%6d iops:%10.3f rate:%10.3f ," " min:%" PRI64_PREFIX "d, max:%" PRI64_PREFIX "d,avg:%" PRI64_PREFIX "d aiops:%10.3f, arate:%10.3f \n", param.index_, total_count, failed_count, zoomed_count, param.file_size_, iops, rate, min_time_consumed, max_time_consumed, accumlate_time_consumed / total_succ_count, aiops, arate); stater.dump_time_stat(); return NULL; } int main(int argc, char* argv[]) { int32_t thread_count = 1; ThreadParam input_param; int32_t ret = fetch_input_opt(argc, argv, input_param, thread_count); if (ret != TFS_SUCCESS || input_param.ns_ip_port_.empty() || thread_count > THREAD_SIZE) { printf("usage: -d -t \n"); exit(-1); } //if (thread_count > 0) ClientPoolCollect::setClientPoolCollectParam(thread_count,0,0); signal(SIGINT, sign_handler); MetaThread threads[THREAD_SIZE]; ThreadParam param[THREAD_SIZE]; tbsys::CThreadMutex glocker; int64_t time_start = Func::curr_time(); for (int32_t i = 0; i < thread_count; ++i) { param[i].index_ = i; param[i].conf_ = input_param.conf_; param[i].file_count_ = input_param.file_count_; param[i].file_size_ = input_param.file_size_; param[i].min_size_ = input_param.min_size_; param[i].max_size_ = input_param.max_size_; param[i].profile_ = input_param.profile_; param[i].random_ = input_param.random_; param[i].locker_ = &glocker; param[i].ns_ip_port_ = input_param.ns_ip_port_; threads[i].start(read_worker, (void*) &param[i]); } for (int32_t i = 0; i < thread_count; ++i) { threads[i].join(); } int32_t total_count = 0; for (int32_t i = 0; i < thread_count; ++i) { total_count += param[i].file_count_; } int64_t time_stop = Func::curr_time(); int64_t time_consumed = time_stop - time_start; double iops = static_cast<double>(total_count) / (static_cast<double>(time_consumed) / 1000000); double rate = static_cast<double>(time_consumed) / total_count; printf("read_thread count filesize iops rate\n"); printf("%10d %5d %9d %8.3f %12.3f \n", thread_count, total_count, input_param.file_size_, iops, rate); }
qqiangwu/annotated-tfs
tests/batch/test_batch_read.cpp
C++
gpl-2.0
7,158
namespace PowerPointLabs.ELearningLab.AudioGenerator { public class AzureAccount { private static AzureAccount instance; private string key; private string endpoint; public static AzureAccount GetInstance() { if (instance == null) { instance = new AzureAccount(); } return instance; } private AzureAccount() { key = null; endpoint = null; } public void SetUserKeyAndRegion(string key, string endpoint) { this.key = key; this.endpoint = endpoint; } public string GetKey() { return key; } public string GetRegion() { return endpoint; } public string GetUri() { if (!string.IsNullOrEmpty(endpoint)) { return EndpointToUriConverter.azureEndpointToUriMapping[endpoint]; } return null; } public bool IsEmpty() { return key == null || endpoint == null; } public void Clear() { key = null; endpoint = null; } } }
PowerPointLabs/PowerPointLabs
PowerPointLabs/PowerPointLabs/ELearningLab/AudioGenerator/AzureVoiceGenerator/Model/AzureAccount.cs
C#
gpl-2.0
1,280
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Hash; use App\Models\Link; use App\Models\User; use App\Helpers\UserHelper; class AdminController extends Controller { /** * Show the admin panel, and process admin AJAX requests. * * @return Response */ public function displayAdminPage(Request $request) { if (!$this->isLoggedIn()) { return abort(404); } $username = session('username'); $role = session('role'); $admin_users = null; $admin_links = null; if ($this->currIsAdmin()) { $admin_users = User::paginate(15); $admin_links = Link::paginate(15); } $user = UserHelper::getUserByUsername($username); if (!$user) { return redirect(route('index'))->with('error', 'Invalid or disabled account.'); } $user_links = Link::where('creator', $username) ->paginate(15); return view('admin', [ 'role' => $role, 'admin_users' => $admin_users, 'admin_links' => $admin_links, 'user_links' => $user_links, 'api_key' => $user->api_key, 'api_active' => $user->api_active, 'api_quota' => $user->api_quota, 'user_id' => $user->id ]); } public function changePassword(Request $request) { if (!$this->isLoggedIn()) { return abort(404); } $username = session('username'); $old_password = $request->input('current_password'); $new_password = $request->input('new_password'); if (UserHelper::checkCredentials($username, $old_password) == false) { // Invalid credentials return redirect('admin')->with('error', 'Current password invalid. Try again.'); } else { // Credentials are correct $user = UserHelper::getUserByUsername($username); $user->password = Hash::make($new_password); $user->save(); $request->session()->flash('success', "Password changed successfully."); return redirect(route('admin')); } } }
goeroe/polr
app/Http/Controllers/AdminController.php
PHP
gpl-2.0
2,212
namespace CommandPattern.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
logicalforhad/designpattern
GofPattern/CommandPattern/Properties/Settings.Designer.cs
C#
gpl-2.0
669
package teammates.client.scripts; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import teammates.common.datatransfer.DataBundle; import teammates.common.datatransfer.attributes.CourseAttributes; import teammates.common.datatransfer.attributes.InstructorAttributes; import teammates.common.datatransfer.attributes.StudentAttributes; import teammates.common.util.JsonUtils; import teammates.test.driver.BackDoor; import teammates.test.driver.FileHelper; import teammates.test.driver.TestProperties; import teammates.test.pageobjects.Browser; import teammates.test.pageobjects.BrowserPool; /** * Annotations for Performance tests with * <ul> * <li>Name: name of the test</li> * <li>CustomTimer: (default is false) if true, the function will return the duration need to recorded itself. * If false, the function return the status of the test and expected the function * which called it to record the duration.</li> * </ul> */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @interface PerformanceTest { String name() default ""; boolean customTimer() default false; } /** * Usage: This script is to profile performance of the app with id in test.properties. To run multiple instance * of this script in parallel, use ParallelProfiler.Java. * * <p>Notes: * <ul> * <li>Edit name of the report file, the result will be written to a file in src/test/resources/data folder</li> * <li>Make sure that the data in PerformanceProfilerImportData.json is imported (by using ImportData.java)</li> * </ul> */ public class PerformanceProfiler extends Thread { private static final String defaultReportPath = TestProperties.TEST_DATA_FOLDER + "/" + "nameOfTheReportFile.txt"; private static final int NUM_OF_RUNS = 2; private static final int WAIT_TIME_TEST = 1000; //waiting time between tests, in ms private static final int WAIT_TIME_RUN = 5000; //waiting time between runs, in ms private static final String runningDataSourceFile = "PerformanceProfilerRunningData.json"; private String reportFilePath; private DataBundle data; private Map<String, ArrayList<Float>> results = new HashMap<>(); protected PerformanceProfiler(String path) { reportFilePath = path; } @Override public void run() { //Data used for profiling String jsonString = ""; try { jsonString = FileHelper.readFile(TestProperties.TEST_DATA_FOLDER + "/" + runningDataSourceFile); } catch (IOException e) { e.printStackTrace(); } data = JsonUtils.fromJson(jsonString, DataBundle.class); //Import previous results try { results = importReportFile(reportFilePath); } catch (IOException e) { e.printStackTrace(); } Browser browser; for (int i = 0; i < NUM_OF_RUNS; i++) { browser = BrowserPool.getBrowser(); //overcome initial loading time with the below line //getInstructorAsJson(); //get all methods with annotation and record time Method[] methods = PerformanceProfiler.class.getMethods(); for (Method method : methods) { performMethod(method); } // Wait between runs BrowserPool.release(browser); try { Thread.sleep(WAIT_TIME_RUN); } catch (InterruptedException e) { e.printStackTrace(); } } // Write the results back to file try { printResult(reportFilePath); } catch (IOException e) { e.printStackTrace(); } System.out.print("\n Finished!"); } /** * This function perform the method and print the return value for debugging. */ private void performMethod(Method method) { if (method.isAnnotationPresent(PerformanceTest.class)) { PerformanceTest test = method.getAnnotation(PerformanceTest.class); String name = test.name(); boolean customTimer = test.customTimer(); Type type = method.getReturnType(); if (!results.containsKey(name)) { results.put(name, new ArrayList<Float>()); } try { float duration = 0; if (type.equals(String.class) && !customTimer) { long startTime = System.nanoTime(); Object retVal = method.invoke(this); long endTime = System.nanoTime(); duration = (float) ((endTime - startTime) / 1000000.0); //in miliSecond System.out.print("Name: " + name + "\tTime: " + duration + "\tVal: " + retVal.toString() + "\n"); } else if (type.equals(Long.class) && customTimer) { duration = (float) ((Long) method.invoke(this) / 1000000.0); System.out.print("Name: " + name + "\tTime: " + duration + "\n"); } // Add new duration to the arrayList of the test. ArrayList<Float> countList = results.get(name); countList.add(duration); } catch (Exception e) { System.out.print(e.toString()); } // reduce chance of data not being persisted try { Thread.sleep(WAIT_TIME_TEST); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * Run this script as an single-thread Java application (for simple, non-parallel profiling). * For parallel profiling, please use ParallelProfiler.java. */ public static void main(String[] args) { // Run this script as an single-thread Java application (for simple, non-parallel profiling) // For parallel profiling, please use ParallelProfiler.java new PerformanceProfiler(defaultReportPath).start(); } /** * The results from file stored in filePath. * @return {@code HashMap<nameOfTest, durations>} of the report stored in filePath */ private static HashMap<String, ArrayList<Float>> importReportFile(String filePath) throws IOException { HashMap<String, ArrayList<Float>> results = new HashMap<>(); File reportFile = new File(filePath); // Create the report file if not existed if (!reportFile.exists()) { try { reportFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } return results; } //Import old data to the HashMap BufferedReader br = new BufferedReader(new FileReader(filePath)); String strLine; while ((strLine = br.readLine()) != null) { System.out.println(strLine); String[] strs = strLine.split("\\|"); String testName = strs[0]; String[] durations = strs[2].split("\\,"); ArrayList<Float> arr = new ArrayList<>(); for (String str : durations) { Float f = Float.parseFloat(str); arr.add(f); } results.put(testName, arr); } br.close(); return results; } /** * Writes the results to the file with path filePath. */ private void printResult(String filePath) throws IOException { List<String> list = new ArrayList<>(); for (String str : results.keySet()) { list.add(str); } Collections.sort(list); FileWriter fstream = new FileWriter(filePath); BufferedWriter out = new BufferedWriter(fstream); for (String str : list) { StringBuilder lineStrBuilder = new StringBuilder(); ArrayList<Float> arr = results.get(str); Float total = 0.0f; for (Float f : arr) { total += f; lineStrBuilder.append(f).append(" , "); } String lineStr = lineStrBuilder.substring(0, lineStrBuilder.length() - 3); //remove last comma Float average = total / arr.size(); out.write(str + "| " + average + " | " + lineStr + "\n"); } out.close(); } // TODO: this class needs to be tweaked to work with the new Browser class // Performance Tests , the order of these tests is also the order they will run /* @PerformanceTest(name = "Instructor login",customTimer = true) public Long instructorLogin() { browser.goToUrl(TestProperties.TEAMMATES_URL); browser.click(browser.instructorLoginButton); long startTime = System.nanoTime(); browser.login("testingforteammates@gmail.com", "testingforteammates", false); return System.nanoTime()-startTime; } @PerformanceTest(name = "Instructor home page") String instructorHomePage() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorHome"); return ""; } @PerformanceTest(name = "Instructor eval page") public String instructorEval() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorEval"); return ""; } @PerformanceTest(name = "Instructor add eval",customTimer = true) public Long instructorAddEval() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.add(Calendar.DATE, +1); Date date1 = cal.getTime(); cal.add(Calendar.DATE, +2); Date date2 = cal.getTime(); long startTime = System.nanoTime(); browser.addEvaluation("idOf_Z2_Cou0_of_Coo0", "test", date1, date2, true, "This is the instructions, please follow", 5); browser.waitForStatusMessage(Common.STATUS_EVALUATION_ADDED); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor eval page") public String instructorEval2() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorEval"); return ""; } @PerformanceTest(name = "Instructor delete eval*",customTimer = true) public Long instructorDeleteEval() { int evalRowID = browser.getEvaluationRowID("idOf_Z2_Cou0_of_Coo0", "test"); By deleteLinkLocator = browser.getInstructorEvaluationDeleteLinkLocator(evalRowID); long startTime =System.nanoTime(); browser.clickAndConfirm(deleteLinkLocator); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor course page") public String instructorCourse() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourse"); return ""; } @PerformanceTest(name = "Instructor add course",customTimer = true) public Long instructorAddCourse() { long startTime = System.nanoTime(); browser.addCourse("testcourse", "testcourse"); browser.waitForStatusMessage(Common.STATUS_COURSE_ADDED); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor course page") public String instructorCourse2() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourse"); return ""; } @PerformanceTest(name = "Instructor delete course*",customTimer = true) public Long instructorDeleteCourse() throws Exception { String courseId = "testcourse"; int courseRowId = browser.getCourseRowID(courseId); By deleteLinkLocator = browser.getInstructorCourseDeleteLinkLocator(courseRowId); long startTime = System.nanoTime(); browser.clickAndConfirm(deleteLinkLocator); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor course student detail page") public String instructorCourseStudentDetails() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourseStudentDetails?courseid=idOf_Z2_Cou0_of_Coo0" + "&studentemail=testingforteammates%40gmail.com"); return ""; } @PerformanceTest(name = "Instructor course enroll page") public String instructorCourseEnroll() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourseEnroll?courseid=idOf_Z2_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Instructor course enroll student*",customTimer = true) public Long instructorCourseEnrollStudent() { String enrollString = "Team 1 | teststudent | alice.b.tmms@gmail.com | This comment has been changed\n"; browser.fillString(By.id("enrollstudents"), enrollString); long startTime = System.nanoTime(); browser.click(By.id("button_enroll")); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor course enroll page") public String instructorCourseDetails() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorCourseDetails?courseid=idOf_Z2_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Instructor course delete student *",customTimer = true) public Long instructorCourseDeleteStudent() { int studentRowId = browser.getStudentRowId("teststudent"); long startTime = System.nanoTime(); browser.clickInstructorCourseDetailStudentDeleteAndConfirm(studentRowId); return System.nanoTime() - startTime; } @PerformanceTest(name = "Instructor eval results") public String instructorEvalResults() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorEvalResults?courseid=idOf_Z2_Cou0_of_Coo0" + "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Instructor view student eval ") public String instructorViewStuEval() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/instructorEvalSubmissionView?courseid=idOf_Z2_Cou0_of_Coo0" + "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0&studentemail=Z2_Stu59Email%40gmail.com"); return ""; } @PerformanceTest(name = "Instructor help page ") public String instructorHelp() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/instructorHelp.jsp"); return ""; } @PerformanceTest(name = "Instructor log out") public String instructorLogout() { browser.logout(); return ""; } @PerformanceTest(name = "Student login") public String stuLogin() { browser.loginStudent("testingforteammates@gmail.com","testingforteammates"); return ""; } @PerformanceTest(name = "Student homepage") public String stuHomepage() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentHome"); return ""; } @PerformanceTest(name = "Student course detail page") public String stuCoursepage() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentCourseDetails?courseid=idOf_Z2_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Student edit submission page") public String stuEditSubmissionPage() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentEvalEdit?courseid=idOf_Z2_Cou0_of_Coo0" + "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Student edit submission ") public String stuEditSubmission() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentCourseDetails?courseid=idOf_Z2_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Student eval result ") public String stuEvalResultPage() { browser.goToUrl(TestProperties.TEAMMATES_URL + "/page/studentEvalResults?courseid=idOf_Z2_Cou0_of_Coo0" + "&evaluationname=Z2_Eval0_in_Cou0_of_Coo0"); return ""; } @PerformanceTest(name = "Student log out") public String stuLogout() { browser.logout(); return ""; } @PerformanceTest(name = "BD create instructor") public String createInstructor() { String status = ""; Set<String> set = data.instructors.keySet(); for (String instructorKey : set) { InstructorAttributes instructor = data.instructors.get(instructorKey); status += BackDoor.createInstructor(instructor); } return status; } @PerformanceTest(name = "BD get instructor") public String getInstructorAsJson() { String status = ""; Set<String> set = data.instructors.keySet(); for (String instructorKey : set) { InstructorAttributes instructor = data.instructors.get(instructorKey); status += BackDoor.getInstructorAsJson(instructor.googleId, instructor.courseId); } return status; } @PerformanceTest(name = "BD get courses by instructor") public String getCoursesByInstructor() { String status = ""; Set<String> set = data.instructors.keySet(); for (String instructorKey : set) { InstructorAttributes instructor = data.instructors.get(instructorKey); String[] courses = BackDoor.getCoursesByInstructorId(instructor.googleId); for (String courseName : courses) { status += " " + courseName; } } return status; } @PerformanceTest(name = "BD create course") public String createCourse() { String status = ""; Set<String> set = data.courses.keySet(); for (String courseKey : set) { CourseAttributes course = data.courses.get(courseKey); status += " " + BackDoor.createCourse(course); } return status; } @PerformanceTest(name = "BD get course") public String getCourseAsJson() { String status = ""; Set<String> set = data.courses.keySet(); for (String courseKey : set) { CourseAttributes course = data.courses.get(courseKey); status += " " + BackDoor.getCourseAsJson(course.id); } return status; } @PerformanceTest(name = "BD create student") public String createStudent() { String status = ""; Set<String> set = data.students.keySet(); for (String studentKey : set) { StudentAttributes student = data.students.get(studentKey); status += " " + BackDoor.createStudent(student); } return status; } // The method createSubmission is not implemented in BackDoor yet. @PerformanceTest(name = "BD create submission") static public String createSubmissions() { String status = ""; Set<String> set = data.submissions.keySet(); for (String submissionKey : set) { SubmissionData submission = data.submissions.get(submissionKey); status += " " + BackDoor.createSubmission(submission); } return status; } */ @PerformanceTest(name = "BD get student") public String getStudent() { StringBuilder status = new StringBuilder(); Set<String> set = data.getStudents().keySet(); for (String studentKey : set) { StudentAttributes student = data.getStudents().get(studentKey); status.append(' ').append(JsonUtils.toJson(BackDoor.getStudent(student.course, student.email))); } return status.toString(); } @PerformanceTest(name = "BD get key for student") public String getKeyForStudent() { StringBuilder status = new StringBuilder(); Set<String> set = data.getStudents().keySet(); for (String studentKey : set) { StudentAttributes student = data.getStudents().get(studentKey); status.append(' ').append(BackDoor.getEncryptedKeyForStudent(student.course, student.email)); } return status.toString(); } @PerformanceTest(name = "BD edit student") public String editStudent() { StringBuilder status = new StringBuilder(); Set<String> set = data.getStudents().keySet(); for (String studentKey : set) { StudentAttributes student = data.getStudents().get(studentKey); status.append(' ').append(BackDoor.editStudent(student.email, student)); } return status.toString(); } @PerformanceTest(name = "BD delete student") public String deleteStudent() { StringBuilder status = new StringBuilder(); Set<String> set = data.getStudents().keySet(); for (String studentKey : set) { StudentAttributes student = data.getStudents().get(studentKey); status.append(' ').append(BackDoor.deleteStudent(student.course, student.email)); } return status.toString(); } @PerformanceTest(name = "BD Delete Course") public String deleteCourse() { StringBuilder status = new StringBuilder(); Set<String> set = data.getCourses().keySet(); for (String courseKey : set) { CourseAttributes course = data.getCourses().get(courseKey); status.append(' ').append(BackDoor.deleteCourse(course.getId())); } return status.toString(); } @PerformanceTest(name = "BD Delete Instructor") public String deleteInstructor() { StringBuilder status = new StringBuilder(); Set<String> set = data.getInstructors().keySet(); for (String instructorKey : set) { InstructorAttributes instructor = data.getInstructors().get(instructorKey); status.append(BackDoor.deleteInstructor(instructor.email, instructor.courseId)); } return status.toString(); } }
Gorgony/teammates
src/client/java/teammates/client/scripts/PerformanceProfiler.java
Java
gpl-2.0
22,398
/* * Copyright (C) 2013-2014 Stefan Ascher <sa14@stievie.mooo.com> * * This file is part of Giddo. * * Giddo 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. * Giddo 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 Giddo. If not, see <http://www.gnu.org/licenses/>. */ function dayDiff(first, second) { return Math.round((second - first) / (1000 * 60 * 60 * 24)); } $(document).ready(function() { var now = new Date(); var nowUtc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds()); $.each($(".date-time"), function() { var val = $(this).text(); var dt = val.split(" "); var date = dt[0].split("-"); var then = new Date(Date.UTC(parseInt(date[0]), parseInt(date[1]) - 1, parseInt(date[2]))); var daysSince = dayDiff(then, nowUtc); var time = dt[1].split(":"); var years = now.getFullYear() - parseInt(date[0]); if (years !== 0) return; $(this).attr("title", val); var months = (now.getMonth() + 1) - parseInt(date[1]); if (daysSince > 29) { if (months > 1) { $(this).text(months + " months ago"); return; } if (months === 1) { $(this).text(months + " month ago"); return; } } if (daysSince > 1) { $(this).text(daysSince + " days ago"); return; } if (daysSince === 1) { $(this).text(daysSince + " day ago"); return; } var hours = now.getHours() - parseInt(time[0]); if (hours > 1) { $(this).text(hours + " hours ago"); return; } if (hours === 1) { $(this).text(hours + " hour ago"); return; } var mins = now.getMinutes() - parseInt(time[1]); if (mins > 1) { $(this).text(mins + " minutes ago"); return; } if (mins === 1) { $(this).text(mins + " minute ago"); return; } var secs = now.getSeconds() - parseInt(time[2]); if (secs > 1) { $(this).text(secs + " seconds ago"); return; } if (secs === 1) { $(this).text(secs + " second ago"); return; } $(this).text("right now"); }); $.each($(".time"), function() { var val = $(this).text(); var dt = val.split(" "); $(this).attr("title", val); $(this).text(dt[1]); }); });
stievie/Giddo
js/datetime.js
JavaScript
gpl-2.0
2,848
/* * Copyright (c) 1998-2015 Caucho Technology -- all rights reserved * * This file is part of Baratine(TM)(TM) * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Baratine 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. * * Baratine 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Baratine; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package io.baratine.pipe; import java.util.Map; /** * General message type for pipes. * * This Message API is designed to improve interoperability by providing a * useful default API. While pipes can use any message type, general messages * drivers like an AMQP broker or a mail sender need to choose one of * their own. * * Applications may be better served by using application-specific messages. * * @param <T> type of the encapsulated value */ public interface Message<T> { /** * Method value returns encapsulated message value. * * @return encapsulated value */ T value(); /** * Method headers returns optional header passed with the message * * @return map of headers */ Map<String,Object> headers(); /** * Method header returns value of a header matching a key * * @param key header key * @return header value */ Object header(String key); /** * Create an instance of a MessageBuilder using passed value as an encapsulated * Message value. * * @param value value to encapsulate in a message * @param <X> type of the value * @return an instance of MessageBuilder */ static <X> MessageBuilder<X> newMessage(X value) { return new MessageImpl<>(value); } /** * MessageBuilder interface allows setting properties for a Message, such as * headers. * * @param <T> type of a value encapsulated in a Message */ interface MessageBuilder<T> extends Message<T> { MessageBuilder<T> header(String key, Object value); } }
baratine/baratine
api/src/main/java/io/baratine/pipe/Message.java
Java
gpl-2.0
2,551
package org.caliog.myRPG.Mobs; import org.bukkit.entity.Entity; import org.caliog.myRPG.Manager; import org.caliog.myRPG.Entities.PlayerManager; import org.caliog.myRPG.Entities.myClass; import org.caliog.myRPG.Utils.EntityUtils; public class PetController { public static void controll() { for (final myClass player : PlayerManager.getPlayers()) { if (player.getPets().isEmpty()) continue; for (final Pet pet : player.getPets()) { Entity entity = EntityUtils.getEntity(pet.getId(), player.getPlayer().getWorld()); if (entity == null) continue; if (entity.getLocation().distanceSquared(player.getPlayer().getLocation()) > 512) { Manager.scheduleTask(new Runnable() { @Override public void run() { pet.die(player); } }); } } } } }
caliog/myRPG
src/org/caliog/myRPG/Mobs/PetController.java
Java
gpl-2.0
811
/* Elysian Fields is a 2D game programmed in C# with the framework MonoGame Copyright (C) 2015 Erik Iwarson If you have any questions, don't hesitate to send me an e-mail at erikiwarson@gmail.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 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. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Elysian_Fields { class DamageObject { public Creature creature; public int ID; public int damageDealt; public int EndTime; public int StartTime; public const int Steps = 30; public const int DamageDuration = 1000; public const int Text_Damage = 1; public const int Text_Healing = 2; public const int Text_Experience = 3; public int StepDuration { get { return DamageDuration / Steps; } set { } } public int CurrentStep = 0; public int Text_Type = 0; //public bool Healing; //public int OffsetX public Coordinates Position = new Coordinates(); //public int StartOffsetX; public double StartOffsetY = 15; //public int EndOffsetX; //public int EndOffsetY = 0; public DamageObject() { ID = -1; } public DamageObject(Creature monster, int Damage, int _text_type, int _StartTime, int _EndTime, int id = 0, Coordinates pos = null) { creature = monster; damageDealt = Damage; ID = id; EndTime = _EndTime; StartTime = _StartTime; Position = pos; Text_Type = _text_type; } public double OffsetY(int CurrentTime) { double CurrentStepEndTime = StartTime + DamageDuration - ((Steps - CurrentStep) * StepDuration); if (CurrentTime >= CurrentStepEndTime) { if(CurrentStep < Steps) CurrentStep++; } return StartOffsetY - (CurrentStep * (StartOffsetY / Steps)); } } }
Szune/Elysian-Fields
Elysian Fields/Elysian Fields/DamageObject.cs
C#
gpl-2.0
2,733
/* * Copyright 2001-2004 The Apache Software Foundation. * * 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.apache.xerces.impl.xs; import java.util.Vector; import org.apache.xerces.impl.Constants; import org.apache.xerces.impl.dv.SchemaDVFactory; import org.apache.xerces.impl.dv.ValidatedInfo; import org.apache.xerces.impl.dv.XSSimpleType; import org.apache.xerces.impl.xs.identity.IdentityConstraint; import org.apache.xerces.impl.xs.util.SimpleLocator; import org.apache.xerces.impl.xs.util.StringListImpl; import org.apache.xerces.impl.xs.util.XSNamedMap4Types; import org.apache.xerces.impl.xs.util.XSNamedMapImpl; import org.apache.xerces.impl.xs.util.XSObjectListImpl; import org.apache.xerces.parsers.DOMParser; import org.apache.xerces.parsers.IntegratedParserConfiguration; import org.apache.xerces.parsers.SAXParser; import org.apache.xerces.util.SymbolHash; import org.apache.xerces.util.SymbolTable; import org.apache.xerces.xni.NamespaceContext; import org.apache.xerces.xni.grammars.XMLGrammarDescription; import org.apache.xerces.xni.grammars.XSGrammar; import org.apache.xerces.xs.StringList; import org.apache.xerces.xs.XSAnnotation; import org.apache.xerces.xs.XSAttributeDeclaration; import org.apache.xerces.xs.XSAttributeGroupDefinition; import org.apache.xerces.xs.XSConstants; import org.apache.xerces.xs.XSElementDeclaration; import org.apache.xerces.xs.XSModel; import org.apache.xerces.xs.XSModelGroupDefinition; import org.apache.xerces.xs.XSNamedMap; import org.apache.xerces.xs.XSNamespaceItem; import org.apache.xerces.xs.XSNotationDeclaration; import org.apache.xerces.xs.XSObjectList; import org.apache.xerces.xs.XSParticle; import org.apache.xerces.xs.XSTypeDefinition; import org.apache.xerces.xs.XSWildcard; /** * This class is to hold all schema component declaration that are declared * within one namespace. * * The Grammar class this class extends contains what little * commonality there is between XML Schema and DTD grammars. It's * useful to distinguish grammar objects from other kinds of object * when they exist in pools or caches. * * @xerces.internal * * @author Sandy Gao, IBM * @author Elena Litani, IBM * * @version $Id: SchemaGrammar.java,v 1.42 2004/12/15 23:48:48 mrglavas Exp $ */ public class SchemaGrammar implements XSGrammar, XSNamespaceItem { // the target namespace of grammar String fTargetNamespace; // global decls: map from decl name to decl object SymbolHash fGlobalAttrDecls; SymbolHash fGlobalAttrGrpDecls; SymbolHash fGlobalElemDecls; SymbolHash fGlobalGroupDecls; SymbolHash fGlobalNotationDecls; SymbolHash fGlobalIDConstraintDecls; SymbolHash fGlobalTypeDecls; // the XMLGrammarDescription member XSDDescription fGrammarDescription = null; // annotations associated with the "root" schema of this targetNamespace XSAnnotationImpl [] fAnnotations = null; // number of annotations declared int fNumAnnotations; // symbol table for constructing parsers (annotation support) private SymbolTable fSymbolTable = null; // parsers for annotation support private SAXParser fSAXParser = null; private DOMParser fDOMParser = null; // // Constructors // // needed to make BuiltinSchemaGrammar work. protected SchemaGrammar() {} /** * Default constructor. * * @param targetNamespace * @param grammarDesc the XMLGrammarDescription corresponding to this objec * at the least a systemId should always be known. * @param symbolTable needed for annotation support */ public SchemaGrammar(String targetNamespace, XSDDescription grammarDesc, SymbolTable symbolTable) { fTargetNamespace = targetNamespace; fGrammarDescription = grammarDesc; fSymbolTable = symbolTable; // REVISIT: do we know the numbers of the following global decls // when creating this grammar? If so, we can pass the numbers in, // and use that number to initialize the following hashtables. fGlobalAttrDecls = new SymbolHash(); fGlobalAttrGrpDecls = new SymbolHash(); fGlobalElemDecls = new SymbolHash(); fGlobalGroupDecls = new SymbolHash(); fGlobalNotationDecls = new SymbolHash(); fGlobalIDConstraintDecls = new SymbolHash(); // if we are parsing S4S, put built-in types in first // they might get overwritten by the types from S4S, but that's // considered what the application wants to do. if (fTargetNamespace == SchemaSymbols.URI_SCHEMAFORSCHEMA) fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls.makeClone(); else fGlobalTypeDecls = new SymbolHash(); } // <init>(String, XSDDescription) // number of built-in XSTypes we need to create for base and full // datatype set private static final int BASICSET_COUNT = 29; private static final int FULLSET_COUNT = 46; private static final int GRAMMAR_XS = 1; private static final int GRAMMAR_XSI = 2; // this class makes sure the static, built-in schema grammars // are immutable. public static class BuiltinSchemaGrammar extends SchemaGrammar { /** * Special constructor to create the grammars for the schema namespaces * * @param grammar */ public BuiltinSchemaGrammar(int grammar) { SchemaDVFactory schemaFactory = SchemaDVFactory.getInstance(); if (grammar == GRAMMAR_XS) { // target namespace fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA; // grammar description fGrammarDescription = new XSDDescription(); fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA); // no global decls other than types fGlobalAttrDecls = new SymbolHash(1); fGlobalAttrGrpDecls = new SymbolHash(1); fGlobalElemDecls = new SymbolHash(1); fGlobalGroupDecls = new SymbolHash(1); fGlobalNotationDecls = new SymbolHash(1); fGlobalIDConstraintDecls = new SymbolHash(1); // get all built-in types fGlobalTypeDecls = schemaFactory.getBuiltInTypes(); // add anyType fGlobalTypeDecls.put(fAnyType.getName(), fAnyType); } else if (grammar == GRAMMAR_XSI) { // target namespace fTargetNamespace = SchemaSymbols.URI_XSI; // grammar description fGrammarDescription = new XSDDescription(); fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; fGrammarDescription.setNamespace(SchemaSymbols.URI_XSI); // no global decls other than attributes fGlobalAttrGrpDecls = new SymbolHash(1); fGlobalElemDecls = new SymbolHash(1); fGlobalGroupDecls = new SymbolHash(1); fGlobalNotationDecls = new SymbolHash(1); fGlobalIDConstraintDecls = new SymbolHash(1); fGlobalTypeDecls = new SymbolHash(1); // 4 attributes, so initialize the size as 4*2 = 8 fGlobalAttrDecls = new SymbolHash(8); String name = null; String tns = null; XSSimpleType type = null; short scope = XSConstants.SCOPE_GLOBAL; // xsi:type name = SchemaSymbols.XSI_TYPE; tns = SchemaSymbols.URI_XSI; type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_QNAME); fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope)); // xsi:nil name = SchemaSymbols.XSI_NIL; tns = SchemaSymbols.URI_XSI; type = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_BOOLEAN); fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope)); XSSimpleType anyURI = schemaFactory.getBuiltInType(SchemaSymbols.ATTVAL_ANYURI); // xsi:schemaLocation name = SchemaSymbols.XSI_SCHEMALOCATION; tns = SchemaSymbols.URI_XSI; type = schemaFactory.createTypeList(null, SchemaSymbols.URI_XSI, (short)0, anyURI, null); fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope)); // xsi:noNamespaceSchemaLocation name = SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION; tns = SchemaSymbols.URI_XSI; type = anyURI; fGlobalAttrDecls.put(name, new BuiltinAttrDecl(name, tns, type, scope)); } } // <init>(int) // return the XMLGrammarDescription corresponding to this // object public XMLGrammarDescription getGrammarDescription() { return fGrammarDescription.makeClone(); } // getGrammarDescription(): XMLGrammarDescription // override these methods solely so that these // objects cannot be modified once they're created. public void setImportedGrammars(Vector importedGrammars) { // ignore } public void addGlobalAttributeDecl(XSAttributeDecl decl) { // ignore } public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) { // ignore } public void addGlobalElementDecl(XSElementDecl decl) { // ignore } public void addGlobalGroupDecl(XSGroupDecl decl) { // ignore } public void addGlobalNotationDecl(XSNotationDecl decl) { // ignore } public void addGlobalTypeDecl(XSTypeDefinition decl) { // ignore } public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) { // ignore } public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) { // ignore } public synchronized void addDocument(Object document, String location) { // ignore } // annotation support synchronized DOMParser getDOMParser() { return null; } synchronized SAXParser getSAXParser() { return null; } } /** * <p>A partial schema for schemas for validating annotations.</p> * * @xerces.internal * * @author Michael Glavassevich, IBM */ public static final class Schema4Annotations extends SchemaGrammar { /** * Special constructor to create a schema * capable of validating annotations. */ public Schema4Annotations() { // target namespace fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA; // grammar description fGrammarDescription = new XSDDescription(); fGrammarDescription.fContextType = XSDDescription.CONTEXT_PREPARSE; fGrammarDescription.setNamespace(SchemaSymbols.URI_SCHEMAFORSCHEMA); // no global decls other than types and // element declarations for <annotation>, <documentation> and <appinfo>. fGlobalAttrDecls = new SymbolHash(1); fGlobalAttrGrpDecls = new SymbolHash(1); fGlobalElemDecls = new SymbolHash(6); fGlobalGroupDecls = new SymbolHash(1); fGlobalNotationDecls = new SymbolHash(1); fGlobalIDConstraintDecls = new SymbolHash(1); // get all built-in types fGlobalTypeDecls = SG_SchemaNS.fGlobalTypeDecls; // create element declarations for <annotation>, <documentation> and <appinfo> XSElementDecl annotationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_ANNOTATION); XSElementDecl documentationDecl = createAnnotationElementDecl(SchemaSymbols.ELT_DOCUMENTATION); XSElementDecl appinfoDecl = createAnnotationElementDecl(SchemaSymbols.ELT_APPINFO); // add global element declarations fGlobalElemDecls.put(annotationDecl.fName, annotationDecl); fGlobalElemDecls.put(documentationDecl.fName, documentationDecl); fGlobalElemDecls.put(appinfoDecl.fName, appinfoDecl); // create complex type declarations for <annotation>, <documentation> and <appinfo> XSComplexTypeDecl annotationType = new XSComplexTypeDecl(); XSComplexTypeDecl documentationType = new XSComplexTypeDecl(); XSComplexTypeDecl appinfoType = new XSComplexTypeDecl(); // set the types on their element declarations annotationDecl.fType = annotationType; documentationDecl.fType = documentationType; appinfoDecl.fType = appinfoType; // create attribute groups for <annotation>, <documentation> and <appinfo> XSAttributeGroupDecl annotationAttrs = new XSAttributeGroupDecl(); XSAttributeGroupDecl documentationAttrs = new XSAttributeGroupDecl(); XSAttributeGroupDecl appinfoAttrs = new XSAttributeGroupDecl(); // fill in attribute groups { // create and fill attribute uses for <annotation>, <documentation> and <appinfo> XSAttributeUseImpl annotationIDAttr = new XSAttributeUseImpl(); annotationIDAttr.fAttrDecl = new XSAttributeDecl(); annotationIDAttr.fAttrDecl.setValues(SchemaSymbols.ATT_ID, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ID), XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, annotationType, null); annotationIDAttr.fUse = SchemaSymbols.USE_OPTIONAL; annotationIDAttr.fConstraintType = XSConstants.VC_NONE; XSAttributeUseImpl documentationSourceAttr = new XSAttributeUseImpl(); documentationSourceAttr.fAttrDecl = new XSAttributeDecl(); documentationSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI), XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null); documentationSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL; documentationSourceAttr.fConstraintType = XSConstants.VC_NONE; XSAttributeUseImpl documentationLangAttr = new XSAttributeUseImpl(); documentationLangAttr.fAttrDecl = new XSAttributeDecl(); documentationLangAttr.fAttrDecl.setValues("lang".intern(), NamespaceContext.XML_URI, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_LANGUAGE), XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, documentationType, null); documentationLangAttr.fUse = SchemaSymbols.USE_OPTIONAL; documentationLangAttr.fConstraintType = XSConstants.VC_NONE; XSAttributeUseImpl appinfoSourceAttr = new XSAttributeUseImpl(); appinfoSourceAttr.fAttrDecl = new XSAttributeDecl(); appinfoSourceAttr.fAttrDecl.setValues(SchemaSymbols.ATT_SOURCE, null, (XSSimpleType) fGlobalTypeDecls.get(SchemaSymbols.ATTVAL_ANYURI), XSConstants.VC_NONE, XSConstants.SCOPE_LOCAL, null, appinfoType, null); appinfoSourceAttr.fUse = SchemaSymbols.USE_OPTIONAL; appinfoSourceAttr.fConstraintType = XSConstants.VC_NONE; // create lax attribute wildcard for <annotation>, <documentation> and <appinfo> XSWildcardDecl otherAttrs = new XSWildcardDecl(); otherAttrs.fNamespaceList = new String [] {fTargetNamespace, null}; otherAttrs.fType = XSWildcard.NSCONSTRAINT_NOT; otherAttrs.fProcessContents = XSWildcard.PC_LAX; // add attribute uses and wildcards to attribute groups for <annotation>, <documentation> and <appinfo> annotationAttrs.addAttributeUse(annotationIDAttr); annotationAttrs.fAttributeWC = otherAttrs; documentationAttrs.addAttributeUse(documentationSourceAttr); documentationAttrs.addAttributeUse(documentationLangAttr); documentationAttrs.fAttributeWC = otherAttrs; appinfoAttrs.addAttributeUse(appinfoSourceAttr); appinfoAttrs.fAttributeWC = otherAttrs; } // create particles for <annotation> XSParticleDecl annotationParticle = createUnboundedModelGroupParticle(); { XSModelGroupImpl annotationChoice = new XSModelGroupImpl(); annotationChoice.fCompositor = XSModelGroupImpl.MODELGROUP_CHOICE; annotationChoice.fParticleCount = 2; annotationChoice.fParticles = new XSParticleDecl[2]; annotationChoice.fParticles[0] = createChoiceElementParticle(appinfoDecl); annotationChoice.fParticles[1] = createChoiceElementParticle(documentationDecl); annotationParticle.fValue = annotationChoice; } // create wildcard particle for <documentation> and <appinfo> XSParticleDecl anyWCSequenceParticle = createUnboundedAnyWildcardSequenceParticle(); // fill complex types annotationType.setValues("#AnonType_" + SchemaSymbols.ELT_ANNOTATION, fTargetNamespace, SchemaGrammar.fAnyType, XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION), XSComplexTypeDecl.CONTENTTYPE_ELEMENT, false, annotationAttrs, null, annotationParticle, new XSObjectListImpl(null, 0)); annotationType.setName("#AnonType_" + SchemaSymbols.ELT_ANNOTATION); annotationType.setIsAnonymous(); documentationType.setValues("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION, fTargetNamespace, SchemaGrammar.fAnyType, XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION), XSComplexTypeDecl.CONTENTTYPE_MIXED, false, documentationAttrs, null, anyWCSequenceParticle, new XSObjectListImpl(null, 0)); documentationType.setName("#AnonType_" + SchemaSymbols.ELT_DOCUMENTATION); documentationType.setIsAnonymous(); appinfoType.setValues("#AnonType_" + SchemaSymbols.ELT_APPINFO, fTargetNamespace, SchemaGrammar.fAnyType, XSConstants.DERIVATION_RESTRICTION, XSConstants.DERIVATION_NONE, (short) (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION), XSComplexTypeDecl.CONTENTTYPE_MIXED, false, appinfoAttrs, null, anyWCSequenceParticle, new XSObjectListImpl(null, 0)); appinfoType.setName("#AnonType_" + SchemaSymbols.ELT_APPINFO); appinfoType.setIsAnonymous(); } // <init>(int) // return the XMLGrammarDescription corresponding to this // object public XMLGrammarDescription getGrammarDescription() { return fGrammarDescription.makeClone(); } // getGrammarDescription(): XMLGrammarDescription // override these methods solely so that these // objects cannot be modified once they're created. public void setImportedGrammars(Vector importedGrammars) { // ignore } public void addGlobalAttributeDecl(XSAttributeDecl decl) { // ignore } public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) { // ignore } public void addGlobalElementDecl(XSElementDecl decl) { // ignore } public void addGlobalGroupDecl(XSGroupDecl decl) { // ignore } public void addGlobalNotationDecl(XSNotationDecl decl) { // ignore } public void addGlobalTypeDecl(XSTypeDefinition decl) { // ignore } public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) { // ignore } public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) { // ignore } public synchronized void addDocument(Object document, String location) { // ignore } // annotation support synchronized DOMParser getDOMParser() { return null; } synchronized SAXParser getSAXParser() { return null; } // // private helper methods // private XSElementDecl createAnnotationElementDecl(String localName) { XSElementDecl eDecl = new XSElementDecl(); eDecl.fName = localName; eDecl.fTargetNamespace = fTargetNamespace; eDecl.setIsGlobal(); eDecl.fBlock = (XSConstants.DERIVATION_EXTENSION | XSConstants.DERIVATION_RESTRICTION | XSConstants.DERIVATION_SUBSTITUTION); eDecl.setConstraintType(XSConstants.VC_NONE); return eDecl; } private XSParticleDecl createUnboundedModelGroupParticle() { XSParticleDecl particle = new XSParticleDecl(); particle.fMinOccurs = 0; particle.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED; particle.fType = XSParticleDecl.PARTICLE_MODELGROUP; return particle; } private XSParticleDecl createChoiceElementParticle(XSElementDecl ref) { XSParticleDecl particle = new XSParticleDecl(); particle.fMinOccurs = 1; particle.fMaxOccurs = 1; particle.fType = XSParticleDecl.PARTICLE_ELEMENT; particle.fValue = ref; return particle; } private XSParticleDecl createUnboundedAnyWildcardSequenceParticle() { XSParticleDecl particle = createUnboundedModelGroupParticle(); XSModelGroupImpl sequence = new XSModelGroupImpl(); sequence.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE; sequence.fParticleCount = 1; sequence.fParticles = new XSParticleDecl[1]; sequence.fParticles[0] = createAnyLaxWildcardParticle(); particle.fValue = sequence; return particle; } private XSParticleDecl createAnyLaxWildcardParticle() { XSParticleDecl particle = new XSParticleDecl(); particle.fMinOccurs = 1; particle.fMaxOccurs = 1; particle.fType = XSParticleDecl.PARTICLE_WILDCARD; XSWildcardDecl anyWC = new XSWildcardDecl(); anyWC.fNamespaceList = null; anyWC.fType = XSWildcard.NSCONSTRAINT_ANY; anyWC.fProcessContents = XSWildcard.PC_LAX; particle.fValue = anyWC; return particle; } } // Grammar methods // return the XMLGrammarDescription corresponding to this // object public XMLGrammarDescription getGrammarDescription() { return fGrammarDescription; } // getGrammarDescription(): XMLGrammarDescription // DTDGrammar methods public boolean isNamespaceAware () { return true; } // isNamespaceAware():boolean Vector fImported = null; public void setImportedGrammars(Vector importedGrammars) { fImported = importedGrammars; } public Vector getImportedGrammars() { return fImported; } /** * Returns this grammar's target namespace. */ public final String getTargetNamespace() { return fTargetNamespace; } // getTargetNamespace():String /** * register one global attribute */ public void addGlobalAttributeDecl(XSAttributeDecl decl) { fGlobalAttrDecls.put(decl.fName, decl); } /** * register one global attribute group */ public void addGlobalAttributeGroupDecl(XSAttributeGroupDecl decl) { fGlobalAttrGrpDecls.put(decl.fName, decl); } /** * register one global element */ public void addGlobalElementDecl(XSElementDecl decl) { fGlobalElemDecls.put(decl.fName, decl); // if there is a substitution group affiliation, store in an array, // for further constraint checking: UPA, PD, EDC if (decl.fSubGroup != null) { if (fSubGroupCount == fSubGroups.length) fSubGroups = resize(fSubGroups, fSubGroupCount+INC_SIZE); fSubGroups[fSubGroupCount++] = decl; } } /** * register one global group */ public void addGlobalGroupDecl(XSGroupDecl decl) { fGlobalGroupDecls.put(decl.fName, decl); } /** * register one global notation */ public void addGlobalNotationDecl(XSNotationDecl decl) { fGlobalNotationDecls.put(decl.fName, decl); } /** * register one global type */ public void addGlobalTypeDecl(XSTypeDefinition decl) { fGlobalTypeDecls.put(decl.getName(), decl); } /** * register one identity constraint */ public final void addIDConstraintDecl(XSElementDecl elmDecl, IdentityConstraint decl) { elmDecl.addIDConstraint(decl); fGlobalIDConstraintDecls.put(decl.getIdentityConstraintName(), decl); } /** * get one global attribute */ public final XSAttributeDecl getGlobalAttributeDecl(String declName) { return(XSAttributeDecl)fGlobalAttrDecls.get(declName); } /** * get one global attribute group */ public final XSAttributeGroupDecl getGlobalAttributeGroupDecl(String declName) { return(XSAttributeGroupDecl)fGlobalAttrGrpDecls.get(declName); } /** * get one global element */ public final XSElementDecl getGlobalElementDecl(String declName) { return(XSElementDecl)fGlobalElemDecls.get(declName); } /** * get one global group */ public final XSGroupDecl getGlobalGroupDecl(String declName) { return(XSGroupDecl)fGlobalGroupDecls.get(declName); } /** * get one global notation */ public final XSNotationDecl getGlobalNotationDecl(String declName) { return(XSNotationDecl)fGlobalNotationDecls.get(declName); } /** * get one global type */ public final XSTypeDefinition getGlobalTypeDecl(String declName) { return(XSTypeDefinition)fGlobalTypeDecls.get(declName); } /** * get one identity constraint */ public final IdentityConstraint getIDConstraintDecl(String declName) { return(IdentityConstraint)fGlobalIDConstraintDecls.get(declName); } /** * get one identity constraint */ public final boolean hasIDConstraints() { return fGlobalIDConstraintDecls.getLength() > 0; } // array to store complex type decls private static final int INITIAL_SIZE = 16; private static final int INC_SIZE = 16; private int fCTCount = 0; private XSComplexTypeDecl[] fComplexTypeDecls = new XSComplexTypeDecl[INITIAL_SIZE]; private SimpleLocator[] fCTLocators = new SimpleLocator[INITIAL_SIZE]; // an array to store groups being redefined by restriction // even-numbered elements are the derived groups, odd-numbered ones their bases private static final int REDEFINED_GROUP_INIT_SIZE = 2; private int fRGCount = 0; private XSGroupDecl[] fRedefinedGroupDecls = new XSGroupDecl[REDEFINED_GROUP_INIT_SIZE]; private SimpleLocator[] fRGLocators = new SimpleLocator[REDEFINED_GROUP_INIT_SIZE/2]; // a flag to indicate whether we have checked the 3 constraints on this // grammar. boolean fFullChecked = false; /** * add one complex type decl: for later constraint checking */ public void addComplexTypeDecl(XSComplexTypeDecl decl, SimpleLocator locator) { if (fCTCount == fComplexTypeDecls.length) { fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount+INC_SIZE); fCTLocators = resize(fCTLocators, fCTCount+INC_SIZE); } fCTLocators[fCTCount] = locator; fComplexTypeDecls[fCTCount++] = decl; } /** * add a group redefined by restriction: for later constraint checking */ public void addRedefinedGroupDecl(XSGroupDecl derived, XSGroupDecl base, SimpleLocator locator) { if (fRGCount == fRedefinedGroupDecls.length) { // double array size each time. fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount << 1); fRGLocators = resize(fRGLocators, fRGCount); } fRGLocators[fRGCount/2] = locator; fRedefinedGroupDecls[fRGCount++] = derived; fRedefinedGroupDecls[fRGCount++] = base; } /** * get all complex type decls: for later constraint checking */ final XSComplexTypeDecl[] getUncheckedComplexTypeDecls() { if (fCTCount < fComplexTypeDecls.length) { fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount); fCTLocators = resize(fCTLocators, fCTCount); } return fComplexTypeDecls; } /** * get the error locator of all complex type decls */ final SimpleLocator[] getUncheckedCTLocators() { if (fCTCount < fCTLocators.length) { fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount); fCTLocators = resize(fCTLocators, fCTCount); } return fCTLocators; } /** * get all redefined groups: for later constraint checking */ final XSGroupDecl[] getRedefinedGroupDecls() { if (fRGCount < fRedefinedGroupDecls.length) { fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount); fRGLocators = resize(fRGLocators, fRGCount/2); } return fRedefinedGroupDecls; } /** * get the error locator of all redefined groups */ final SimpleLocator[] getRGLocators() { if (fRGCount < fRedefinedGroupDecls.length) { fRedefinedGroupDecls = resize(fRedefinedGroupDecls, fRGCount); fRGLocators = resize(fRGLocators, fRGCount/2); } return fRGLocators; } /** * after the first-round checking, some types don't need to be checked * against UPA again. here we trim the array to the proper size. */ final void setUncheckedTypeNum(int newSize) { fCTCount = newSize; fComplexTypeDecls = resize(fComplexTypeDecls, fCTCount); fCTLocators = resize(fCTLocators, fCTCount); } // used to store all substitution group information declared in // this namespace private int fSubGroupCount = 0; private XSElementDecl[] fSubGroups = new XSElementDecl[INITIAL_SIZE]; /** * get all substitution group information: for the 3 constraint checking */ final XSElementDecl[] getSubstitutionGroups() { if (fSubGroupCount < fSubGroups.length) fSubGroups = resize(fSubGroups, fSubGroupCount); return fSubGroups; } // anyType and anySimpleType: because there are so many places where // we need direct access to these two types public final static XSComplexTypeDecl fAnyType = new XSAnyType(); private static class XSAnyType extends XSComplexTypeDecl { public XSAnyType () { fName = SchemaSymbols.ATTVAL_ANYTYPE; super.fTargetNamespace = SchemaSymbols.URI_SCHEMAFORSCHEMA; fBaseType = this; fDerivedBy = XSConstants.DERIVATION_RESTRICTION; fContentType = XSComplexTypeDecl.CONTENTTYPE_MIXED; fParticle = null; fAttrGrp = null; } // overridden methods public void setValues(String name, String targetNamespace, XSTypeDefinition baseType, short derivedBy, short schemaFinal, short block, short contentType, boolean isAbstract, XSAttributeGroupDecl attrGrp, XSSimpleType simpleType, XSParticleDecl particle) { // don't allow this. } public void setName(String name){ // don't allow this. } public void setIsAbstractType() { // null implementation } public void setContainsTypeID() { // null implementation } public void setIsAnonymous() { // null implementation } public void reset() { // null implementation } public XSObjectList getAttributeUses() { return new XSObjectListImpl(null, 0); } public XSAttributeGroupDecl getAttrGrp() { XSWildcardDecl wildcard = new XSWildcardDecl(); wildcard.fProcessContents = XSWildcardDecl.PC_LAX; XSAttributeGroupDecl attrGrp = new XSAttributeGroupDecl(); attrGrp.fAttributeWC = wildcard; return attrGrp; } public XSWildcard getAttributeWildcard() { XSWildcardDecl wildcard = new XSWildcardDecl(); wildcard.fProcessContents = XSWildcardDecl.PC_LAX; return wildcard; } public XSParticle getParticle() { // the wildcard used in anyType (content and attribute) // the spec will change strict to skip for anyType XSWildcardDecl wildcard = new XSWildcardDecl(); wildcard.fProcessContents = XSWildcardDecl.PC_LAX; // the particle for the content wildcard XSParticleDecl particleW = new XSParticleDecl(); particleW.fMinOccurs = 0; particleW.fMaxOccurs = SchemaSymbols.OCCURRENCE_UNBOUNDED; particleW.fType = XSParticleDecl.PARTICLE_WILDCARD; particleW.fValue = wildcard; // the model group of a sequence of the above particle XSModelGroupImpl group = new XSModelGroupImpl(); group.fCompositor = XSModelGroupImpl.MODELGROUP_SEQUENCE; group.fParticleCount = 1; group.fParticles = new XSParticleDecl[1]; group.fParticles[0] = particleW; // the content of anyType: particle of the above model group XSParticleDecl particleG = new XSParticleDecl(); particleG.fType = XSParticleDecl.PARTICLE_MODELGROUP; particleG.fValue = group; return particleG; } public XSObjectList getAnnotations() { return null; } } private static class BuiltinAttrDecl extends XSAttributeDecl { public BuiltinAttrDecl(String name, String tns, XSSimpleType type, short scope) { fName = name; super.fTargetNamespace = tns; fType = type; fScope = scope; } public void setValues(String name, String targetNamespace, XSSimpleType simpleType, short constraintType, short scope, ValidatedInfo valInfo, XSComplexTypeDecl enclosingCT) { // ignore this call. } public void reset () { // also ignore this call. } public XSAnnotation getAnnotation() { return null; } } // class BuiltinAttrDecl // the grammars to hold components of the schema namespace public final static BuiltinSchemaGrammar SG_SchemaNS = new BuiltinSchemaGrammar(GRAMMAR_XS); public final static Schema4Annotations SG_Schema4Annotations = new Schema4Annotations(); public final static XSSimpleType fAnySimpleType = (XSSimpleType)SG_SchemaNS.getGlobalTypeDecl(SchemaSymbols.ATTVAL_ANYSIMPLETYPE); // the grammars to hold components of the schema-instance namespace public final static BuiltinSchemaGrammar SG_XSI = new BuiltinSchemaGrammar(GRAMMAR_XSI); static final XSComplexTypeDecl[] resize(XSComplexTypeDecl[] oldArray, int newSize) { XSComplexTypeDecl[] newArray = new XSComplexTypeDecl[newSize]; System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize)); return newArray; } static final XSGroupDecl[] resize(XSGroupDecl[] oldArray, int newSize) { XSGroupDecl[] newArray = new XSGroupDecl[newSize]; System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize)); return newArray; } static final XSElementDecl[] resize(XSElementDecl[] oldArray, int newSize) { XSElementDecl[] newArray = new XSElementDecl[newSize]; System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize)); return newArray; } static final SimpleLocator[] resize(SimpleLocator[] oldArray, int newSize) { SimpleLocator[] newArray = new SimpleLocator[newSize]; System.arraycopy(oldArray, 0, newArray, 0, Math.min(oldArray.length, newSize)); return newArray; } // XSNamespaceItem methods // the max index / the max value of XSObject type private static final short MAX_COMP_IDX = XSTypeDefinition.SIMPLE_TYPE; private static final boolean[] GLOBAL_COMP = {false, // null true, // attribute true, // element true, // type false, // attribute use true, // attribute group true, // group false, // model group false, // particle false, // wildcard false, // idc true, // notation false, // annotation false, // facet false, // multi value facet true, // complex type true // simple type }; // store a certain kind of components from all namespaces private XSNamedMap[] fComponents = null; // store the documents and their locations contributing to this namespace // REVISIT: use StringList and XSObjectList for there fields. private Vector fDocuments = null; private Vector fLocations = null; public synchronized void addDocument(Object document, String location) { if (fDocuments == null) { fDocuments = new Vector(); fLocations = new Vector(); } fDocuments.addElement(document); fLocations.addElement(location); } /** * [schema namespace] * @see <a href="http://www.w3.org/TR/xmlschema-1/#nsi-schema_namespace">[schema namespace]</a> * @return The target namespace of this item. */ public String getSchemaNamespace() { return fTargetNamespace; } // annotation support synchronized DOMParser getDOMParser() { if (fDOMParser != null) return fDOMParser; // REVISIT: when schema handles XML 1.1, will need to // revisit this (and the practice of not prepending an XML decl to the annotation string IntegratedParserConfiguration config = new IntegratedParserConfiguration(fSymbolTable); // note that this should never produce errors or require // entity resolution, so just a barebones configuration with // a couple of feature set will do fine config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true); config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false); fDOMParser = new DOMParser(config); return fDOMParser; } synchronized SAXParser getSAXParser() { if (fSAXParser != null) return fSAXParser; // REVISIT: when schema handles XML 1.1, will need to // revisit this (and the practice of not prepending an XML decl to the annotation string IntegratedParserConfiguration config = new IntegratedParserConfiguration(fSymbolTable); // note that this should never produce errors or require // entity resolution, so just a barebones configuration with // a couple of feature set will do fine config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, true); config.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE, false); fSAXParser = new SAXParser(config); return fSAXParser; } /** * [schema components]: a list of top-level components, i.e. element * declarations, attribute declarations, etc. * @param objectType The type of the declaration, i.e. * <code>ELEMENT_DECLARATION</code>. Note that * <code>XSTypeDefinition.SIMPLE_TYPE</code> and * <code>XSTypeDefinition.COMPLEX_TYPE</code> can also be used as the * <code>objectType</code> to retrieve only complex types or simple * types, instead of all types. * @return A list of top-level definition of the specified type in * <code>objectType</code> or an empty <code>XSNamedMap</code> if no * such definitions exist. */ public synchronized XSNamedMap getComponents(short objectType) { if (objectType <= 0 || objectType > MAX_COMP_IDX || !GLOBAL_COMP[objectType]) { return XSNamedMapImpl.EMPTY_MAP; } if (fComponents == null) fComponents = new XSNamedMap[MAX_COMP_IDX+1]; // get the hashtable for this type of components if (fComponents[objectType] == null) { SymbolHash table = null; switch (objectType) { case XSConstants.TYPE_DEFINITION: case XSTypeDefinition.COMPLEX_TYPE: case XSTypeDefinition.SIMPLE_TYPE: table = fGlobalTypeDecls; break; case XSConstants.ATTRIBUTE_DECLARATION: table = fGlobalAttrDecls; break; case XSConstants.ELEMENT_DECLARATION: table = fGlobalElemDecls; break; case XSConstants.ATTRIBUTE_GROUP: table = fGlobalAttrGrpDecls; break; case XSConstants.MODEL_GROUP_DEFINITION: table = fGlobalGroupDecls; break; case XSConstants.NOTATION_DECLARATION: table = fGlobalNotationDecls; break; } // for complex/simple types, create a special implementation, // which take specific types out of the hash table if (objectType == XSTypeDefinition.COMPLEX_TYPE || objectType == XSTypeDefinition.SIMPLE_TYPE) { fComponents[objectType] = new XSNamedMap4Types(fTargetNamespace, table, objectType); } else { fComponents[objectType] = new XSNamedMapImpl(fTargetNamespace, table); } } return fComponents[objectType]; } /** * Convenience method. Returns a top-level simple or complex type * definition. * @param name The name of the definition. * @return An <code>XSTypeDefinition</code> or null if such definition * does not exist. */ public XSTypeDefinition getTypeDefinition(String name) { return getGlobalTypeDecl(name); } /** * Convenience method. Returns a top-level attribute declaration. * @param name The name of the declaration. * @return A top-level attribute declaration or null if such declaration * does not exist. */ public XSAttributeDeclaration getAttributeDeclaration(String name) { return getGlobalAttributeDecl(name); } /** * Convenience method. Returns a top-level element declaration. * @param name The name of the declaration. * @return A top-level element declaration or null if such declaration * does not exist. */ public XSElementDeclaration getElementDeclaration(String name) { return getGlobalElementDecl(name); } /** * Convenience method. Returns a top-level attribute group definition. * @param name The name of the definition. * @return A top-level attribute group definition or null if such * definition does not exist. */ public XSAttributeGroupDefinition getAttributeGroup(String name) { return getGlobalAttributeGroupDecl(name); } /** * Convenience method. Returns a top-level model group definition. * * @param name The name of the definition. * @return A top-level model group definition definition or null if such * definition does not exist. */ public XSModelGroupDefinition getModelGroupDefinition(String name) { return getGlobalGroupDecl(name); } /** * Convenience method. Returns a top-level notation declaration. * * @param name The name of the declaration. * @return A top-level notation declaration or null if such declaration * does not exist. */ public XSNotationDeclaration getNotationDeclaration(String name) { return getGlobalNotationDecl(name); } /** * [document location] * @see <a href="http://www.w3.org/TR/xmlschema-1/#sd-document_location">[document location]</a> * @return a list of document information item */ public StringList getDocumentLocations() { return new StringListImpl(fLocations); } /** * Return an <code>XSModel</code> that represents components in this schema * grammar. * * @return an <code>XSModel</code> representing this schema grammar */ public XSModel toXSModel() { return new XSModelImpl(new SchemaGrammar[]{this}); } public XSModel toXSModel(XSGrammar[] grammars) { if (grammars == null || grammars.length == 0) return toXSModel(); int len = grammars.length; boolean hasSelf = false; for (int i = 0; i < len; i++) { if (grammars[i] == this) { hasSelf = true; break; } } SchemaGrammar[] gs = new SchemaGrammar[hasSelf ? len : len+1]; for (int i = 0; i < len; i++) gs[i] = (SchemaGrammar)grammars[i]; if (!hasSelf) gs[len] = this; return new XSModelImpl(gs); } /** * @see org.apache.xerces.xs.XSNamespaceItem#getAnnotations() */ public XSObjectList getAnnotations() { return new XSObjectListImpl(fAnnotations, fNumAnnotations); } public void addAnnotation(XSAnnotationImpl annotation) { if(annotation == null) return; if(fAnnotations == null) { fAnnotations = new XSAnnotationImpl[2]; } else if(fNumAnnotations == fAnnotations.length) { XSAnnotationImpl[] newArray = new XSAnnotationImpl[fNumAnnotations << 1]; System.arraycopy(fAnnotations, 0, newArray, 0, fNumAnnotations); fAnnotations = newArray; } fAnnotations[fNumAnnotations++] = annotation; } } // class SchemaGrammar
BIORIMP/biorimp
BIO-RIMP/test_data/code/xerces/src/org/apache/xerces/impl/xs/SchemaGrammar.java
Java
gpl-2.0
49,139
// ********************************************************************** // // Copyright (c) 2003-2013 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** using Test; using System; using System.Diagnostics; using System.Reflection; [assembly: CLSCompliant(true)] [assembly: AssemblyTitle("IceTest")] [assembly: AssemblyDescription("Ice test")] [assembly: AssemblyCompany("ZeroC, Inc.")] public class Collocated { internal class App : Ice.Application { public override int run(string[] args) { communicator().getProperties().setProperty("TestAdapter.Endpoints", "default -p 12010"); communicator().getProperties().setProperty("Ice.Warn.Dispatch", "0"); Ice.ObjectAdapter adapter = communicator().createObjectAdapter("TestAdapter"); adapter.addServantLocator(new ServantLocatorI("category"), "category"); adapter.addServantLocator(new ServantLocatorI(""), ""); adapter.add(new TestI(), communicator().stringToIdentity("asm")); adapter.add(new TestActivationI(), communicator().stringToIdentity("test/activation")); AllTests.allTests(communicator(), true); return 0; } } public static int Main(string[] args) { App app = new App(); return app.main(args); } }
sbesson/zeroc-ice
cs/test/Ice/servantLocator/Collocated.cs
C#
gpl-2.0
1,521
// This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // Based upon // CDialogMinTrayBtn template class // MFC CDialog with minimize to systemtray button (0.04a) // Supports WinXP styles (thanks to David Yuheng Zhao for CVisualStylesXP - yuheng_zhao@yahoo.com) // // ------------------------------------------------------------ // DialogMinTrayBtn.hpp // zegzav - 2002,2003 - eMule project (http://www.emule-project.net) // ------------------------------------------------------------ // // Modified by Tim Kosse (mailto:tim.kosse@gmx.de) for use within FileZilla #include "StdAfx.h"; #include "MinTrayBtn.h" #include "VisualStylesXP.h" IMPLEMENT_DYNCREATE(CMinTrayBtn, CHookWnd); // ------------------------------ // constants // ------------------------------ #define CAPTION_BUTTONSPACE (2) #define CAPTION_MINHEIGHT (8) #define TIMERMINTRAYBTN_ID 0x76617a67 #define TIMERMINTRAYBTN_PERIOD 200 // ms #define WP_TRAYBUTTON WP_MINBUTTON BEGIN_TM_PART_STATES(TRAYBUTTON) TM_STATE(1, TRAYBS, NORMAL) TM_STATE(2, TRAYBS, HOT) TM_STATE(3, TRAYBS, PUSHED) TM_STATE(4, TRAYBS, DISABLED) // Inactive TM_STATE(5, TRAYBS, INORMAL) TM_STATE(6, TRAYBS, IHOT) TM_STATE(7, TRAYBS, IPUSHED) TM_STATE(8, TRAYBS, IDISABLED) END_TM_PART_STATES() #define BMP_TRAYBTN_WIDTH (21) #define BMP_TRAYBTN_HEIGHT (21) #define BMP_TRAYBTN_BLUE _T("IDB_LUNA_BLUE") #define BMP_TRAYBTN_METALLIC _T("IDB_LUNA_METALLIC") #define BMP_TRAYBTN_HOMESTEAD _T("IDB_LUNA_HOMESTEAD") #define BMP_TRAYBTN_TRANSCOLOR (RGB(255,0,255)) LPCTSTR CMinTrayBtn::m_pszMinTrayBtnBmpName[] = { BMP_TRAYBTN_BLUE, BMP_TRAYBTN_METALLIC, BMP_TRAYBTN_HOMESTEAD }; #define VISUALSTYLESXP_DEFAULTFILE L"LUNA.MSSTYLES" #define VISUALSTYLESXP_BLUE 0 #define VISUALSTYLESXP_METALLIC 1 #define VISUALSTYLESXP_HOMESTEAD 2 #define VISUALSTYLESXP_NAMEBLUE L"NORMALCOLOR" #define VISUALSTYLESXP_NAMEMETALLIC L"METALLIC" #define VISUALSTYLESXP_NAMEHOMESTEAD L"HOMESTEAD" // _WIN32_WINNT >= 0x0501 (XP only) #define _WM_THEMECHANGED 0x031A #define _ON_WM_THEMECHANGED() \ { _WM_THEMECHANGED, 0, 0, 0, AfxSig_l, \ (AFX_PMSG)(AFX_PMSGW) \ (static_cast< LRESULT (AFX_MSG_CALL CWnd::*)(void) > (_OnThemeChanged)) \ }, // _WIN32_WINDOWS >= 0x0410 (95 not supported) BOOL (WINAPI *CMinTrayBtn::_TransparentBlt)(HDC, int, int, int, int, HDC, int, int, int, int, UINT)= NULL; // ------------------------------ // contructor/init // ------------------------------ CMinTrayBtn::CMinTrayBtn(CWnd* pParentWnd) : CHookWnd(FALSE), m_MinTrayBtnPos(0,0), m_MinTrayBtnSize(0,0), m_bMinTrayBtnEnabled(TRUE), m_bMinTrayBtnVisible(TRUE), m_bMinTrayBtnUp(TRUE), m_bMinTrayBtnCapture(FALSE), m_bMinTrayBtnActive(FALSE), m_bMinTrayBtnHitTest(FALSE) { ASSERT(pParentWnd); m_pOwner = pParentWnd; m_hDLL = NULL; MinTrayBtnInit(); } CMinTrayBtn::~CMinTrayBtn() { if (m_hDLL) FreeLibrary(m_hDLL); } void CMinTrayBtn::MinTrayBtnInit() { m_nMinTrayBtnTimerId = 0; MinTrayBtnInitBitmap(); if (!_TransparentBlt) { m_hDLL = LoadLibrary(_T("MSIMG32.DLL")); if (m_hDLL) { (FARPROC &)_TransparentBlt = GetProcAddress(m_hDLL, "TransparentBlt"); if (!_TransparentBlt) { FreeLibrary(m_hDLL); m_hDLL = NULL; } } } } // ------------------------------ // messages // ------------------------------ void CMinTrayBtn::OnNcPaint() { MinTrayBtnUpdatePosAndSize(); MinTrayBtnDraw(); } BOOL CMinTrayBtn::OnNcActivate(BOOL bActive) { MinTrayBtnUpdatePosAndSize(); m_bMinTrayBtnActive = bActive; MinTrayBtnDraw(); return TRUE; } UINT CMinTrayBtn::OnNcHitTest(CPoint point) { BOOL bPreviousHitTest= m_bMinTrayBtnHitTest; m_bMinTrayBtnHitTest= MinTrayBtnHitTest(point); if ((!IsWindowsClassicStyle()) && (m_bMinTrayBtnHitTest != bPreviousHitTest)) MinTrayBtnDraw(); // Windows XP Style (hot button) if (m_bMinTrayBtnHitTest) return HTMINTRAYBUTTON; return HTERROR; } BOOL CMinTrayBtn::OnNcLButtonDown(UINT nHitTest, CPoint point) { if ((m_pOwner->GetStyle() & WS_DISABLED) || (!MinTrayBtnIsEnabled()) || (!MinTrayBtnIsVisible()) || (!MinTrayBtnHitTest(point))) { return FALSE; } m_pOwner->SetCapture(); m_bMinTrayBtnCapture = TRUE; MinTrayBtnSetDown(); return TRUE; } BOOL CMinTrayBtn::OnMouseMove(UINT nFlags, CPoint point) { if ((m_pOwner->GetStyle() & WS_DISABLED) || (!m_bMinTrayBtnCapture)) return FALSE; m_pOwner->ClientToScreen(&point); m_bMinTrayBtnHitTest= MinTrayBtnHitTest(point); if (m_bMinTrayBtnHitTest) { if (m_bMinTrayBtnUp) MinTrayBtnSetDown(); } else { if (!m_bMinTrayBtnUp) MinTrayBtnSetUp(); } return TRUE; } BOOL CMinTrayBtn::OnLButtonUp(UINT nFlags, CPoint point) { if ((m_pOwner->GetStyle() & WS_DISABLED) || (!m_bMinTrayBtnCapture)) return FALSE; ReleaseCapture(); m_bMinTrayBtnCapture = FALSE; MinTrayBtnSetUp(); m_pOwner->ClientToScreen(&point); if (MinTrayBtnHitTest(point)) m_pOwner->SendMessage(WM_SYSCOMMAND, SC_MINIMIZETRAY, MAKELONG(point.x, point.y)); return TRUE; } void CMinTrayBtn::OnThemeChanged() { MinTrayBtnInitBitmap(); } // ------------------------------ // methods // ------------------------------ void CMinTrayBtn::MinTrayBtnUpdatePosAndSize() { DWORD dwStyle = m_pOwner->GetStyle(); DWORD dwExStyle = m_pOwner->GetExStyle(); INT caption= ((dwExStyle & WS_EX_TOOLWINDOW) == 0) ? GetSystemMetrics(SM_CYCAPTION) - 1 : GetSystemMetrics(SM_CYSMCAPTION) - 1; if (caption < CAPTION_MINHEIGHT) caption= CAPTION_MINHEIGHT; CSize borderfixed(-GetSystemMetrics(SM_CXFIXEDFRAME), GetSystemMetrics(SM_CYFIXEDFRAME)); CSize bordersize(-GetSystemMetrics(SM_CXSIZEFRAME), GetSystemMetrics(SM_CYSIZEFRAME)); CRect window; m_pOwner->GetWindowRect(&window); CSize button; button.cy= caption - (CAPTION_BUTTONSPACE * 2); button.cx= button.cy; if (IsWindowsClassicStyle()) button.cx+= 2; m_MinTrayBtnSize = button; m_MinTrayBtnPos.x = window.Width() - ((CAPTION_BUTTONSPACE + button.cx) * 2); m_MinTrayBtnPos.y = CAPTION_BUTTONSPACE; if ((dwStyle & WS_THICKFRAME) != 0) { // resizable window m_MinTrayBtnPos+= bordersize; } else { // fixed window m_MinTrayBtnPos+= borderfixed; } if ( ((dwExStyle & WS_EX_TOOLWINDOW) == 0) && (((dwStyle & WS_MINIMIZEBOX) != 0) || ((dwStyle & WS_MAXIMIZEBOX) != 0)) ) { if (IsWindowsClassicStyle()) m_MinTrayBtnPos.x-= (button.cx * 2) + CAPTION_BUTTONSPACE; else m_MinTrayBtnPos.x-= (button.cx + CAPTION_BUTTONSPACE) * 2; } } void CMinTrayBtn::MinTrayBtnShow() { if (MinTrayBtnIsVisible()) return; m_bMinTrayBtnVisible = TRUE; if (m_pOwner->IsWindowVisible()) { m_pOwner->RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW); } } void CMinTrayBtn::MinTrayBtnHide() { if (!MinTrayBtnIsVisible()) return; m_bMinTrayBtnVisible= FALSE; if (m_pOwner->IsWindowVisible()) { m_pOwner->RedrawWindow(NULL, NULL, RDW_FRAME | RDW_INVALIDATE | RDW_UPDATENOW); } } void CMinTrayBtn::MinTrayBtnEnable() { if (MinTrayBtnIsEnabled()) return; m_bMinTrayBtnEnabled= TRUE; MinTrayBtnSetUp(); } void CMinTrayBtn::MinTrayBtnDisable() { if (!MinTrayBtnIsEnabled()) return; m_bMinTrayBtnEnabled= FALSE; if (m_bMinTrayBtnCapture) { ReleaseCapture(); m_bMinTrayBtnCapture= FALSE; } MinTrayBtnSetUp(); } void CMinTrayBtn::MinTrayBtnDraw() { if (!MinTrayBtnIsVisible()) return; CDC *pDC = m_pOwner->GetWindowDC(); if (!pDC) return; // panic! if (IsWindowsClassicStyle()) { CBrush black(GetSysColor(COLOR_BTNTEXT)); CBrush gray(GetSysColor(COLOR_GRAYTEXT)); CBrush gray2(GetSysColor(COLOR_BTNHILIGHT)); // button if (m_bMinTrayBtnUp) pDC->DrawFrameControl(MinTrayBtnGetRect(), DFC_BUTTON, DFCS_BUTTONPUSH); else pDC->DrawFrameControl(MinTrayBtnGetRect(), DFC_BUTTON, DFCS_BUTTONPUSH | DFCS_PUSHED); // dot CRect btn= MinTrayBtnGetRect(); btn.DeflateRect(2,2); UINT caption= MinTrayBtnGetSize().cy + (CAPTION_BUTTONSPACE * 2); UINT pixratio= (caption >= 14) ? ((caption >= 20) ? 2 + ((caption - 20) / 8) : 2) : 1; UINT pixratio2= (caption >= 12) ? 1 + (caption - 12) / 8: 0; UINT dotwidth= (1 + pixratio * 3) >> 1; UINT dotheight= pixratio; CRect dot(CPoint(0,0), CPoint(dotwidth, dotheight)); CSize spc((1 + pixratio2 * 3) >> 1, pixratio2); dot-= dot.Size(); dot+= btn.BottomRight(); dot-= spc; if (!m_bMinTrayBtnUp) dot+= CPoint(1,1); if (m_bMinTrayBtnEnabled) { pDC->FillRect(dot, &black); } else { pDC->FillRect(dot + CPoint(1,1), &gray2); pDC->FillRect(dot, &gray); } } else { // VisualStylesXP CRect btn = MinTrayBtnGetRect(); int iState; if (!m_bMinTrayBtnEnabled) iState= TRAYBS_DISABLED; else if (m_pOwner->GetStyle() & WS_DISABLED) iState= MINBS_NORMAL; else if (m_bMinTrayBtnHitTest) iState= (m_bMinTrayBtnCapture) ? MINBS_PUSHED : MINBS_HOT; else iState= MINBS_NORMAL; // inactive if (!m_bMinTrayBtnActive) iState+= 4; // inactive state TRAYBS_Ixxx if ((m_bmMinTrayBtnBitmap.m_hObject) && (_TransparentBlt)) { // known theme (bitmap) CBitmap *pBmpOld; CDC dcMem; if ((dcMem.CreateCompatibleDC(pDC)) && ((pBmpOld= dcMem.SelectObject(&m_bmMinTrayBtnBitmap)) != NULL)) { _TransparentBlt(pDC->m_hDC, btn.left, btn.top, btn.Width(), btn.Height(), dcMem.m_hDC, 0, BMP_TRAYBTN_HEIGHT * (iState - 1), BMP_TRAYBTN_WIDTH, BMP_TRAYBTN_HEIGHT, BMP_TRAYBTN_TRANSCOLOR); dcMem.SelectObject(pBmpOld); } } else { // unknown theme (ThemeData) HTHEME hTheme= g_xpStyle.OpenThemeData(m_pOwner->GetSafeHwnd(), L"Window"); if (hTheme) { btn.top+= btn.Height() / 8; g_xpStyle.DrawThemeBackground(hTheme, pDC->m_hDC, WP_TRAYBUTTON, iState, &btn, NULL); g_xpStyle.CloseThemeData(hTheme); } } } m_pOwner->ReleaseDC(pDC); } BOOL CMinTrayBtn::MinTrayBtnHitTest(CPoint point) const { CRect rWnd; m_pOwner->GetWindowRect(&rWnd); point.Offset(-rWnd.TopLeft()); CRect rBtn= MinTrayBtnGetRect(); rBtn.InflateRect(0, CAPTION_BUTTONSPACE); return (rBtn.PtInRect(point)); } void CMinTrayBtn::MinTrayBtnSetUp() { m_bMinTrayBtnUp= TRUE; MinTrayBtnDraw(); } void CMinTrayBtn::MinTrayBtnSetDown() { m_bMinTrayBtnUp = FALSE; MinTrayBtnDraw(); } BOOL CMinTrayBtn::IsWindowsClassicStyle() const { return (!((g_xpStyle.IsThemeActive()) && (g_xpStyle.IsAppThemed()))); } INT CMinTrayBtn::GetVisualStylesXPColor() const { if (IsWindowsClassicStyle()) return -1; WCHAR szwThemeFile[MAX_PATH]; WCHAR szwThemeColor[256]; if (g_xpStyle.GetCurrentThemeName(szwThemeFile, MAX_PATH, szwThemeColor, 256, NULL, 0) != S_OK) return -1; WCHAR *p; if ((p= wcsrchr(szwThemeFile, '\\')) == NULL) return -1; p++; if (_wcsicmp(p, VISUALSTYLESXP_DEFAULTFILE) != 0) return -1; if (_wcsicmp(szwThemeColor, VISUALSTYLESXP_NAMEBLUE) == 0) return VISUALSTYLESXP_BLUE; if (_wcsicmp(szwThemeColor, VISUALSTYLESXP_NAMEMETALLIC) == 0) return VISUALSTYLESXP_METALLIC; if (_wcsicmp(szwThemeColor, VISUALSTYLESXP_NAMEHOMESTEAD) == 0) return VISUALSTYLESXP_HOMESTEAD; return -1; } BOOL CMinTrayBtn::MinTrayBtnInitBitmap() { INT nColor; m_bmMinTrayBtnBitmap.DeleteObject(); if ((nColor= GetVisualStylesXPColor()) == -1) return FALSE; const TCHAR *pszBmpName= m_pszMinTrayBtnBmpName[nColor]; BOOL res = m_bmMinTrayBtnBitmap.Attach(::LoadBitmap(AfxGetInstanceHandle(), pszBmpName)); return res; } #define WM_THEMECHANGED 0x031A BOOL CMinTrayBtn::ProcessWindowMessage(HWND hWnd, UINT nMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult) { switch (nMsg) { case WM_NCPAINT: lResult = DefWindowProc(nMsg, wParam, lParam); OnNcPaint(); return TRUE; case WM_SETTEXT: lResult = DefWindowProc(nMsg, wParam, lParam); MinTrayBtnDraw(); return TRUE; case WM_NCACTIVATE: lResult = DefWindowProc(nMsg, wParam, lParam); OnNcActivate(wParam); return TRUE; case WM_NCHITTEST: { lResult = (INT)OnNcHitTest(CPoint(lParam)); if (lResult == HTERROR) lResult = DefWindowProc(nMsg, wParam, lParam); } return TRUE; case WM_NCLBUTTONDOWN: if (!OnNcLButtonDown(wParam, CPoint(lParam))) lResult = DefWindowProc(nMsg, wParam, lParam); else lResult = 0; return TRUE; case WM_THEMECHANGED: OnThemeChanged(); break; case WM_MOUSEMOVE: OnMouseMove(wParam, CPoint(lParam)); break; case WM_LBUTTONUP: if (OnLButtonUp(wParam, CPoint(lParam))) lResult = 0; else lResult = DefWindowProc(nMsg, wParam, lParam); return TRUE; } return FALSE; }
ChadSki/FeatherweightVirtualMachine
FVM_UI/fvmshell/misc/MinTrayBtn.cpp
C++
gpl-2.0
13,862
package com.pcab.marvel.model; /** * Summary type used for creators. */ public class RoleSummary extends Summary { /** * The role in the parent entity. */ private String role; public String getRole() { return role; } public void setRole(String role) { this.role = role; } }
pablocabrera85/marvel-api-client
src/main/java/com/pcab/marvel/model/RoleSummary.java
Java
gpl-2.0
330
/* ***** BEGIN LICENSE BLOCK ***** * Source last modified: $Id: test_velocity_caps.cpp,v 1.2 2005/03/14 19:36:42 bobclark Exp $ * * Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved. * * The contents of this file, and the files included with this file, * are subject to the current version of the RealNetworks Public * Source License (the "RPSL") available at * http://www.helixcommunity.org/content/rpsl unless you have licensed * the file under the current version of the RealNetworks Community * Source License (the "RCSL") available at * http://www.helixcommunity.org/content/rcsl, in which case the RCSL * will apply. You may also obtain the license terms directly from * RealNetworks. You may not use this file except in compliance with * the RPSL or, if you have a valid RCSL with RealNetworks applicable * to this file, the RCSL. Please see the applicable RPSL or RCSL for * the rights, obligations and limitations governing use of the * contents of the file. * * Alternatively, the contents of this file may be used under the * terms of the GNU General Public License Version 2 or later (the * "GPL") in which case the provisions of the GPL are applicable * instead of those above. If you wish to allow use of your version of * this file only under the terms of the GPL, and not to allow others * to use your version of this file under the terms of either the RPSL * or RCSL, indicate your decision by deleting the provisions above * and replace them with the notice and other provisions required by * the GPL. If you do not delete the provisions above, a recipient may * use your version of this file under the terms of any one of the * RPSL, the RCSL or the GPL. * * This file is part of the Helix DNA Technology. RealNetworks is the * developer of the Original Code and owns the copyrights in the * portions it created. * * This file, and the files included with this file, is distributed * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET * ENJOYMENT OR NON-INFRINGEMENT. * * Technology Compatibility Kit Test Suite(s) Location: * http://www.helixcommunity.org/content/tck * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ #include "hxtypes.h" #include "hxcom.h" #include "hxplayvelocity.h" #include "test_velocity_caps.h" CHXPlaybackVelocityCapsTest::CHXPlaybackVelocityCapsTest() { m_ppCaps[0] = new CHXPlaybackVelocityCaps(); m_ppCaps[1] = new CHXPlaybackVelocityCaps(); } CHXPlaybackVelocityCapsTest::~CHXPlaybackVelocityCapsTest() { HX_DELETE(m_ppCaps[0]); HX_DELETE(m_ppCaps[1]); } void CHXPlaybackVelocityCapsTest::GetCommandInfo(UTVector<HLXUnitTestCmdInfo*>& cmds) { cmds.Resize(6); cmds[0] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "CHXPlaybackVelocityCaps()", &CHXPlaybackVelocityCapsTest::HandleConstructorCmd, 2); cmds[1] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "GetNumRanges", &CHXPlaybackVelocityCapsTest::HandleGetNumRangesCmd, 3); cmds[2] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "GetRange", &CHXPlaybackVelocityCapsTest::HandleGetRangeCmd, 5); cmds[3] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "AddRange", &CHXPlaybackVelocityCapsTest::HandleAddRangeCmd, 5); cmds[4] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "CombineCapsLogicalAnd", &CHXPlaybackVelocityCapsTest::HandleCombineCapsLogicalAndCmd, 2); cmds[5] = new HLXUnitTestCmdInfoDisp<CHXPlaybackVelocityCapsTest>(this, "IsCapable", &CHXPlaybackVelocityCapsTest::HandleIsCapableCmd, 4); } const char* CHXPlaybackVelocityCapsTest::DefaultCommandLine() const { return "test_velocity_caps test_velocity_caps.in -a"; } HLXCmdBasedTest* CHXPlaybackVelocityCapsTest::Clone() const { return new CHXPlaybackVelocityCapsTest(); } bool CHXPlaybackVelocityCapsTest::HandleConstructorCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2) { HX_DELETE(m_ppCaps[ulIndex]); m_ppCaps[ulIndex] = new CHXPlaybackVelocityCaps(); if (m_ppCaps[ulIndex]) { bRet = true; } } return bRet; } bool CHXPlaybackVelocityCapsTest::HandleGetNumRangesCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2 && m_ppCaps[ulIndex]) { UINT32 ulExpectedNum = strtoul(params[2], NULL, 10); UINT32 ulActualNum = m_ppCaps[ulIndex]->GetNumRanges(); if (ulExpectedNum == ulActualNum) { bRet = true; } } return bRet; } bool CHXPlaybackVelocityCapsTest::HandleGetRangeCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2 && m_ppCaps[ulIndex]) { UINT32 ulRangeIndex = strtoul(params[2], NULL, 10); INT32 lExpectedMin = (INT32) strtol(params[3], NULL, 10); INT32 lExpectedMax = (INT32) strtol(params[4], NULL, 10); INT32 lActualMin = 0; INT32 lActualMax = 0; HX_RESULT retVal = m_ppCaps[ulIndex]->GetRange(ulRangeIndex, lActualMin, lActualMax); if (SUCCEEDED(retVal) && lExpectedMin == lActualMin && lExpectedMax == lActualMax) { bRet = true; } } return bRet; } bool CHXPlaybackVelocityCapsTest::HandleAddRangeCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2 && m_ppCaps[ulIndex]) { INT32 lMinToAdd = strtol(params[2], NULL, 10); INT32 lMaxToAdd = strtol(params[3], NULL, 10); UINT32 ulExpRet = strtoul(params[4], NULL, 10); HX_RESULT retVal = m_ppCaps[ulIndex]->AddRange(lMinToAdd, lMaxToAdd); if ((ulExpRet && SUCCEEDED(retVal)) || (!ulExpRet && FAILED(retVal))) { bRet = true; } } return bRet; } bool CHXPlaybackVelocityCapsTest::HandleCombineCapsLogicalAndCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2 && m_ppCaps[0] && m_ppCaps[1]) { UINT32 ulOtherIndex = (ulIndex == 0 ? 1 : 0); HX_RESULT retVal = m_ppCaps[ulIndex]->CombineCapsLogicalAnd(m_ppCaps[ulOtherIndex]); if (SUCCEEDED(retVal)) { bRet = true; } } return bRet; } bool CHXPlaybackVelocityCapsTest::HandleIsCapableCmd(const UTVector<UTString>& params) { bool bRet = false; UINT32 ulIndex = strtoul(params[1], NULL, 10); if (ulIndex < 2 && m_ppCaps[ulIndex]) { INT32 lVelToCheck = strtol(params[2], NULL, 10); UINT32 ulExpRet = strtoul(params[3], NULL, 10); HXBOOL bExpRet = (ulExpRet ? TRUE : FALSE); HXBOOL bActRet = m_ppCaps[ulIndex]->IsCapable(lVelToCheck); if (bActRet == bExpRet) { bRet = true; } } return bRet; }
muromec/qtopia-ezx
src/3rdparty/libraries/helix/src/common/util/test/test_velocity_caps.cpp
C++
gpl-2.0
8,664
/*************************************************************************** kgpanel.cpp - description ------------------- copyright : (C) 2003 by Csaba Karai copyright : (C) 2010 by Jan Lepper e-mail : krusader@users.sourceforge.net web site : http://krusader.sourceforge.net --------------------------------------------------------------------------- Description *************************************************************************** A db dD d8888b. db db .d8888. .d8b. d8888b. d88888b d8888b. 88 ,8P' 88 `8D 88 88 88' YP d8' `8b 88 `8D 88' 88 `8D 88,8P 88oobY' 88 88 `8bo. 88ooo88 88 88 88ooooo 88oobY' 88`8b 88`8b 88 88 `Y8b. 88~~~88 88 88 88~~~~~ 88`8b 88 `88. 88 `88. 88b d88 db 8D 88 88 88 .8D 88. 88 `88. YP YD 88 YD ~Y8888P' `8888Y' YP YP Y8888D' Y88888P 88 YD S o u r c e F i l e *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "kgpanel.h" #include "../defaults.h" #include "../Dialogs/krdialogs.h" #include <QtGui/QTabWidget> #include <QFrame> #include <QGridLayout> #include <QLabel> #include <QVBoxLayout> #include <klocale.h> #include <QtGui/QValidator> #include <kmessagebox.h> #include <kfiledialog.h> #include <kglobal.h> #include <kstandarddirs.h> #include "viewtype.h" #include "viewfactory.h" #include "module.h" #include "viewconfigui.h" #include "../krusaderapp.h" #include "../Panel/krlayoutfactory.h" enum { PAGE_MISC = 0, PAGE_VIEW, PAGE_PANELTOOLBAR, PAGE_MOUSE, PAGE_MEDIA_MENU, PAGE_LAYOUT }; KgPanel::KgPanel(bool first, QWidget* parent) : KonfiguratorPage(first, parent) { tabWidget = new QTabWidget(this); setWidget(tabWidget); setWidgetResizable(true); setupMiscTab(); setupPanelTab(); setupButtonsTab(); setupMouseModeTab(); setupMediaMenuTab(); setupLayoutTab(); } ViewConfigUI *KgPanel::viewConfigUI() { ViewConfigUI *viewCfg = qobject_cast<ViewConfigUI*>(KrusaderApp::self()->module("View")); Q_ASSERT(viewCfg); return viewCfg; } // --------------------------------------------------------------------------------------- // ---------------------------- Misc TAB ------------------------------------------------ // --------------------------------------------------------------------------------------- void KgPanel::setupMiscTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); QWidget *tab = new QWidget(scrollArea); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidget(tab); scrollArea->setWidgetResizable(true); tabWidget->addTab(scrollArea, i18n("General")); QVBoxLayout *miscLayout = new QVBoxLayout(tab); miscLayout->setSpacing(6); miscLayout->setContentsMargins(11, 11, 11, 11); // --------------------------------------------------------------------------------------- // ------------------------------- Address Bar ------------------------------------------- // --------------------------------------------------------------------------------------- QGroupBox *miscGrp = createFrame(i18n("Address bar"), tab); QGridLayout *miscGrid = createGridLayout(miscGrp); KONFIGURATOR_CHECKBOX_PARAM general_settings[] = { // cfg_class, cfg_name, default, text, restart, tooltip {"Look&Feel", "FlatOriginBar", _FlatOriginBar, i18n("Flat address bar"), true, 0 }, {"Look&Feel", "ShortenHomePath", _ShortenHomePath, i18n("Shorten home path"), true, i18n("Display home path as \"~\"") }, }; KonfiguratorCheckBoxGroup *cbs = createCheckBoxGroup(2, 0, general_settings, 2 /*count*/, miscGrp, PAGE_MISC); cbs->find("FlatOriginBar")->addDep(cbs->find("ShortenHomePath")); miscGrid->addWidget(cbs, 0, 0); miscLayout->addWidget(miscGrp); // --------------------------------------------------------------------------------------- // ------------------------------- Operation --------------------------------------------- // --------------------------------------------------------------------------------------- miscGrp = createFrame(i18n("Operation"), tab); miscGrid = createGridLayout(miscGrp); KONFIGURATOR_CHECKBOX_PARAM operation_settings[] = { // cfg_class, cfg_name, default, text, restart, tooltip {"Look&Feel", "Mark Dirs", _MarkDirs, i18n("Autoselect directories"), false, i18n("When matching the select criteria, not only files will be selected, but also directories.") }, {"Look&Feel", "Rename Selects Extension", true, i18n("Rename selects extension"), false, i18n("When renaming a file, the whole text is selected. If you want Total-Commander like renaming of just the name, without extension, uncheck this option.") }, {"Look&Feel", "UnselectBeforeOperation", _UnselectBeforeOperation, i18n("Unselect files before copy/move"), false, i18n("Unselect files, which are to be copied/moved, before the operation starts.") }, {"Look&Feel", "FilterDialogRemembersSettings", _FilterDialogRemembersSettings, i18n("Filter dialog remembers settings"), false, i18n("The filter dialog is opened with the last filter settings that where applied to the panel.") }, }; cbs = createCheckBoxGroup(2, 0, operation_settings, 4 /*count*/, miscGrp, PAGE_MISC); miscGrid->addWidget(cbs, 0, 0); miscLayout->addWidget(miscGrp); // --------------------------------------------------------------------------------------- // ------------------------------ Tabs --------------------------------------------------- // --------------------------------------------------------------------------------------- miscGrp = createFrame(i18n("Tabs"), tab); miscGrid = createGridLayout(miscGrp); KONFIGURATOR_CHECKBOX_PARAM tabbar_settings[] = { // cfg_class cfg_name default text restart tooltip {"Look&Feel", "Fullpath Tab Names", _FullPathTabNames, i18n("Use full path tab names"), true , i18n("Display the full path in the folder tabs. By default only the last part of the path is displayed.") }, {"Look&Feel", "Show Tab Buttons", true, i18n("Show new/close tab buttons"), true , i18n("Show the new/close tab buttons") }, }; cbs = createCheckBoxGroup(2, 0, tabbar_settings, 2 /*count*/, miscGrp, PAGE_MISC); miscGrid->addWidget(cbs, 0, 0); // ----------------- Tab Bar position ---------------------------------- QHBoxLayout *hbox = new QHBoxLayout(); hbox->addWidget(new QLabel(i18n("Tab Bar position:"), miscGrp)); KONFIGURATOR_NAME_VALUE_PAIR positions[] = {{ i18n("Top"), "top" }, { i18n("Bottom"), "bottom" } }; KonfiguratorComboBox *cmb = createComboBox("Look&Feel", "Tab Bar Position", "bottom", positions, 2, miscGrp, true, false, PAGE_MISC); hbox->addWidget(cmb); hbox->addWidget(createSpacer(miscGrp)); miscGrid->addLayout(hbox, 1, 0); miscLayout->addWidget(miscGrp); // --------------------------------------------------------------------------------------- // ----------------------------- Quicksearch ------------------------------------------- // --------------------------------------------------------------------------------------- miscGrp = createFrame(i18n("Quicksearch/Quickfilter"), tab); miscGrid = createGridLayout(miscGrp); KONFIGURATOR_CHECKBOX_PARAM quicksearch[] = { // cfg_class cfg_name default text restart tooltip {"Look&Feel", "New Style Quicksearch", _NewStyleQuicksearch, i18n("New style Quicksearch"), false, i18n("Opens a quick search dialog box.") }, {"Look&Feel", "Case Sensitive Quicksearch", _CaseSensitiveQuicksearch, i18n("Case sensitive Quicksearch/QuickFilter"), false, i18n("All files beginning with capital letters appear before files beginning with non-capital letters (UNIX default).") }, {"Look&Feel", "Up/Down Cancels Quicksearch", false, i18n("Up/Down cancels Quicksearch"), false, i18n("Pressing the Up/Down buttons cancels Quicksearch.") }, }; quicksearchCheckboxes = createCheckBoxGroup(2, 0, quicksearch, 3 /*count*/, miscGrp, PAGE_MISC); miscGrid->addWidget(quicksearchCheckboxes, 0, 0); connect(quicksearchCheckboxes->find("New Style Quicksearch"), SIGNAL(stateChanged(int)), this, SLOT(slotDisable())); slotDisable(); // -------------- Quicksearch position ----------------------- hbox = new QHBoxLayout(); hbox->addWidget(new QLabel(i18n("Position:"), miscGrp)); cmb = createComboBox("Look&Feel", "Quicksearch Position", "bottom", positions, 2, miscGrp, true, false, PAGE_MISC); hbox->addWidget(cmb); hbox->addWidget(createSpacer(miscGrp)); miscGrid->addLayout(hbox, 1, 0); miscLayout->addWidget(miscGrp); // -------------------------------------------------------------------------------------------- // ------------------------------- Status/Totalsbar settings ---------------------------------- // -------------------------------------------------------------------------------------------- miscGrp = createFrame(i18n("Status/Totalsbar"), tab); miscGrid = createGridLayout(miscGrp); KONFIGURATOR_CHECKBOX_PARAM barSettings[] = { {"Look&Feel", "Show Size In Bytes", true, i18n("Show size in bytes too"), true, i18n("Show size in bytes too") }, {"Look&Feel", "ShowSpaceInformation", true, i18n("Show space information"), true, i18n("Show free/total space on the device") }, }; KonfiguratorCheckBoxGroup *barSett = createCheckBoxGroup(2, 0, barSettings, 2 /*count*/, miscGrp, PAGE_MISC); miscGrid->addWidget(barSett, 1, 0, 1, 2); miscLayout->addWidget(miscGrp); } // -------------------------------------------------------------------------------------------- // ------------------------------------ Layout Tab -------------------------------------------- // -------------------------------------------------------------------------------------------- void KgPanel::setupLayoutTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); QWidget *tab = new QWidget(scrollArea); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidget(tab); scrollArea->setWidgetResizable(true); tabWidget->addTab(scrollArea, i18n("Layout")); QGridLayout *grid = createGridLayout(tab); QStringList layoutNames = KrLayoutFactory::layoutNames(); int numLayouts = layoutNames.count(); grid->addWidget(createSpacer(tab), 0, 2); QLabel *l = new QLabel(i18n("Layout:"), tab); l->setAlignment(Qt::AlignRight | Qt::AlignVCenter); grid->addWidget(l, 0, 0); KONFIGURATOR_NAME_VALUE_PAIR *layouts = new KONFIGURATOR_NAME_VALUE_PAIR[numLayouts]; for (int i = 0; i != numLayouts; i++) { layouts[ i ].text = KrLayoutFactory::layoutDescription(layoutNames[i]); layouts[ i ].value = layoutNames[i]; } KonfiguratorComboBox *cmb = createComboBox("PanelLayout", "Layout", "default", layouts, numLayouts, tab, true, false, PAGE_LAYOUT); grid->addWidget(cmb, 0, 1); delete [] layouts; l = new QLabel(i18n("Frame Color:"), tab); l->setAlignment(Qt::AlignRight | Qt::AlignVCenter); grid->addWidget(l, 1, 0); KONFIGURATOR_NAME_VALUE_PAIR frameColor[] = { { i18nc("Frame color", "Defined by Layout"), "default" }, { i18nc("Frame color", "None"), "none" }, { i18nc("Frame color", "Statusbar"), "Statusbar" } }; cmb = createComboBox("PanelLayout", "FrameColor", "default", frameColor, 3, tab, true, false, PAGE_LAYOUT); grid->addWidget(cmb, 1, 1); l = new QLabel(i18n("Frame Shape:"), tab); l->setAlignment(Qt::AlignRight | Qt::AlignVCenter); grid->addWidget(l, 2, 0); KONFIGURATOR_NAME_VALUE_PAIR frameShape[] = { { i18nc("Frame shape", "Defined by Layout"), "default" }, { i18nc("Frame shape", "None"), "NoFrame" }, { i18nc("Frame shape", "Box"), "Box" }, { i18nc("Frame shape", "Panel"), "Panel" }, }; cmb = createComboBox("PanelLayout", "FrameShape", "default", frameShape, 4, tab, true, false, PAGE_LAYOUT); grid->addWidget(cmb, 2, 1); l = new QLabel(i18n("Frame Shadow:"), tab); l->setAlignment(Qt::AlignRight | Qt::AlignVCenter); grid->addWidget(l, 3, 0); KONFIGURATOR_NAME_VALUE_PAIR frameShadow[] = { { i18nc("Frame shadow", "Defined by Layout"), "default" }, { i18nc("Frame shadow", "None"), "Plain" }, { i18nc("Frame shadow", "Raised"), "Raised" }, { i18nc("Frame shadow", "Sunken"), "Sunken" }, }; cmb = createComboBox("PanelLayout", "FrameShadow", "default", frameShadow, 4, tab, true, false, PAGE_LAYOUT); grid->addWidget(cmb, 3, 1); } // ---------------------------------------------------------------------------------- // ---------------------------- VIEW TAB ------------------------------------------- // ---------------------------------------------------------------------------------- void KgPanel::setupPanelTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidgetResizable(true); QWidget *tab_panel = viewConfigUI()->createViewCfgTab(scrollArea, this, PAGE_VIEW); scrollArea->setWidget(tab_panel); tabWidget->addTab(scrollArea, i18n("View")); } // ----------------------------------------------------------------------------------- // -------------------------- Panel Toolbar TAB ---------------------------------- // ----------------------------------------------------------------------------------- void KgPanel::setupButtonsTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); QWidget *tab = new QWidget(scrollArea); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidget(tab); scrollArea->setWidgetResizable(true); tabWidget->addTab(scrollArea, i18n("Buttons")); QBoxLayout * tabLayout = new QVBoxLayout(tab); tabLayout->setSpacing(6); tabLayout->setContentsMargins(11, 11, 11, 11); KONFIGURATOR_CHECKBOX_PARAM buttonsParams[] = // cfg_class cfg_name default text restart tooltip { {"ListPanelButtons", "Icons", false, i18n("Toolbar buttons have icons"), true, "" }, {"Look&Feel", "Media Button Visible", true, i18n("Show Media Button"), true , i18n("The media button will be visible.") }, {"Look&Feel", "Back Button Visible", false, i18n("Show Back Button"), true , "Goes back in history." }, {"Look&Feel", "Forward Button Visible", false, i18n("Show Forward Button"), true , "Goes forward in history." }, {"Look&Feel", "History Button Visible", true, i18n("Show History Button"), true , i18n("The history button will be visible.") }, {"Look&Feel", "Bookmarks Button Visible", true, i18n("Show Bookmarks Button"), true , i18n("The bookmarks button will be visible.") }, {"Look&Feel", "Panel Toolbar visible", _PanelToolBar, i18n("Show Panel Toolbar"), true, i18n("The panel toolbar will be visible.") }, }; buttonsCheckboxes = createCheckBoxGroup(1, 0, buttonsParams, 7/*count*/, tab, PAGE_PANELTOOLBAR); connect(buttonsCheckboxes->find("Panel Toolbar visible"), SIGNAL(stateChanged(int)), this, SLOT(slotEnablePanelToolbar())); tabLayout->addWidget(buttonsCheckboxes, 0, 0); QGroupBox * panelToolbarGrp = createFrame(i18n("Visible Panel Toolbar buttons"), tab); QGridLayout * panelToolbarGrid = createGridLayout(panelToolbarGrp); KONFIGURATOR_CHECKBOX_PARAM panelToolbarButtonsParams[] = { // cfg_class cfg_name default text restart tooltip {"Look&Feel", "Open Button Visible", _Open, i18n("Open button"), true , i18n("Opens the directory browser.") }, {"Look&Feel", "Equal Button Visible", _cdOther, i18n("Equal button (=)"), true , i18n("Changes the panel directory to the other panel directory.") }, {"Look&Feel", "Up Button Visible", _cdUp, i18n("Up button (..)"), true , i18n("Changes the panel directory to the parent directory.") }, {"Look&Feel", "Home Button Visible", _cdHome, i18n("Home button (~)"), true , i18n("Changes the panel directory to the home directory.") }, {"Look&Feel", "Root Button Visible", _cdRoot, i18n("Root button (/)"), true , i18n("Changes the panel directory to the root directory.") }, {"Look&Feel", "SyncBrowse Button Visible", _syncBrowseButton, i18n("Toggle-button for sync-browsing"), true , i18n("Each directory change in the panel is also performed in the other panel.") }, }; panelToolbarButtonsCheckboxes = createCheckBoxGroup(1, 0, panelToolbarButtonsParams, sizeof(panelToolbarButtonsParams) / sizeof(*panelToolbarButtonsParams), panelToolbarGrp, PAGE_PANELTOOLBAR); panelToolbarGrid->addWidget(panelToolbarButtonsCheckboxes, 0, 0); tabLayout->addWidget(panelToolbarGrp, 1, 0); // Enable panel toolbar checkboxes slotEnablePanelToolbar(); } // --------------------------------------------------------------------------- // -------------------------- Mouse TAB ---------------------------------- // --------------------------------------------------------------------------- void KgPanel::setupMouseModeTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidgetResizable(true); QWidget *tab_mouse = viewConfigUI()->createSelectionModeCfgTab(scrollArea, this, PAGE_MOUSE); scrollArea->setWidget(tab_mouse); tabWidget->addTab(scrollArea, i18n("Selection Mode")); } // --------------------------------------------------------------------------- // -------------------------- Media Menu TAB ---------------------------------- // --------------------------------------------------------------------------- void KgPanel::setupMediaMenuTab() { QScrollArea *scrollArea = new QScrollArea(tabWidget); QWidget *tab = new QWidget(scrollArea); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidget(tab); scrollArea->setWidgetResizable(true); tabWidget->addTab(scrollArea, i18n("Media Menu")); QBoxLayout * tabLayout = new QVBoxLayout(tab); tabLayout->setSpacing(6); tabLayout->setContentsMargins(11, 11, 11, 11); KONFIGURATOR_CHECKBOX_PARAM mediaMenuParams[] = { // cfg_class cfg_name default text restart tooltip {"MediaMenu", "ShowPath", true, i18n("Show Mount Path"), false, 0 }, {"MediaMenu", "ShowFSType", true, i18n("Show File System Type"), false, 0 }, }; KonfiguratorCheckBoxGroup *mediaMenuCheckBoxes = createCheckBoxGroup(1, 0, mediaMenuParams, sizeof(mediaMenuParams) / sizeof(*mediaMenuParams), tab, PAGE_MEDIA_MENU); tabLayout->addWidget(mediaMenuCheckBoxes, 0, 0); QHBoxLayout *showSizeHBox = new QHBoxLayout(); showSizeHBox->addWidget(new QLabel(i18n("Show Size:"), tab)); KONFIGURATOR_NAME_VALUE_PAIR showSizeValues[] = { { i18nc("setting 'show size'", "Always"), "Always" }, { i18nc("setting 'show size'", "When Device has no Label"), "WhenNoLabel" }, { i18nc("setting 'show size'", "Never"), "Never" }, }; KonfiguratorComboBox *showSizeCmb = createComboBox("MediaMenu", "ShowSize", "Always", showSizeValues, sizeof(showSizeValues) / sizeof(*showSizeValues), tab, false, false, PAGE_MEDIA_MENU); showSizeHBox->addWidget(showSizeCmb); showSizeHBox->addStretch(); tabLayout->addLayout(showSizeHBox); tabLayout->addStretch(); } void KgPanel::slotDisable() { bool isNewStyleQuickSearch = quicksearchCheckboxes->find("New Style Quicksearch")->isChecked(); quicksearchCheckboxes->find("Case Sensitive Quicksearch")->setEnabled(isNewStyleQuickSearch); } void KgPanel::slotEnablePanelToolbar() { bool enableTB = buttonsCheckboxes->find("Panel Toolbar visible")->isChecked(); panelToolbarButtonsCheckboxes->find("Root Button Visible")->setEnabled(enableTB); panelToolbarButtonsCheckboxes->find("Home Button Visible")->setEnabled(enableTB); panelToolbarButtonsCheckboxes->find("Up Button Visible")->setEnabled(enableTB); panelToolbarButtonsCheckboxes->find("Equal Button Visible")->setEnabled(enableTB); panelToolbarButtonsCheckboxes->find("Open Button Visible")->setEnabled(enableTB); panelToolbarButtonsCheckboxes->find("SyncBrowse Button Visible")->setEnabled(enableTB); } int KgPanel::activeSubPage() { return tabWidget->currentIndex(); }
amatveyakin/skuire
krusader/Konfigurator/kgpanel.cpp
C++
gpl-2.0
21,856
var v = "题库题数:1546(2015.05.09更新)"; alert("脚本加载完成。\n如果您为使用此脚本支付了任何费用,那么恭喜您,您被坑了。\n\n按确定开始执行。"); var allQ = []; $(".examLi").each(function(){ allQ.push($(this).text()); }); var counter = 0; for(var i = 1; i <= 20; i++){ var thisQ = allQ[i].split(" "); var q = thisQ[64].substring(0, thisQ[64].length - 1); //问题 //答案 var a = []; for(var ii = 112; ii <= 172; ii += 20){ a.push(thisQ[ii].substring(1, thisQ[ii].length - 1)); } var rightA = getAns(q); //获取正确答案 if(a.indexOf(rightA) > -1){ $(".examLi").eq(i) //找到正确的题 .find("li").eq(a.indexOf(rightA)) //找到正确的选项 .addClass("currSolution"); //选择选项 }else{ counter += 1; if(rightA !== undefined){ //题库错误处理 alert("题库错误!\n问题:\"" + q + "\"\n返回的答案:\"" + rightA + "\"\n捕获的答案列表:" + a); } } } alert("答题完成,有" + counter +"道题没填写(题库中没有或返回的答案无效)。") //题库函数 function getAns (q){ // 79 = 79 switch(q){ case "以下哪一位数学家不是法国人?": return ".黎曼"; case "当PCl5 = PCl3 +Cl2的化学平衡常数Kc=1.8M时,在0.5L的容器中加入0.15molPCl5,求平衡后Cl2的浓度": return ".0.26M"; case "以下哪种颜色不属于色光三原色?": return ".黄"; case "iphone 4之后苹果推出的手机是": return ".iphone 4S"; case "c++的int类型通常占用几个字节?": return "4(byte)"; case "冥王星的公转周期?": return ".248地球年"; case "世界上用图像显示的第一个电子游戏是什么?": return ".Core War"; case "AIDS的全称是什么?": return ".获得性免疫缺陷综合征"; case "计算机编程中常见的if语句是?": return ".判断语句"; case "风靡一时的游戏主机“红白机”全名为?": return ".Family Computer"; case "当天空出现了鱼鳞云(透光高积云),下列哪种天气现象会发生?": return ".降雨"; case "一直被拿去做实验从未被超越的动物是": return ".小白鼠"; case "以下作品中哪一个完全没有使用3D技术": return ".LOVELIVE TV版"; case "以下哪款耳机采用了特斯拉技术": return ".拜亚T1"; case "美国历史上第一位黑人总统是": return ".Barack Hussein Obama II"; case "以下哪种功率放大器效率最低?": return ".甲类"; case "RGBA中的A是指?": return ".Alpha"; case "“不学礼,无以立”。出于何处?": return ".《论语》"; case "静电场的高斯定理和环路定理说明静电场是个什么场?": return ".有源有旋场"; case "新生物性状产生的根本原因在于?": return ".基因重组"; case "一个农田的全部生物属于?": return ".群落"; case "北回归线没有从下列哪个省中穿过?": return ".福建"; case "什么是“DTS”": return ".数字家庭影院系统"; case "被誉为生命科学“登月”计划的是": return ".人类基因组计划"; case "下列有关电子显微镜的说法正确的是": return ".常用的有透射电镜和扫描电子镜"; case "天文学上,红移是指": return ".天体离我们远去"; case "传说中从天而降砸到牛顿的是": return ".苹果"; case "拿破仑在从厄尔巴岛逃回法国,到兵败滑铁卢再次流放,一共重返帝位多少天?": return ".101"; case "剧毒NaCN(氰化钠)的水解产物HCN是什么味道": return ".苦杏仁味"; case "金鱼的卵什么颜色的才能孵化": return ".淡青色"; default: return undefined; }} //结束switch和题库函数 } //结束运行确认
mobaobaoss/mobaobaoss.github.io
timu1.js
JavaScript
gpl-2.0
3,742
package net.kolls.railworld.play; /* * Copyright (C) 2010 Steve Kollmansberger * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; import java.util.Vector; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.WindowConstants; import net.kolls.railworld.Car; import net.kolls.railworld.Factories; import net.kolls.railworld.Images; import net.kolls.railworld.RailSegment; import net.kolls.railworld.Train; import net.kolls.railworld.car.Caboose; import net.kolls.railworld.car.Engine; import net.kolls.railworld.play.script.ScriptManager; import net.kolls.railworld.segment.EESegment; import net.kolls.railworld.segment.LUSegment; import net.kolls.railworld.tuic.TrainPainter; /** * Provides a window allowing the user to create a train to enter the map. * * @author Steve Kollmansberger * */ public class TrainCreator extends JFrame { private JPanel loaded, unloaded, nonload; private MultiLineTrainPanel ctrain; private Vector<EESegment> ees; private PlayFrame pf; private JComboBox enters, speeds; private final int incr = Train.MAX_SPEED_MPH / Train.MAX_THROTTLE; private Map<String,Car> sc; /** * Generate a series of engines, cargo cars, and possibly a caboose * based on possible cargo cars. * * @param r Random number source * @param engine The template car for the engine, e.g. to allow derived engine types * @param sources Array of allowable cargo cars * @return Train cars */ public static Car[] generate(Random r, Car engine, Car[] sources) { int leng = r.nextInt(20)+2; int occurs; int i, j; ArrayList<Car> results = new ArrayList<Car>(); int l2 = leng; while (l2 > 1 && results.size() < 3) { results.add( (Car)engine.newInstance()); l2 /= r.nextInt(5)+1; } if (sources.length == 0) return results.toArray(new Car[0]); while (results.size() < leng) { occurs = r.nextInt(4)+1; i = r.nextInt(sources.length); for (j = 0; j < occurs; j++) { try { Car c2 = (Car)sources[i].newInstance(); if (sources[i].loaded()) c2.load(); else c2.unload(); results.add(c2); } catch (Exception ex) { ex.printStackTrace(); } } } if ((double)leng / 20 > r.nextDouble()) results.add(new Caboose()); return results.toArray(new Car[0]); } private void generate() { Random r = new Random(); Car[] cars = sc.values().toArray(new Car[0]); Car[] resultCars = generate(r, new Engine(), cars); for (Car c : resultCars) ctrain.myVC.add(c); } private JButton carButton(final Car c) { String d = c.show(); Icon i = new ImageIcon(TrainPainter.image(c, this)); JButton j = new JButton(d,i); j.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // because of the way the cars are added to the train // we have to have separate instances for each car // because a referencer is just copied // so it's actually many of the same car otherwise // this does create a problem for selected cars try { Car c2 = (Car)c.newInstance(); if (c.loaded()) c2.load(); else c2.unload(); ctrain.myVC.add(c2); } catch (Exception ex) { ex.printStackTrace(); } ctrain.revalidate(); ctrain.repaint(); } }); return j; } private void addLUButton(Car c) { c.load(); loaded.add(carButton(c)); // in order to have a loaded and unloaded car // separately, we need to have two instances try { Car c2 = (Car)c.newInstance(); c2.unload(); unloaded.add(carButton(c2)); } catch (Exception e) { e.printStackTrace(); } } private void addWidgets() { getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); JTabbedPane tabbedPane = new JTabbedPane(); nonload = new JPanel(); loaded = new JPanel(); unloaded = new JPanel(); nonload.setLayout(new GridLayout(0,2)); loaded.setLayout(new GridLayout(0,2)); unloaded.setLayout(new GridLayout(0,2)); ArrayList<Car> at = Factories.cars.allTypes(); for (int i = 0; i < at.size(); i++) { Car c = at.get(i); if (c.canUserCreate() == false) continue; if (c.isLoadable()) { addLUButton(c); } else { nonload.add(carButton(c)); } } tabbedPane.add("Special", nonload); tabbedPane.add("Loaded", loaded); tabbedPane.add("Unloaded", unloaded); getContentPane().add(tabbedPane); ctrain = new MultiLineTrainPanel(); getContentPane().add(ctrain); // create the combo boxes // for selecting entrance and speed JPanel hp = new JPanel(); hp.setLayout(new BoxLayout(hp, BoxLayout.X_AXIS)); hp.add(new JLabel("Entering At")); hp.add(Box.createHorizontalGlue()); enters = new JComboBox(); Iterator<EESegment> ei = ees.iterator(); while (ei.hasNext()) { EESegment ee = ei.next(); enters.addItem(ee.label); } hp.add(enters); getContentPane().add(hp); hp = new JPanel(); hp.setLayout(new BoxLayout(hp, BoxLayout.X_AXIS)); hp.add(new JLabel("Speed")); hp.add(Box.createHorizontalGlue()); speeds = new JComboBox(); int i; for (i = 1; i <= Train.MAX_THROTTLE; i++) { speeds.addItem(Integer.toString(i*incr) + " MPH"); } speeds.setSelectedIndex(i-2); // due to starting at 1 hp.add(speeds); getContentPane().add(hp); hp = new JPanel(); hp.setLayout(new BoxLayout(hp, BoxLayout.X_AXIS)); JButton b; b = new JButton("OK"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (ctrain.myVC.isEmpty()) { // cancel, no cars dispose(); return; } Car[] cr = (ctrain.myVC.toArray(new Car[0])); Train t = new Train(cr); if (t.hasEngine()) t.setThrottle(speeds.getSelectedIndex()+1); t.setVel(incr*(speeds.getSelectedIndex()+1)); // avoid acceleration wait // also if there are no engines, the train // would ever be stuck on the border EESegment ee = ees.get(enters.getSelectedIndex()); t.pos.r = ee; t.pos.orig = ee.HES; t.followMeOnce = true; t.getController().setTrainActionScriptNotify(sm); pf.addTrain(t, true); dispose(); // close window when done } }); hp.add(Box.createHorizontalGlue()); hp.add(b); hp.add(Box.createHorizontalGlue()); b = new JButton("Clear"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ctrain.myVC.clear(); ctrain.revalidate(); getContentPane().repaint(); } }); hp.add(b); hp.add(Box.createHorizontalGlue()); b = new JButton("Generate"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ctrain.myVC.clear(); generate(); ctrain.revalidate(); getContentPane().repaint(); } }); hp.add(b); hp.add(Box.createHorizontalGlue()); b = new JButton("Cancel"); b.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dispose(); } }); hp.add(b); hp.add(Box.createHorizontalGlue()); getContentPane().add(hp); setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); pack(); } private ScriptManager sm; /** * Shows the train creator window. * The rail segments are needed for the generator to know what load/unload cars are supported. * When created, the train will be added to the given trains collection automatically. * * @param lines An array of {@link RailSegment}s used for the train generator. * @param pf PlayFrame by which the {@link PlayFrame#addTrain(Train, boolean)} method will be called. * @param trainNotify The script manager to attach to the traincontroller for notification. */ public TrainCreator(RailSegment[] lines, PlayFrame pf, ScriptManager trainNotify) { super("New Train"); setIconImage(Images.frameIcon); // need to find all EE segments // and lu segments for generator ees = new Vector<EESegment>(); sc = new HashMap<String,Car>(); for (int i = 0; i < lines.length; i++) { if (lines[i] instanceof EESegment) ees.add((EESegment)lines[i]); if (lines[i] instanceof LUSegment) { Car[] cl = ((LUSegment)lines[i]).lu(); for (int j = 0; j < cl.length; j++) sc.put(cl[j].show() + (cl[j].loaded() ? "/L" : "/U"), cl[j]); } } this.pf = pf; sm = trainNotify; addWidgets(); } }
Neschur/railworld
src/net/kolls/railworld/play/TrainCreator.java
Java
gpl-2.0
9,483
<?php /** * @version CVS: 1.0.0 * @package Com_Propertycontact * @author azharuddin <azharuddin.shaikh53@gmail.com> * @copyright 2017 azharuddin * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; // Include dependancies jimport('joomla.application.component.controller'); JLoader::registerPrefix('Propertycontact', JPATH_COMPONENT); JLoader::register('PropertycontactController', JPATH_COMPONENT . '/controller.php'); // Execute the task. $controller = JControllerLegacy::getInstance('Propertycontact'); $controller->execute(JFactory::getApplication()->input->get('task')); $controller->redirect();
azharu53/kuwithome
components/com_propertycontact/propertycontact.php
PHP
gpl-2.0
676
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * The contents of this file are subject to the Netscape Public License * Version 1.0 (the "NPL"); you may not use this file except in * compliance with the NPL. You may obtain a copy of the NPL at * http://www.mozilla.org/NPL/ * * Software distributed under the NPL is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the NPL * for the specific language governing rights and limitations under the * NPL. * * The Initial Developer of this code under the NPL is Netscape * Communications Corporation. Portions created by Netscape are * Copyright (C) 1997-1999 Netscape Communications Corporation. All Rights * Reserved. * * This file was originally distributed with Rhino. I have copied it * into SmallJava to avoid enforcing a dependency on Rhino being * installed (and to avoid conflicting with installed versions of * Rhino) -- all hail Java's extraordinarily bad package system! */ package com.svincent.smalljava.rhino; public class Label { private static final int FIXUPTABLE_SIZE = 8; private static final boolean DEBUG = true; public Label() { itsPC = -1; } public short getPC() { return itsPC; } public void fixGotos(byte theCodeBuffer[]) { if (DEBUG) { if ((itsPC == -1) && (itsFixupTable != null)) throw new RuntimeException("Unlocated label"); } if (itsFixupTable != null) { for (int i = 0; i < itsFixupTableTop; i++) { int fixupSite = itsFixupTable[i]; // -1 to get delta from instruction start short offset = (short)(itsPC - (fixupSite - 1)); theCodeBuffer[fixupSite++] = (byte)(offset >> 8); theCodeBuffer[fixupSite] = (byte)offset; } } itsFixupTable = null; } public void setPC(short thePC) { if (DEBUG) { if ((itsPC != -1) && (itsPC != thePC)) throw new RuntimeException("Duplicate label"); } itsPC = thePC; } public void addFixup(int fixupSite) { if (itsFixupTable == null) { itsFixupTableTop = 1; itsFixupTable = new int[FIXUPTABLE_SIZE]; itsFixupTable[0] = fixupSite; } else { if (itsFixupTableTop == itsFixupTable.length) { int oldLength = itsFixupTable.length; int newTable[] = new int[oldLength + FIXUPTABLE_SIZE]; System.arraycopy(itsFixupTable, 0, newTable, 0, oldLength); itsFixupTable = newTable; } itsFixupTable[itsFixupTableTop++] = fixupSite; } } private short itsPC; private int itsFixupTable[]; private int itsFixupTableTop; }
shawn-vincent/moksa
src/com/svincent/smalljava/rhino/Label.java
Java
gpl-2.0
3,032
<?php /* * @version $Id: HEADER 15930 2011-10-30 15:47:55Z tsmr $ ------------------------------------------------------------------------- ocsinventoryng plugin for GLPI Copyright (C) 2015-2022 by the ocsinventoryng Development Team. https://github.com/pluginsGLPI/ocsinventoryng ------------------------------------------------------------------------- LICENSE This file is part of ocsinventoryng. ocsinventoryng 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. ocsinventoryng 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 ocsinventoryng. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ if (!defined('GLPI_ROOT')) { die("Sorry. You can't access directly to this file"); } /** * Class PluginOcsinventoryngRuleImportEntity */ class PluginOcsinventoryngRuleImportEntity extends CommonDBTM { static $rightname = "plugin_ocsinventoryng"; const NO_RULE = 0; /** * @param int $nb * * @return translated */ static function getTypeName($nb = 0) { return __('Elements not match with the rule', 'ocsinventoryng'); } /** * @param $name * * @return array */ static function cronInfo($name) { switch ($name) { case "CheckRuleImportEntity" : return ['description' => __('OCSNG', 'ocsinventoryng') . " - " . __('Alerts on computers that no longer respond the rules for assigning an item to an entity', 'ocsinventoryng')]; } } /** * Checking machines that no longer respond the assignment rules * * @param $task * * @return int */ static function cronCheckRuleImportEntity($task) { global $DB, $CFG_GLPI; ini_set("memory_limit", "-1"); ini_set("max_execution_time", "0"); if (!$CFG_GLPI["notifications_mailing"]) { return 0; } $CronTask = new CronTask(); if ($CronTask->getFromDBbyName("PluginOcsinventoryngRuleImportEntity", "CheckRuleImportEntity")) { if ($CronTask->fields["state"] == CronTask::STATE_DISABLE) { return 0; } } else { return 0; } $cron_status = 0; $plugin_ocsinventoryng_ocsservers_id = 0; foreach ($DB->request("glpi_plugin_ocsinventoryng_ocsservers", "`is_active` = 1 AND `use_checkruleimportentity` = 1") as $config) { $plugin_ocsinventoryng_ocsservers_id = $config["id"]; $plugin_ocsinventoryng_ocsservers_name = $config["name"]; if ($plugin_ocsinventoryng_ocsservers_id > 0) { $computers = self::checkRuleImportEntity($plugin_ocsinventoryng_ocsservers_id); foreach ($computers as $entities_id => $items) { $message = $plugin_ocsinventoryng_ocsservers_name . ": <br />" . sprintf(__('Items that do not meet the allocation rules for the entity %s: %s', 'ocsinventoryng'), Dropdown::getDropdownName("glpi_entities", $entities_id), count($items)) . "<br />"; if (NotificationEvent::raiseEvent("CheckRuleImportEntity", new PluginOcsinventoryngRuleImportEntity(), ['entities_id' => $entities_id, 'items' => $items])) { $cron_status = 1; if ($task) { $task->addVolume(1); $task->log($message); } else { Session::addMessageAfterRedirect($message); } } else { if ($task) { $task->addVolume(count($items)); $task->log($message . "\n"); } else { Session::addMessageAfterRedirect($message); } } } } } return $cron_status; } /** * Checks the assignment rules for the server computers * * @param $plugin_ocsinventoryng_ocsservers_id * * @return array */ static function checkRuleImportEntity($plugin_ocsinventoryng_ocsservers_id) { $data = []; $computers = self::getComputerOcsLink($plugin_ocsinventoryng_ocsservers_id); $ruleCollection = new RuleImportEntityCollection(); $ruleAsset = new RuleAssetCollection(); foreach ($computers as $computer) { $fields = $ruleCollection->processAllRules($computer, [], ['ocsid' => $computer['ocsid']]); //case pc matched with a rule if (isset($fields['_ruleid'])) { $entities_id = $computer['entities_id']; //Verification of the entity and location if (isset($fields['entities_id']) && $fields['entities_id'] != $entities_id) { if (!isset($data[$entities_id])) { $data[$entities_id] = []; } $data[$entities_id][$computer['id']] = $computer; $data[$entities_id][$computer['id']]['ruleid'] = $fields['_ruleid']; $rule = new Rule(); $rule->getFromDB($fields['_ruleid']); $data[$entities_id][$computer['id']]['rule_name'] = $rule->fields['name']; if (isset($fields['entities_id']) && $fields['entities_id'] != $entities_id) { if (!isset($data[$fields['entities_id']])) { $data[$fields['entities_id']] = []; } $data[$entities_id][$computer['id']]['error'][] = 'Entity'; $data[$entities_id][$computer['id']]['dataerror'][] = $fields['entities_id']; $data[$fields['entities_id']][$computer['id']] = $data[$entities_id][$computer['id']]; } } $output = ['locations_id' => $computer['locations_id']]; $fields = $ruleAsset->processAllRules($computer, $output, ['ocsid' => $computer['ocsid']]); if (isset($fields['locations_id']) && $fields['locations_id'] != $computer['locations_id'] || !isset($fields['locations_id']) && $computer['locations_id'] != 0) { if(!isset($data[$entities_id][$computer['id']])) { $data[$entities_id][$computer['id']] = $computer; } $data[$entities_id][$computer['id']]['error'][] = 'Location'; $data[$entities_id][$computer['id']]['dataerror'][] = $fields['locations_id']; } } else { //No rules match $entities_id = $computer['entities_id']; if (!isset($data[$entities_id])) { $data[$entities_id] = []; } $data[$entities_id][$computer['id']] = $computer; $data[$entities_id][$computer['id']]['error'][] = self::NO_RULE; } } return $data; } /** * @param $plugin_ocsinventoryng_ocsservers_id * * @return array */ static function getComputerOcsLink($plugin_ocsinventoryng_ocsservers_id) { $ocslink = new PluginOcsinventoryngOcslink(); $ocslinks = $ocslink->find(["plugin_ocsinventoryng_ocsservers_id" => $plugin_ocsinventoryng_ocsservers_id], ["entities_id"]); $computers = []; foreach ($ocslinks as $ocs) { $computer = new Computer(); if ($computer->getFromDB($ocs['computers_id'])) { $computer_id = $computer->fields['id']; $computers[$computer_id] = $computer->fields; $computers[$computer_id]['ocsservers_id'] = $ocs['plugin_ocsinventoryng_ocsservers_id']; $computers[$computer_id]['ocsid'] = $ocs['ocsid']; $computers[$computer_id]['_source'] = 'ocsinventoryng'; $computers[$computer_id]['_auto'] = true; } } return $computers; } }
pluginsGLPI/ocsinventoryng
inc/ruleimportentity.class.php
PHP
gpl-2.0
8,763
package ika.geo.grid; import ika.geo.GeoGrid; import ika.geo.GeoObject; import ika.geoexport.ESRIASCIIGridExporter; import ika.geoimport.EsriASCIIGridReader; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Multiply the cell values of two grids. * @author Bernhard Jenny, Institute of Cartography, ETH Zurich. */ public class GridMultiplyOperator implements GridOperator{ public static void main(String[] args) { try { String f1 = ika.utils.FileUtils.askFile(null, "Grid 1 (ESRI ASCII format)", true); if (f1 == null) { System.exit(0); } String f2 = ika.utils.FileUtils.askFile(null, "Grid 2 (ESRI ASCII format)", true); if (f2 == null) { System.exit(0); } GeoGrid grid1 = EsriASCIIGridReader.read(f1); GeoGrid grid2 = EsriASCIIGridReader.read(f2); GeoGrid res = new GridMultiplyOperator().operate(grid1, grid2); String resFilePath = ika.utils.FileUtils.askFile(null, "Result Grid (ESRI ASCII format)", false); if (resFilePath != null) { ESRIASCIIGridExporter.export(res, resFilePath); } System.exit(0); } catch (IOException ex) { Logger.getLogger(GridMultiplyOperator.class.getName()).log(Level.SEVERE, null, ex); } } public String getName() { return "Multiply"; } public GeoObject operate(GeoGrid geoGrid) { throw new UnsupportedOperationException("Not supported yet."); } public GeoGrid operate(GeoGrid grid1, GeoGrid grid2) { if (!grid1.hasSameExtensionAndResolution(grid2)) { throw new IllegalArgumentException("grids of different size"); } final int nrows = grid1.getRows(); final int ncols = grid1.getCols(); GeoGrid newGrid = new GeoGrid(ncols, nrows, grid1.getCellSize()); newGrid.setWest(grid1.getWest()); newGrid.setNorth(grid1.getNorth()); float[][] src1 = grid1.getGrid(); float[][] src2 = grid2.getGrid(); float[][] dstGrid = newGrid.getGrid(); for (int row = 0; row < nrows; ++row) { float[] srcRow1 = src1[row]; float[] srcRow2 = src2[row]; float[] dstRow = dstGrid[row]; for (int col = 0; col < ncols; ++col) { dstRow[col] = srcRow1[col] * srcRow2[col]; } } return newGrid; } }
OSUCartography/FlexProjector
src/ika/geo/grid/GridMultiplyOperator.java
Java
gpl-2.0
2,585
""" This is script doc string. """ g = 1 # block 1 at level 0 # this is a comment that starts a line after indent # this comment starts in column 1 h=2 # another inline comment # see if this comment is preceded by whitespace def f(a,b,c): # function with multiple returns """ This is multi-line function doc string. """ if a > b: # block 2 at level 1 if b > c: # block 3 at level 2 a = c # block 4 at level 3 else: # block 3 at level 2 return # block 4 at level 3 - explicit return print a # block 2 at level 1 # implicit return f(1,2,3) # block 1 at level 0 [f(i,3,5) for i in range(5)] def g(a,b): a += 1 if a > 'c': print "a is larger" def h(b): return b*b return h(b) g(3,2) v = 123 # this function definition shows that parameter names are not # defined until after the parameter list is completed. That is, # it is invalid to define: def h(a,b=a): ... def h(a, b=v,c=(v,),d={'a':(2,4,6)},e=[3,5,7]): print "b: a=%s b=%s" % (a,b) def k( a , b ) : c = a d = b if c > d: return d def kk( c ): return c*c return kk(c+d) class C: """ This is class doc string.""" def __init__( self ): """ This is a member function doc string""" if 1: return elif 0: return class D (object): def dd( self, *args, **kwds ): return args, kwds def main(): "This is single line doc string" h(3) c = C() g(3,2) f(7,5,3) # next, test if whitespace affects token sequences h ( 'a' , 'z' ) [ 1 : ] # next, test tokenization for statement that crosses lines h ( 'b' , 'y' ) [ 1 : ] if __name__ == "__main__": main()
ipmb/PyMetrics
PyMetrics/examples/sample.py
Python
gpl-2.0
1,928
package sampler; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import java.io.File; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.util.List; import java.util.Vector; import static org.mockito.Mockito.*; public class SamplerTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void partitionsCreatedFromInputAndWrittenToOutput() { SequenceReader sequenceReader = mock(SequenceReader.class); SubSequenceCollector subSequenceCollector = mock(SubSequenceCollector.class); PeriodicSampler periodicSampler = mock(PeriodicSampler.class); ListWriter listWriter = mock(ListWriter.class); Sampler sampler = new Sampler(sequenceReader, subSequenceCollector, periodicSampler, listWriter); Reader inputReader = new StringReader("abcdefghi"); Writer outputWriter = new StringWriter(); int numPartitions = 5; Sequence inputSequence = new Sequence("abcdefghi"); List<Sequence> sequenceList = new Vector<>(); sequenceList.add(new Sequence("abc")); sequenceList.add(new Sequence("def")); sequenceList.add(new Sequence("ghi")); List<Sequence> partitions = new Vector<>(); partitions.add(new Sequence("abc")); partitions.add(new Sequence("ghi")); when(sequenceReader.read(inputReader)).thenReturn(inputSequence); when(subSequenceCollector.collect(inputSequence)).thenReturn(sequenceList); when(periodicSampler.sample(sequenceList, numPartitions - 1)).thenReturn(partitions); sampler.createPartitions(inputReader, outputWriter, numPartitions); verify(listWriter).write(partitions, outputWriter); } @Test public void validateFailsIfLessThanTwoParametersPassed() { thrown.expect(SamplerException.class); Sampler.validateInputs(new String[] {}); } @Test public void validateFailsIfMoreThanTwoParametersPassed() { thrown.expect(SamplerException.class); Sampler.validateInputs(new String[] {"", "", ""}); } @Test public void firstArgumentMustBeFile() { thrown.expect(SamplerException.class); Sampler.validateInputs(new String[] {"does not exist", "1"}); } @Test public void secondArgumentMustBeInteger() throws IOException { File file = File.createTempFile("sampler-unit-test", ".tmp"); thrown.expect(SamplerException.class); Sampler.validateInputs(new String[] {file.getAbsolutePath(), "abc"}); } }
dennislloydjr/genome-indexing
src/test/java/sampler/SamplerTest.java
Java
gpl-2.0
2,670
package com.dovydasvenckus.timetracker.entry; import com.dovydasvenckus.timetracker.core.date.clock.DateTimeService; import com.dovydasvenckus.timetracker.core.pagination.PageSizeResolver; import com.dovydasvenckus.timetracker.core.security.ClientDetails; import com.dovydasvenckus.timetracker.project.Project; import com.dovydasvenckus.timetracker.project.ProjectRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Optional; @Service public class TimeEntryService { private final DateTimeService dateTimeService; private final TimeEntryRepository timeEntryRepository; private final ProjectRepository projectRepository; private final PageSizeResolver pageSizeResolver; public TimeEntryService(DateTimeService dateTimeService, TimeEntryRepository timeEntryRepository, ProjectRepository projectRepository, PageSizeResolver pageSizeResolver) { this.dateTimeService = dateTimeService; this.timeEntryRepository = timeEntryRepository; this.projectRepository = projectRepository; this.pageSizeResolver = pageSizeResolver; } @Transactional(readOnly = true) Page<TimeEntryDTO> findAll(int page, int pageSize, ClientDetails clientDetails) { return timeEntryRepository .findAllByDeleted( clientDetails.getId(), false, PageRequest.of(page, pageSizeResolver.resolvePageSize(pageSize)) ) .map(TimeEntryDTO::new); } @Transactional(readOnly = true) public Page<TimeEntryDTO> findAllByProject(long projectId, int page, int pageSize, ClientDetails clientDetails) { return timeEntryRepository .findAllByProject( projectId, clientDetails.getId(), PageRequest.of(page, pageSizeResolver.resolvePageSize(pageSize)) ) .map(TimeEntryDTO::new); } @Transactional public TimeEntry create(TimeEntryDTO timeEntryDTO, ClientDetails clientDetails) { timeEntryDTO.setId(null); TimeEntry timeEntry; timeEntry = new TimeEntry(timeEntryDTO, clientDetails.getId()); Optional<Project> project = projectRepository.findByIdAndCreatedBy( timeEntryDTO.getProject().getId(), clientDetails.getId() ); project.ifPresent(timeEntry::setProject); timeEntryRepository.save(timeEntry); return timeEntry; } @Transactional public void stop(TimeEntryDTO timeEntryDTO, ClientDetails clientDetails) { timeEntryRepository.findByIdAndCreatedBy(timeEntryDTO.getId(), clientDetails.getId()) .ifPresent(entry -> entry.setEndDate(dateTimeService.now())); } @Transactional public void delete(Long id, ClientDetails clientDetails) { timeEntryRepository.findByIdAndCreatedBy(id, clientDetails.getId()) .ifPresent(timeEntry -> timeEntry.setDeleted(true)); } Optional<TimeEntryDTO> findCurrentlyActive(ClientDetails clientDetails) { return timeEntryRepository.findCurrentlyActive(clientDetails.getId()) .map(TimeEntryDTO::new); } @Transactional public TimeEntry startTracking(Long projectId, String description, ClientDetails clientDetails) { Optional<Project> project = projectRepository.findByIdAndCreatedBy(projectId, clientDetails.getId()); if (project.isPresent()) { TimeEntry timeEntry = new TimeEntry(); timeEntry.setStartDate(dateTimeService.now()); timeEntry.setDescription(description); timeEntry.setProject(project.get()); timeEntry.setCreatedBy(clientDetails.getId()); timeEntryRepository.save(timeEntry); return timeEntry; } return null; } }
dovydasvenckus/time-tracker
src/main/java/com/dovydasvenckus/timetracker/entry/TimeEntryService.java
Java
gpl-2.0
4,153
<?php //Yii::import('application.extensions.EUploadedImage'); class MarketController extends Controller { /** * @var string the default layout for the views. Defaults to '//layouts/column2', meaning * using two-column layout. See 'protected/views/layouts/column2.php'. */ public $layout = '//layouts/column2'; /** * @return array action filters */ public function filters() { return array( 'accessControl', // perform access control for CRUD operations ); } /** * Specifies the access control rules. * This method is used by the 'accessControl' filter. * @return array access control rules */ public function accessRules() { return array( array('allow', // allow all users to perform 'index' and 'view' actions 'actions' => array('index', 'view', 'rss'), 'users' => array('*'), ), array('allow', // allow authenticated user to perform 'create' and 'update' actions 'actions' => array('create', 'update', 'join', 'panel', 'panelView', 'list', 'delete', 'expire'), 'users' => array('@'), ), array('allow', // allow admin user to perform 'admin' and 'delete' actions 'actions' => array('admin'), 'users' => array('admin'), ), array('deny', // deny all users 'users' => array('*'), ), ); } /** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionView($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $entity_id = Yii::app()->user->getId(); $model = MarketAd::model()->with( array( 'entities' => array('on' => ($entity_id ? 'entities.id=' . $entity_id : null)), 'joined' => array('on' => ($entity_id ? 'joined.entity_id=' . $entity_id : null)) ))->findByPk($id); $this->render('view', array( 'model' => $model, )); } /** * Displays a particular model. * @param integer $id the ID of the model to be displayed */ public function actionPanel($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $model = $this->loadModel($id); //MarketAd::model()->with('users')->findByPk($id); if (isset(Yii::app()->user->roles[$model->created_by])) { $criteria = new CDbCriteria; $criteria->with = array( 'marketAds' => array( 'together' => true, 'condition' => 'marketAds.id=' . $id, ), 'marketJoined' => array( 'together' => true, 'condition' => 'marketJoined.ad_id=' . $id, ), ); $criteria->compare('marketAds.id', $id); $dataProvider = new CActiveDataProvider('Entity', array( 'criteria' => $criteria, )); Notification::shown($model->created_by, Sid::getSID($model)); $this->render('panel', array( 'model' => $model, 'dataProvider' => $dataProvider, )); } else { Yii::app()->user->setFlash('error', Yii::t('market', 'You can not access to this advertisement control panel')); $this->redirect(array('view', 'id' => $id)); } } public function actionPanelView($ad_id, $entity_id) { if(!is_numeric($ad_id) || !is_numeric($entity_id)){ throw new CHttpException(404, 'Access denied.'); } $ad = $this->loadModel($ad_id); if (!isset(Yii::app()->user->roles[$model->created_by])) { $entity = Entity::model()->findByPk($entity_id); $joined = MarketJoined::model()->with('entity')->findByPk(array('ad_id' => $ad_id, 'entity_id' => $entity_id)); $joined->setScenario('panel'); if (isset($_POST['MarketJoined'])) { $joined->attributes = $_POST['MarketJoined']; if ($joined->save()) { /* if($joined->form_comment != '') { $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=utf-8' . "\r\n"; $headers .= "From: noreply@instauremoslademocracia.net\r\n"; if (mail($user->email,Yii::t('market','[Comment from DEMOS Market]').' '.$ad->title, $this->renderPartial('_joinMail', array('title' => $ad->title, 'message' => $joined->form_comment, 'ad_id' => $ad_id, 'user_id' => $user_id, ), true),$headers)) Yii::app()->user->setFlash('success',Yii::t('market','Thank you for contacting')); else Yii::app()->user->setFlash('error',Yii::t('market','E-mail not sent')); } */ $this->redirect(array('panel', 'id' => $ad_id)); } } Notification::shown($ad->created_by, Sid::getSID($joined)); $this->render('panelView', array( 'entity' => $entity, 'joined' => $joined, 'ad' => $ad, ) ); } else { Yii::app()->user->setFlash('error', Yii::t('market', 'You can not access to this advertisement control panel')); $this->redirect(array('view', 'id' => $ad_id)); } } /** * Creates a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionCreate($id = null) { $model = new MarketAd; // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); $entity = Entity::model()->findByPk(Yii::app()->user->logged); $user = $entity->getObject(); if ($id != null) { if (isset(Yii::app()->user->roles[$id])) { $model->created_by = $id; } else { throw new CHttpException(404, 'Access denied.'); } } if (isset($_POST['MarketAd'])) { $model->attributes = $_POST['MarketAd']; if ($model->save()) { if ($user->blocked) { ActivityLog::add(Yii::app()->user->logged, ActivityLog::BLOCKED_MARKET_AD, Sid::getSID($model)); } $this->redirect(array('view', 'id' => $model->id)); } } $model->expiration = date('Y-m-d', time() + MarketAd::MAX_EXPIRATION); $this->render('create', array( 'model' => $model, )); } /** * Updates a particular model. * If update is successful, the browser will be redirected to the 'view' page. * @param integer $id the ID of the model to be updated */ public function actionUpdate($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $model = $this->loadModel($id); if (!isset(Yii::app()->user->roles[$model->created_by])) { Yii::app()->user->setFlash('error', Yii::t('market', 'You can not update this advertisement')); $this->redirect(array('view', 'id' => $id)); return; } // Uncomment the following line if AJAX validation is needed // $this->performAjaxValidation($model); if (isset($_POST['MarketAd'])) { $model->attributes = $_POST['MarketAd']; if ($model->save()) $this->redirect(array('view', 'id' => $model->id)); } $this->render('update', array( 'model' => $model, )); } /** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'admin' page. * @param integer $id the ID of the model to be deleted */ public function actionExpire($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $model = $this->loadModel($id); if (!isset(Yii::app()->user->roles[$model->created_by])) { Yii::app()->user->setFlash('error', Yii::t('market', 'You can not update this advertisement')); $this->redirect(array('view', 'id' => $id)); return; } // we only allow deletion via POST request $model->expiration = '0000-00-00'; $model->save(); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if (!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index')); } /** * Deletes a particular model. * If deletion is successful, the browser will be redirected to the 'admin' page. * @param integer $id the ID of the model to be deleted */ public function actionDelete($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $model = $this->loadModel($id); if (!isset(Yii::app()->user->roles[$model->created_by])) { Yii::app()->user->setFlash('error', Yii::t('market', 'You can not delete this advertisement')); $this->redirect(array('view', 'id' => $id)); return; } $model->visible = 0; $model->save(); Yii::app()->user->setFlash('notice', Yii::t('app', 'The advertisement have been moved away')); // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser if (!isset($_GET['ajax'])) $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index')); // else // throw new CHttpException(400,'Invalid request. Please do not repeat this request again.'); } /** * Join to a Market Ad a new model. * If creation is successful, the browser will be redirected to the 'view' page. */ public function actionJoin($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $ad = $this->loadModel($id); $entity_id = Yii::app()->user->getId(); $model = MarketJoined::model()->findByPk(array('ad_id' => $id, 'entity_id' => $entity_id)); if ($model == null) { $model = new MarketJoined; $model->ad_id = $id; $already_joined = false; } else { $already_joined = true; Yii::app()->user->setFlash('success', Yii::t('market', 'You are already joined, update anything you need.')); } $model->setScenario('join'); // uncomment the following code to enable ajax-based validation /* if(isset($_POST['ajax']) && $_POST['ajax']==='market-joined-join-form') { echo CActiveForm::validate($model); Yii::app()->end(); } */ if (isset($_POST['MarketJoined'])) { $model->attributes = $_POST['MarketJoined']; if ($model->validate()) { // form inputs are valid, do something here if ($model->save()) { Yii::app()->user->setFlash('success', Yii::t('market', 'You have successfully joined')); $this->redirect(array('view', 'id' => $ad->id)); } } } Notification::shown($entity_id, Sid::getSID($model)); $this->render('join', array('model' => $model, 'ad' => $ad)); } /** * Lists all models. */ public function actionList($mode = null, $tribe_id=null) { if((!!$mode && !is_numeric($mode)) || (!!$tribe_id && !is_numeric($tribe_id))){ throw new CHttpException(404, 'Access denied.'); } $this->actionIndex($mode,$tribe_id); } /** * Lists all models. */ public function actionIndex($mode = null, $tribe_id=null) { if((!!$mode && !is_numeric($mode)) || (!!$tribe_id && !is_numeric($tribe_id))){ throw new CHttpException(404, 'Access denied.'); } $entity_id = Yii::app()->user->getId(); $model = new MarketAd('search'); $model->unsetAttributes(); // clear any default values $tribe= null; if ($tribe_id && is_numeric($tribe_id)){ $tribe = Tribe::model()->findByPk($tribe_id); } if (isset($_GET['MarketAd'])) $model->attributes = $_GET['MarketAd']; $dataProvider = MarketAd::getAds($model, $mode, $entity_id,$tribe_id); $this->render('index', array( 'dataProvider' => $dataProvider, 'model' => $model, 'tribe' => $tribe )); } /** * Manages all models. */ public function actionAdmin() { $model = new MarketAd('search'); $model->unsetAttributes(); // clear any default values if (isset($_GET['MarketAd'])) $model->attributes = $_GET['MarketAd']; $this->render('admin', array( 'model' => $model, )); } /** * Manages all models. */ public function actionRss() { $entity_id = Yii::app()->user->getId(); $dataProvider = MarketAd::getAds(null, 3, $entity_id); $dataProvider->setPagination(false); $this->renderPartial('rss', array( 'dataProvider' => $dataProvider, )); } /** * Returns the data model based on the primary key given in the GET variable. * If the data model is not found, an HTTP exception will be raised. * @param integer the ID of the model to be loaded */ public function loadModel($id) { if(!is_numeric($id)){ throw new CHttpException(404, 'Access denied.'); } $model = MarketAd::model()->findByPk($id); if ($model === null) throw new CHttpException(404, 'The requested page does not exist.'); return $model; } /** * Performs the AJAX validation. * @param CModel the model to be validated */ protected function performAjaxValidation($model) { if (isset($_POST['ajax']) && $_POST['ajax'] === 'market-ad-form') { echo CActiveForm::validate($model); Yii::app()->end(); } } }
mianfiga/monedademos
protected/controllers/MarketController.php
PHP
gpl-2.0
14,834
/* * This source file is part of CaesarJ * For the latest info, see http://caesarj.org/ * * Copyright © 2003-2005 * Darmstadt University of Technology, Software Technology Group * Also see acknowledgements in readme.txt * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * $Id: OpcodeNames.java,v 1.2 2005-01-24 16:52:57 aracic Exp $ */ package org.caesarj.classfile; /** * The human-readable name of this opcodes */ public class OpcodeNames { /** * Returns the name for this opcode */ public static String getName(int opcode) { return opcodeNames[opcode]; } // -------------------------------------------------------------------- // DATA MEMBERS // -------------------------------------------------------------------- private static String[] opcodeNames = { "nop", "aconst_null", "iconst_m1", "iconst_0", "iconst_1", "iconst_2", "iconst_3", "iconst_4", "iconst_5", "lconst_0", "lconst_1", "fconst_0", "fconst_1", "fconst_2", "dconst_0", "dconst_1", "bipush", "sipush", "ldc", "ldc_w", "ldc2_w", "iload", "lload", "fload", "dload", "aload", "iload_0", "iload_1", "iload_2", "iload_3", "lload_0", "lload_1", "lload_2", "lload_3", "fload_0", "fload_1", "fload_2", "fload_3", "dload_0", "dload_1", "dload_2", "dload_3", "aload_0", "aload_1", "aload_2", "aload_3", "iaload", "laload", "faload", "daload", "aaload", "baload", "caload", "saload", "istore", "lstore", "fstore", "dstore", "astore", "istore_0", "istore_1", "istore_2", "istore_3", "lstore_0", "lstore_1", "lstore_2", "lstore_3", "fstore_0", "fstore_1", "fstore_2", "fstore_3", "dstore_0", "dstore_1", "dstore_2", "dstore_3", "astore_0", "astore_1", "astore_2", "astore_3", "iastore", "lastore", "fastore", "dastore", "aastore", "bastore", "castore", "sastore", "pop", "pop2", "dup", "dup_x1", "dup_x2", "dup2", "dup2_x1", "dup2_x2", "swap", "iadd", "ladd", "fadd", "dadd", "isub", "lsub", "fsub", "dsub", "imul", "lmul", "fmul", "dmul", "idiv", "ldiv", "fdiv", "ddiv", "irem", "lrem", "frem", "drem", "ineg", "lneg", "fneg", "dneg", "ishl", "lshl", "ishr", "lshr", "iushr", "lushr", "iand", "land", "ior", "lor", "ixor", "lxor", "iinc", "i2l", "i2f", "i2d", "l2i", "l2f", "l2d", "f2i", "f2l", "f2d", "d2i", "d2l", "d2f", "i2b", "i2c", "i2s", "lcmp", "fcmpl", "fcmpg", "dcmpl", "dcmpg", "ifeq", "ifne", "iflt", "ifge", "ifgt", "ifle", "if_icmpeq", "if_icmpne", "if_icmplt", "if_icmpge", "if_icmpgt", "if_icmple", "if_acmpeq", "if_acmpne", "goto", "jsr", "ret", "tableswitch", "lookupswitch", "ireturn", "lreturn", "freturn", "dreturn", "areturn", "return", "getstatic", "putstatic", "getfield", "putfield", "invokevirtual", "invokespecial", "invokestatic", "invokeinterface", "xxxunusedxxx", "new", "newarray", "anewarray", "arraylength", "athrow", "checkcast", "instanceof", "monitorenter", "monitorexit", "wide", "multianewarray", "ifnull", "ifnonnull", "goto_w", "jsr_w" }; }
tud-stg-lang/caesar-compiler
src/org/caesarj/classfile/OpcodeNames.java
Java
gpl-2.0
4,355
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ declare(strict_types=1); namespace eZ\Publish\API\Repository\Values\Content\Search\Facet; use eZ\Publish\API\Repository\Values\Content\Search\Facet; /** * This class represents a field range facet. * * @deprecated since eZ Platform 3.2.0, to be removed in eZ Platform 4.0.0. */ class FieldRangeFacet extends Facet { /** * Number of documents not containing any terms in the queried fields. * * @var int */ public $missingCount; /** * The number of terms which are not in the queried top list. * * @var int */ public $otherCount; /** * The total count of terms found. * * @var int */ public $totalCount; /** * For each interval there is an entry with statistical data. * * @var \eZ\Publish\API\Repository\Values\Content\Search\Facet\RangeFacetEntry[] */ public $entries; }
gggeek/ezpublish-kernel
eZ/Publish/API/Repository/Values/Content/Search/Facet/FieldRangeFacet.php
PHP
gpl-2.0
1,081
package de.tum.bgu.msm.syntheticPopulationGenerator.properties; import de.tum.bgu.msm.common.datafile.TableDataSet; import de.tum.bgu.msm.properties.PropertiesUtil; import de.tum.bgu.msm.utils.SiloUtil; import org.apache.commons.math.distribution.GammaDistributionImpl; import java.util.ResourceBundle; public class GermanyPropertiesSynPop extends AbstractPropertiesSynPop { public GermanyPropertiesSynPop(ResourceBundle bundle) { PropertiesUtil.newPropertySubmodule("SP: main properties"); state = PropertiesUtil.getStringProperty(bundle, "state.synPop", "01"); states = PropertiesUtil.getStringPropertyArray(bundle, "states.synPop.splitting", new String[]{"01","10"}); numberOfSubpopulations = PropertiesUtil.getIntProperty(bundle, "micro.data.subpopulations", 1); populationSplitting = PropertiesUtil.getBooleanProperty(bundle, "micro.data.splitting", false); runBySubpopulation = PropertiesUtil.getBooleanProperty(bundle,"run.by.subpopulation",false); readMergeAndSplit = PropertiesUtil.getBooleanProperty(bundle, "micro.data.read.splitting", false); runSyntheticPopulation = PropertiesUtil.getBooleanProperty(bundle, "run.synth.pop.generator", false); runIPU = PropertiesUtil.getBooleanProperty(bundle, "run.ipu.synthetic.pop", false); runAllocation = PropertiesUtil.getBooleanProperty(bundle, "run.population.allocation", false); //runJobAllocation = PropertiesUtil.getBooleanProperty(bundle, "run.job.de.tum.bgu.msm.syntheticPopulationGenerator.germany.disability ", true); // was there initially. was true - than can not find Agri runJobAllocation = PropertiesUtil.getBooleanProperty(bundle, "run.job.allocation", true); twoGeographicalAreasIPU = PropertiesUtil.getBooleanProperty(bundle, "run.ipu.city.and.county", false); boroughIPU = PropertiesUtil.getBooleanProperty(bundle,"run.three.areas",false); runDisability = PropertiesUtil.getBooleanProperty(bundle, "run.disability", false); runMicrolocation = PropertiesUtil.getBooleanProperty(bundle, "run.sp.microlocation", false); microDataFile = PropertiesUtil.getStringProperty(bundle, "micro.data", "C:/Users/Wei/Documents/germanyModel/topSecretData/suf2010v1.dat"); // todo this table is not a property but a data container, "ID_city" might be a property? (if this is applciable to other implementations) marginalsMunicipality = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"marginals.municipality","input/syntheticPopulation/" + state + "/marginalsMunicipality.csv")); marginalsMunicipality.buildIndex(marginalsMunicipality.getColumnPosition("ID_city")); jobsByTaz = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"jobs.by.taz","input/syntheticPopulation" + "/jobsByTaz.csv")); jobsByTaz.buildIndex(jobsByTaz.getColumnPosition("taz")); //todo same as municipalities marginalsCounty = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"marginals.county","input/syntheticPopulation/" + state + "/marginalsCounty.csv")); marginalsCounty.buildIndex(marginalsCounty.getColumnPosition("ID_county")); selectedMunicipalities = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"municipalities.list","input/syntheticPopulation/" + state + "/municipalitiesList.csv")); selectedMunicipalities.buildIndex(selectedMunicipalities.getColumnPosition("ID_city")); cellsMatrix = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"taz.definition","input/syntheticPopulation/" + state + "/zoneAttributeswithTAZ.csv")); cellsMatrix.buildIndex(cellsMatrix.getColumnPosition("ID_cell")); zoneSystemFileName = PropertiesUtil.getStringProperty(bundle,"taz.definition ","input/syntheticPopulation/" + state + "/zoneAttributeswithTAZ.csv"); //todo this cannot be the final name of the matrix omxFileName = PropertiesUtil.getStringProperty(bundle, "distanceODmatrix", "input/syntheticPopulation/tdTest_distance.omx"); attributesMunicipality = PropertiesUtil.getStringPropertyArray(bundle, "attributes.municipality", new String[]{"Agr", "Ind", "Srv"}); attributesCounty = PropertiesUtil.getStringPropertyArray(bundle, "attributes.county", new String[]{"Agr", "Ind", "Srv"}); ageBracketsPerson = PropertiesUtil.getIntPropertyArray(bundle, "age.brackets", new int[]{9, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64, 69, 74, 79, 84, 120}); ageBracketsPersonQuarter = null; jobStringType = PropertiesUtil.getStringPropertyArray(bundle, "employment.types", new String[]{"Agr", "Ind", "Srv"}); alphaJob = PropertiesUtil.getDoubleProperty(bundle, "employment.choice.alpha", 50); gammaJob = PropertiesUtil.getDoubleProperty(bundle, "employment.choice.gamma", -0.003); tripLengthDistributionFileName = PropertiesUtil.getStringProperty(bundle, "trip.length.distribution", "input/syntheticPopulation/tripLengthDistribution.csv"); schoolTypes = PropertiesUtil.getIntPropertyArray(bundle, "school.types", new int[]{1, 2, 3}); alphaUniversity = PropertiesUtil.getDoubleProperty(bundle, "university.choice.alpha", 50); gammaUniversity = PropertiesUtil.getDoubleProperty(bundle, "university.choice.gamma", -0.003); householdSizes = PropertiesUtil.getIntPropertyArray(bundle, "household.size.brackets", new int[]{1, 2, 3, 4, 5}); maxIterations = PropertiesUtil.getIntProperty(bundle, "max.iterations.ipu", 1000); maxError = PropertiesUtil.getDoubleProperty(bundle, "max.error.ipu", 0.0001); improvementError = PropertiesUtil.getDoubleProperty(bundle, "min.improvement.error.ipu", 0.001); iterationError = PropertiesUtil.getDoubleProperty(bundle, "iterations.improvement.ipu", 2); increaseError = PropertiesUtil.getDoubleProperty(bundle, "increase.error.ipu", 1.05); initialError = PropertiesUtil.getDoubleProperty(bundle, "ini.error.ipu", 1000); double incomeShape = PropertiesUtil.getDoubleProperty(bundle, "income.gamma.shape", 1.0737036186); double incomeRate = PropertiesUtil.getDoubleProperty(bundle, "income.gamma.rate", 0.0006869439); //todo consider to read it from another source e.g. a JS calculator or CSV file //this is not a property but a variable? incomeGammaDistribution = new GammaDistributionImpl(incomeShape, 1 / incomeRate); //todo this properties will be doubled with silo model run properties weightsFileName = PropertiesUtil.getStringProperty(bundle, "weights.matrix", "microData/" + state + "/interimFiles/weigthsMatrix.csv"); errorsMunicipalityFileName = PropertiesUtil.getStringProperty(bundle, "errors.IPU.municipality.matrix", "microData/" + state + "/interimFiles/errorsIPUmunicipality.csv"); errorsCountyFileName = PropertiesUtil.getStringProperty(bundle, "errors.IPU.county.matrix", "microData/" + state + "/interimFiles/errorsIPUcounty.csv"); errorsSummaryFileName = PropertiesUtil.getStringProperty(bundle, "errors.IPU.summary.matrix", "microData/" + state + "/interimFiles/errorsIPUsummary.csv"); frequencyMatrixFileName = PropertiesUtil.getStringProperty(bundle,"frequency.matrix.file","microData/" + state + "/interimFiles/quencyMatrix.csv"); buildingLocationlist = null; jobLocationlist = null; schoolLocationlist = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"school.location", "input/syntheticPopulation/08_schoolLocation.csv")); firstVacantJob = PropertiesUtil.getIntProperty(bundle,"first.vacant.job.id", 45000000); /*cellsMicrolocations = SiloUtil.readCSVfile2("C:/models/silo/germany/input/syntheticPopulation/all_raster_100_updated.csv"); cellsMicrolocations.buildStringIndex(cellsMicrolocations.getColumnPosition("id"));*/ microPersonsFileName = PropertiesUtil.getStringProperty(bundle, "micro.persons", "microData/" + state + "/interimFiles/microPersons.csv"); microHouseholdsFileName = PropertiesUtil.getStringProperty(bundle, "micro.households", "microData/" + state + "/interimFiles/microHouseholds.csv"); zonalDataIPU = null; householdsFileName = PropertiesUtil.getStringProperty(bundle, "household.file.ascii", "microData/hh"); personsFileName = PropertiesUtil.getStringProperty(bundle, "person.file.ascii", "microData/pp"); dwellingsFileName = PropertiesUtil.getStringProperty(bundle, "dwelling.file.ascii", "microData/dd"); jobsFileName = PropertiesUtil.getStringProperty(bundle, "job.file.ascii", "microData/jj"); pathSyntheticPopulationFiles = PropertiesUtil.getStringProperty(bundle, "path.synthetic.ascii", "microData/"); householdsStateFileName = PropertiesUtil.getStringProperty(bundle, "household.file.ascii.sp", "microData/" + state + "/hh"); personsStateFileName = PropertiesUtil.getStringProperty(bundle, "person.file.ascii.sp", "microData/" + state + "/pp"); dwellingsStateFileName = PropertiesUtil.getStringProperty(bundle, "dwelling.file.ascii.sp", "microData/" + state + "/dd"); jobsStateFileName = PropertiesUtil.getStringProperty(bundle, "job.file.ascii.sp", "microData/" + state + "/jj"); counters = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"counters.synthetic.population","microData/subPopulations/countersByState.csv")); counters.buildStringIndex(counters.getColumnPosition("state")); vacantJobPercentage = PropertiesUtil.getIntProperty(bundle,"jobs.vacant.percentage", 25); if (boroughIPU) { attributesBorough = PropertiesUtil.getStringPropertyArray(bundle, "attributes.borough", new String[]{"Agr", "Ind", "Srv"}); marginalsBorough = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle, "marginals.borough", "input/syntheticPopulation/" + state + "/marginalsBorough.csv")); marginalsBorough.buildIndex(marginalsBorough.getColumnPosition("ID_borough")); selectedBoroughs = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"municipalities.list.borough","input/syntheticPopulation/" + state + "/municipalitiesListBorough.csv")); selectedBoroughs.buildIndex(selectedBoroughs.getColumnPosition("ID_borough")); cellsMatrixBoroughs = SiloUtil.readCSVfile(PropertiesUtil.getStringProperty(bundle,"taz.definition","input/syntheticPopulation/" + state + "/zoneAttributesBoroughwithTAZ.csv")); cellsMatrixBoroughs.buildIndex(cellsMatrixBoroughs.getColumnPosition("ID_cell")); } } }
msmobility/silo
synthetic-population/src/main/java/de/tum/bgu/msm/syntheticPopulationGenerator/properties/GermanyPropertiesSynPop.java
Java
gpl-2.0
10,681
/************************************************************************* Copyright (C) 2005 Joseph D'Errico, Wei Qin See file COPYING for more information. 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. *************************************************************************/ #ifndef CGEN_HPP #define CGEN_HPP #include "arch.hpp" char *emitc_nop(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_add(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_addi(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_addiu(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_addu(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sub(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_subu(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_mult(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_multu(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_div(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_divu(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_and(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_andi(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_nor(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_or(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_ori(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_xor(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_xori(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sll(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sllv(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_srl(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_srlv(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sra(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_srav(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_slt(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_slti(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sltiu(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sltu(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_beq(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_bgez(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_bgezal(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_bgtz(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_blez(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_bltzal(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_bltz(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_bne(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_j(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_jal(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_jalr(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_jr(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_mfhi(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_mflo(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_mthi(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_mtlo(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_mfc1(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_mtc1(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_cfc1(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_ctc1(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_lb(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_lbu(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_lh(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_lhu(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_lw(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_lwl(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_lwr(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_lui(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sb(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sh(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sw(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_swl(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_swr(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_lwc1(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_swc1(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_ll(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sc(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_brk(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_abs_d(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_abs_s(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_add_d(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_add_s(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_cvt_d_s(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_cvt_d_w(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_cvt_s_d(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_cvt_s_w(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_cvt_w_d(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_cvt_w_s(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_div_d(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_div_s(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_mov_d(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_mov_s(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_mul_d(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_mul_s(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_neg_d(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_neg_s(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sub_d(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_sub_s(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_c_cond_d(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_c_cond_s(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_bc1f(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_bc1t(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); char *emitc_syscall(char *, emulator_t *, target_addr_t, target_addr_t, target_addr_t, bool); #endif
kagucho/mipsim
jit/mips_gen.hpp
C++
gpl-2.0
9,099
package de.zedlitz.opendocument; import groovy.lang.Closure; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; /** * A row in an OpenDocument table. * * @author jzedlitz * */ public class Row { /** * Element name "table-row" */ static final QName ELEMENT_ROW = new QName(Document.NS_TABLE, "table-row"); private final XMLStreamReaderWithDepth xpp; private final int depth; private int emptyCells; List<Cell> allCells = null; /** * @param xpp */ public Row(final XMLStreamReaderWithDepth xpp) { this.xpp = xpp; this.depth = xpp.getDepth(); } /** * @see de.freenet.jzedlitz.oo.Row#nextCell() */ public Cell nextCell() { Cell result = null; // while there are empty (faked) cells return one those if (this.emptyCells > 0) { result = new EmptyCell(); this.emptyCells--; } else { try { int eventType = xpp.getEventType(); while (!((eventType == XMLStreamConstants.END_ELEMENT) && Row.ELEMENT_ROW.equals(xpp.getName())) && (eventType != XMLStreamConstants.END_DOCUMENT) && (xpp.getDepth() >= depth)) { if ((eventType == XMLStreamConstants.START_ELEMENT) && Cell.ELEMENT_CELL.equals(xpp.getName())) { final Cell myCell = new Cell(xpp); if (myCell.getNumberColumnsRepeated() > 1) { this.emptyCells = myCell.getNumberColumnsRepeated() - 1; } result = myCell; xpp.next(); break; } eventType = xpp.next(); } } catch (final XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } Cell getAt(final int i) { // switch to memory mode if (allCells == null) { allCells = new ArrayList<Cell>(); Cell nextCell = this.nextCell(); while (nextCell != null) { allCells.add(nextCell); nextCell = this.nextCell(); } } return allCells.get(i); } /** * @see de.zedlitz.opendocument.Row#eachCell(groovy.lang.Closure) */ public void eachCell(final Closure c) { Cell nextCell = this.nextCell(); while (nextCell != null) { c.call(nextCell); nextCell = this.nextCell(); } } }
jze/opendocument-reader
src/main/java/de/zedlitz/opendocument/Row.java
Java
gpl-2.0
2,873
#include "nexusdefs.h" #include "nexustoken.h" #include "nexus.h" /** * @class NexusBlock * @file nexus.h * @file nexusblock.cpp * @author Paul O. Lewis * @copyright Copyright © 1999. All Rights Reserved. * @variable isDisabled [bool:private] true if this block is currently disabled * @variable isEmpty [bool:private] true if this object is currently storing data * @variable next [NexusBlock*:protected] pointer to next block in list * @variable id [nxsstring:protected] holds name of block (e.g., "DATA", "TREES", etc.) * @see Nexus * @see NexusReader * @see NexusToken * * This is the base class from which all Nexus block classes are derived. * The abstract virtual function Read must be overridden for each derived * class to provide the ability to read everything following the block name * (which is read by the Nexus object) to the end or endblock statement. * Derived classes must provide their own data storage and access functions. */ /** * @constructor * * Default constructor * Initializes 'next' and 'nexus' data members to NULL, and 'isEmpty' and * 'isEnabled' to true. */ NexusBlock::NexusBlock() : next(NULL), nexus(NULL), isEmpty(true), isEnabled(true) { } /** * @destructor * * Does nothing. */ NexusBlock::~NexusBlock() { } /** * @method CharLabelToNumber [int:protected] * @param s [nxsstring] the character label to be translated to character number * * This base class version simply returns -1, but a derived class should * override this function if it needs to construct and run a SetReader * object to read a set involving characters. The SetReader object may * need to use this function to look up a character label encountered in * the set. A class that overrides this method should return the * character index in the range [1..nchar]; i.e., add one to the 0-offset * index. */ int NexusBlock::CharLabelToNumber( nxsstring /*s*/ ) { return 0; } /** * @method Disable [void:public] * * Sets the value of isEnabled to false. A NexusBlock * can be disabled (by calling this method) if blocks of that type * are to be skipped during execution of the nexus file. * If a disabled block is encountered, the virtual * Nexus::SkippingDisabledBlock function is called. */ void NexusBlock::Disable() { isEnabled = false; } /** * @method Enable [void:public] * * Sets the value of isEnabled to true. A NexusBlock * can be disabled (by calling Disable) if blocks of that type * are to be skipped during execution of the nexus file. * If a disabled block is encountered, the virtual * Nexus::SkippingDisabledBlock function is called. */ void NexusBlock::Enable() { isEnabled = true; } /** * @method IsEnabled [bool:public] * * Returns value of isEnabled, which can be controlled through * use of the Enable and Disable member functions. A NexusBlock * should be disabled if blocks of that type are to be skipped * during execution of the nexus file. If a disabled block is * encountered, the virtual Nexus::SkippingDisabledBlock function * is called. */ bool NexusBlock::IsEnabled() { return isEnabled; } /** * @method IsEmpty [bool:public] * * Returns true if Read function has not been called since the last Reset. * This base class version simply returns the value of the data member * isEmpty. If you derive a new block class from NexusBlock, be sure * to set isEmpty to true in your Reset function and isEmpty to false in your * Read function. */ bool NexusBlock::IsEmpty() { return isEmpty; } /** * @method Read [virtual void:protected] * @param token [NexusToken&] the NexusToken to use for reading block * @param in [istream&] the input stream from which to read * * This abstract virtual function must be overridden for each derived * class to provide the ability to read everything following the block name * (which is read by the Nexus object) to the end or endblock statement. * Characters are read from the input stream in. Note that to get output * comments displayed, you must derive a class from NexusToken, override * the member function OutputComment to display a supplied comment, and * then pass a reference to an object of the derived class to this function. */ // virtual void Read( NexusToken& token, istream& in ) = 0; /** * @method Reset [virtual void:protected] * * This abstract virtual function must be overridden for each derived * class to completely reset the block object in preparation for reading * in another block of this type. This function is called by the Nexus * object just prior to calling the block object's Read function. */ // virtual void Reset() = 0; /** * @method GetID [nxsstring:public] * * Returns the id nxsstring. */ nxsstring NexusBlock::GetID() { return id; } /** * @method Report [virtual void:public] * @param out [ostream&] the output stream to which the report is sent * * Provides a brief report of the contents of the block. */ // virtual void Report( ostream& out ) = 0; /** * @method SetNexus [virtual void:public] * @param nxsptr [Nexus*] pointer to a Nexus object * * Sets the nexus data member of the NexusBlock object to * nxsptr. */ void NexusBlock::SetNexus( Nexus* nxsptr ) { nexus = nxsptr; } /** * @method SkippingCommand [virtual void:public] * @param commandName [nxsstring] the name of the command being skipped * * This function is called when an unknown command named commandName is * about to be skipped. This version of the function does nothing (i.e., * no warning is issued that a command was unrecognized. Override this * virtual function in a derived class to provide such warnings to the * user. */ void NexusBlock::SkippingCommand( nxsstring /* commandName */ ) { } /** * @method TaxonLabelToNumber [int:protected] * @param s [nxsstring] the taxon label to be translated to a taxon number * * This base class version simply returns 0, but a derived class should * override this function if it needs to construct and run a SetReader * object to read a set involving taxa. The SetReader object may * need to use this function to look up a taxon label encountered in * the set. A class that overrides this method should return the * taxon index in the range [1..ntax]; i.e., add one to the 0-offset * index. */ int NexusBlock::TaxonLabelToNumber( nxsstring /*s*/ ) { return 0; }
rdmpage/treeviewx
ncl-2.0/src/nexusblock.cpp
C++
gpl-2.0
6,417
/* * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. * */ package sun.jvm.hotspot.types.basic; import sun.jvm.hotspot.debugger.*; import sun.jvm.hotspot.types.*; /** A specialization of BasicField which represents a field containing an oop value and which adds typechecked getValue() routines returning OopHandles. */ public class BasicNarrowOopField extends BasicOopField implements NarrowOopField { private static final boolean DEBUG = false; public BasicNarrowOopField (OopField oopf) { super(oopf); } public BasicNarrowOopField(BasicTypeDataBase db, Type containingType, String name, Type type, boolean isStatic, long offset, Address staticFieldAddress) { super(db, containingType, name, type, isStatic, offset, staticFieldAddress); if (DEBUG) { System.out.println(" name " + name + " type " + type + " isStatic " + isStatic + " offset " + offset + " static addr " + staticFieldAddress); } if (!type.isOopType()) { throw new WrongTypeException("Type of a BasicOopField must be an oop type"); } } /** The field must be nonstatic and the type of the field must be a Java oop, or a WrongTypeException will be thrown. */ public OopHandle getValue(Address addr) throws UnmappedAddressException, UnalignedAddressException, WrongTypeException { return getNarrowOopHandle(addr); } /** The field must be static and the type of the field must be a Java oop, or a WrongTypeException will be thrown. */ public OopHandle getValue() throws UnmappedAddressException, UnalignedAddressException, WrongTypeException { return getNarrowOopHandle(); } }
TheTypoMaster/Scaper
openjdk/hotspot/agent/src/share/classes/sun/jvm/hotspot/types/basic/BasicNarrowOopField.java
Java
gpl-2.0
2,652
package com.teambitcoin.coinwallet; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.Gravity; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.widget.Toast; import android.view.KeyEvent; import android.view.inputmethod.*; import com.teambitcoin.coinwallet.models.*; public class ForgotPassword extends Activity { String username; // username variable to hold the input String secretQuestionDb; // variable to hold the secret question query from database String answer; // answer variable to the input String dbAnswer; // variable to hold answer query from database String dbPassword; // variable to hold password query from database public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.forgot_main); // added this text when hit done after the user entered username // had to make it final in order to work... final EditText editText1 = (EditText) findViewById(R.id.username_field); editText1.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_DONE) { Context context = getApplicationContext(); CharSequence text = "Successfully entered username"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); username = editText1.getText().toString(); CharSequence usernamePrint = "Welcome " + username + " your question will appear shortly"; int durationUsername = Toast.LENGTH_LONG; Toast toastUsername = Toast.makeText(context, usernamePrint, durationUsername); toastUsername.show(); // method to query the secret question from database // according to username entered... // this method return a string with the question querySecretQuestion(username); handled = true; } return handled; } }); // added this text when hit done after the user entered answer final EditText editText2 = (EditText) findViewById(R.id.password_field); editText2.setOnEditorActionListener(new OnEditorActionListener() { public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_DONE) { Context context = getApplicationContext(); CharSequence text = "Successfully answered question"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); // set the variable answer to be the inputed answer user answer = editText2.getText().toString(); handled = true; } return handled; } }); // adding the button object Button button = (Button) findViewById(R.id.login_button); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Context context = getApplicationContext(); CharSequence text = "Checking answer..."; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.show(); validateAnswer(answer); // call the method which will check if the answer entered // corresponds to the right answer to that member's secret question } }); } public String querySecretQuestion(String username) { if (User.getUser(username) == null) { Context context = getApplicationContext(); secretQuestionDb = null; CharSequence secretQuestion = "No Secret Question associated with the inputted username"; int duration2 = Toast.LENGTH_LONG; Toast toast2 = Toast.makeText(context, secretQuestion, duration2); toast2.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, -40); toast2.show(); return secretQuestionDb; } if (User.getUser(username).getQuestion() == null) { Context context = getApplicationContext(); secretQuestionDb = null; CharSequence secretQuestion = "No Secret Question associated with the inputted username"; int duration2 = Toast.LENGTH_LONG; Toast toast2 = Toast.makeText(context, secretQuestion, duration2); toast2.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, -40); toast2.show(); return secretQuestionDb; } else { Context context = getApplicationContext(); secretQuestionDb = User.getUser(username).getQuestion(); CharSequence secretQuestion = "Secret question: " + secretQuestionDb; int duration2 = Toast.LENGTH_LONG; Toast toast2 = Toast.makeText(context, secretQuestion, duration2); toast2.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, -40); toast2.show(); return secretQuestionDb; } // take the inputed username and go to the database first check if that username exists // if not output the entered username does not exist // if the username exist query the secret question associated with it and return it } public String validateAnswer(String answer) { if (User.getUser(username) == null) { Context context = getApplicationContext(); dbPassword = null; CharSequence secretAnswer = "Could not find any user with the given username"; int duration2 = Toast.LENGTH_LONG;// stay on screen longer Toast toast2 = Toast.makeText(context, secretAnswer, duration2); toast2.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, -40); toast2.show(); return dbPassword; } // if the password is null, wrong answer inputed. no password shown. if (User.getUser(username).recoverPassword(answer) == null) { dbPassword = null; Context context = getApplicationContext(); // wrong answer no password shown CharSequence text = "Wrong answer to question, please try again"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, -40); toast.show(); return dbPassword; } else { // if correct answer shown, show password to user dbPassword = User.getUser(username).recoverPassword(answer); Context context = getApplicationContext(); // set to password, query from database CharSequence text = "Password: " + dbPassword; int duration = Toast.LENGTH_LONG; Toast toast = Toast.makeText(context, text, duration); toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, -40); toast.show(); return dbPassword; } // query from database the answer associated to the user's secret // question, if the inputted answer // equals the one saved in the database output the user recorded // password else print WRONG ANSWER... } }
cwallet/coinwallet
CoinWallet/src/main/java/com/teambitcoin/coinwallet/ForgotPassword.java
Java
gpl-2.0
8,528
//----------------------------------------------------------------------------- // Class: Block Manager // Authors: LiXizhi, Clayman // Emails: LiXizhi@yeah.net // Company: ParaEngine // Date: 2012.11.26 //----------------------------------------------------------------------------- #include "ParaEngine.h" #include "SceneObject.h" #include "EffectManager.h" #include "OceanManager.h" #include "ParaVertexBufferPool.h" #include "ShadowMap.h" #ifdef USE_DIRECTX_RENDERER #include "DirectXEngine.h" #endif #include "SunLight.h" #include "BaseCamera.h" #include "ParaWorldAsset.h" #include "terrain/GlobalTerrain.h" #include "WorldInfo.h" #include "BlockCommon.h" #include "BlockRegion.h" #include "terrain/Settings.h" #include "IBatchedElementDraw.h" #include "AISimulator.h" #include "NPLRuntime.h" #include "BlockLightGridClient.h" #include "ParaEngineSettings.h" #include "ViewportManager.h" #include "LightObject.h" #include "NPLHelper.h" #include "util/os_calls.h" #include "ChunkVertexBuilderManager.h" #include "MultiFrameBlockWorldRenderer.h" #include "BlockWorldClient.h" #include "ParaScriptingCommon.h" #include "ParaScriptingMisc.h" /** default block light color. due to shader optimization, there can only be one color for all emissive blocks. * ARBG: it is usually white or yellow(red) color. */ // #define DEFAULT_BLOCK_LIGHT_COLOR 0xffffffff #define DEFAULT_BLOCK_LIGHT_COLOR 0xffffffff // define to output log for debugging. //#define PRINT_CHUNK_LOG #ifdef PRINT_CHUNK_LOG #include "ParaTime.h" #endif namespace ParaEngine { BlockWorldClient* BlockWorldClient::g_pInstance = NULL; int32_t BlockWorldClient::g_TexPass = 0; int32_t BlockWorldClient::g_twoTexPass = 1; int32_t BlockWorldClient::g_TexNormalMapPass = 2; int32_t BlockWorldClient::g_twoTexNormalMapPass = 3; // not used. #ifdef PARAENGINE_MOBILE int32_t BlockWorldClient::g_transparentBlockPass = 2; int32_t BlockWorldClient::g_waterBlockPass = 2; int32_t BlockWorldClient::g_bumpyBlockPass = 1; #else int32_t BlockWorldClient::g_transparentBlockPass = 3; int32_t BlockWorldClient::g_waterBlockPass = 4; int32_t BlockWorldClient::g_bumpyBlockPass = 5; #endif int32_t BlockWorldClient::g_selectBlockPass = 1; inline int64_t GetBlockSparseIndex(int64_t bx, int64_t by, int64_t bz) { return by * 30000 * 30000 + bx * 30000 + bz; } ////////////////////////////////////////////////////////////////////////// //BlockWorldClient ////////////////////////////////////////////////////////////////////////// BlockWorldClient::BlockWorldClient() :m_maxSelectBlockPerBatch(80), m_isUnderLiquid(false), m_vBlockLightColor(DEFAULT_BLOCK_LIGHT_COLOR), m_nBufferRebuildCountThisTick(0), m_bUsePointTextureFiltering(true), m_nVertexBufferSizeLimit(100 * 1024 * 1024), m_nMaxVisibleVertexBufferBytes(100 * 1024 * 1024), m_nAlwaysInVertexBufferChunkRadius(2), m_pMultiFrameRenderer(NULL), #ifdef USE_DIRECTX_RENDERER m_pDepthStencilSurface(NULL), m_render_target_block_info_surface(NULL), m_render_target_depth_tex_surface(NULL), m_render_target_normal_surface(NULL), m_pOldRenderTarget(NULL), m_pOldZBuffer(NULL), #endif m_bUseSunlightShadowMap(true), m_bUseWaterReflection(true), m_bMovieOutputMode(false), m_bAsyncChunkMode(true) { g_pInstance = this; m_damageDegree = 0; #if defined(PARAENGINE_CLIENT) || defined(WIN32) m_nMaxBufferRebuildPerTick = 4; m_nNearCameraChunkDist = 8; m_nMaxBufferRebuildPerTick_FarChunk = 2; m_nVertexBufferSizeLimit = 200 * 1024 * 1024; m_nMaxVisibleVertexBufferBytes = (100 * 1024 * 1024); #else m_nMaxBufferRebuildPerTick = 4; m_nNearCameraChunkDist = 6; m_nMaxBufferRebuildPerTick_FarChunk = 2; m_nVertexBufferSizeLimit = 100 * 1024 * 1024; m_nMaxVisibleVertexBufferBytes = (50 * 1024 * 1024); #endif #ifdef PARAENGINE_MOBILE SetGroupByChunkBeforeTexture(true); #endif SAFE_DELETE(m_pLightGrid); m_pLightGrid = new CBlockLightGridClient(m_activeChunkDim + 2, this); // ensure that all vertices can be indexed by uint16 index buffer. PE_ASSERT((BlockConfig::g_maxFaceCountPerBatch * 4) <= 0xffff); RenderableChunk::GetVertexBufferPool()->SetFullSizedBufferSize(BlockConfig::g_maxFaceCountPerBatch * sizeof(BlockVertexCompressed) * 4); // 6MB at most RenderableChunk::GetVertexBufferPool()->SetMaxPooledCount(6000000 / RenderableChunk::GetVertexBufferPool()->GetFullSizedBufferSize()); m_pMultiFrameRenderer = new CMultiFrameBlockWorldRenderer(this); } BlockWorldClient::~BlockWorldClient() { DeleteDeviceObjects(); SAFE_DELETE(m_pMultiFrameRenderer); for (int i = 0; i < (int)(m_activeChunks.size()); ++i) { SAFE_DELETE(m_activeChunks[i]); } m_activeChunks.clear(); ChunkVertexBuilderManager::GetInstance().Cleanup(); RenderableChunk::StaticRelease(); } void BlockWorldClient::EnterWorld(const string& sWorldDir, float x, float y, float z) { if (m_isInWorld) return; ChunkVertexBuilderManager::GetInstance().StartChunkBuildThread(this); Scoped_WriteLock<BlockReadWriteLock> lock_(GetReadWriteLock()); CBlockWorld::EnterWorld(sWorldDir, x, y, z); } void BlockWorldClient::Cleanup() { DeleteDeviceObjects(); for (int i = 0; i < BLOCK_GROUP_ID_MAX; ++i) { m_highLightTextures[i].reset(); } } void BlockWorldClient::LeaveWorld() { if (!m_isInWorld) return; ChunkVertexBuilderManager::GetInstance().Cleanup(); Scoped_WriteLock<BlockReadWriteLock> lock_(GetReadWriteLock()); Cleanup(); CBlockWorld::LeaveWorld(); } void BlockWorldClient::DeleteAllBlocks() { Scoped_WriteLock<BlockReadWriteLock> lock_(GetReadWriteLock()); for (std::map<int, BlockRegion*>::iterator iter = m_regionCache.begin(); iter != m_regionCache.end(); iter++) { iter->second->DeleteAllBlocks(); } for (uint32_t i = 0; i < m_activeChunks.size(); i++) { m_activeChunks[i]->SetChunkDirty(true); } m_isVisibleChunkDirty = true; } void BlockWorldClient::PreRender(bool bIsShadowPass) { if (!m_isInWorld) return; Vector3 camWorldPos = CGlobals::GetSceneState()->vEye; Uint16x3 camBlockPos; BlockCommon::ConvertToBlockIndex(camWorldPos.x, camWorldPos.y, camWorldPos.z, camBlockPos.x, camBlockPos.y, camBlockPos.z); SetEyeBlockId(camBlockPos); Block* eye_block = GetBlock(camBlockPos.x, camBlockPos.y, camBlockPos.z); if (eye_block && eye_block->GetTemplate()) { m_isUnderLiquid = eye_block->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_liquid); } else m_isUnderLiquid = false; if (!bIsShadowPass) GetLightGrid().UpdateLighting(); //perform culling and refresh render buffers if dirty. m_nBufferRebuildCountThisTick = 0; if (m_isVisibleChunkDirty || (GetBlockRenderMethod() == BLOCK_RENDER_FANCY_SHADER && GetUseSunlightShadowMap())) UpdateVisibleChunks(bIsShadowPass); m_solidRenderTasks.clear(); m_alphaTestRenderTasks.clear(); m_alphaBlendRenderTasks.clear(); m_reflectedWaterRenderTasks.clear(); //fill render task Vector3 renderOfs = CGlobals::GetScene()->GetRenderOrigin(); float verticalOffset = GetVerticalOffset(); if (!bIsShadowPass) ChunkVertexBuilderManager::GetInstance().UploadPendingChunksToDevice(); if (IsRenderBlocks()) { // please note m_visibleChunks is already arranged in a spiral pattern around the eye. // hence the closer ones get updated sooner. m_nBufferRebuildCountThisTick = 0; CheckRebuildVisibleChunks(m_bAsyncChunkMode, bIsShadowPass); ClearVisibleChunksToByteLimit(bIsShadowPass); #ifdef PRINT_CHUNK_LOG static int64 g_lastTime = GetTimeUS(); int64 curTime = GetTimeUS(); if (m_nBufferRebuildCountThisTick > 0) { OUTPUT_LOG("deltaTime: %d ms: chunk buffer update this tick %d\n", (int)(curTime - g_lastTime) / 1000, (int)m_nBufferRebuildCountThisTick); } g_lastTime = curTime; #endif for (uint32 i = 0; i < m_visibleChunks.size(); i++) { m_visibleChunks[i]->FillRenderQueue(this, renderOfs, verticalOffset); } } //sort data if (!IsGroupByChunkBeforeTexture()) { if (m_solidRenderTasks.size() > 0) sort(m_solidRenderTasks.begin(), m_solidRenderTasks.end(), CompareRenderOrder); } if (m_alphaTestRenderTasks.size() > 0) sort(m_alphaTestRenderTasks.begin(), m_alphaTestRenderTasks.end(), CompareRenderOrder); if (m_alphaBlendRenderTasks.size() > 0) sort(m_alphaBlendRenderTasks.begin(), m_alphaBlendRenderTasks.end(), CompareRenderOrder); if (m_reflectedWaterRenderTasks.size() > 0) sort(m_reflectedWaterRenderTasks.begin(), m_reflectedWaterRenderTasks.end(), CompareRenderOrder); } void BlockWorldClient::RenderShadowMap() { #ifdef USE_DIRECTX_RENDERER // only render shadow map for fancy shader mode. if ((GetBlockRenderMethod() != BLOCK_RENDER_FANCY_SHADER) || !GetUseSunlightShadowMap()) return; // prepare shadow pass PreRender(true); // make sure all shaders are replaced. PrepareAllRenderTargets(false); if (m_alphaTestRenderTasks.size() == 0 && m_solidRenderTasks.size() == 0 && m_alphaBlendRenderTasks.size() == 0) return; if (m_block_effect_fancy == 0) return; m_block_effect_fancy->LoadAsset(); const float fBlockSize = BlockConfig::g_blockSize; Vector3 renderOfs = CGlobals::GetScene()->GetRenderOrigin(); float verticalOffset = GetVerticalOffset(); Uint16x3 renderBlockOfs; renderBlockOfs.x = (uint16_t)(renderOfs.x / fBlockSize); renderBlockOfs.z = (uint16_t)(renderOfs.z / fBlockSize); Vector3 renderBlockOfs_remain; renderBlockOfs_remain.x = renderOfs.x - renderBlockOfs.x * fBlockSize; renderBlockOfs_remain.z = renderOfs.z - renderBlockOfs.z * fBlockSize; EffectManager* pEffectManager = CGlobals::GetEffectManager(); RenderDevicePtr pDevice = CGlobals::GetRenderDevice(); IScene* pScene = CGlobals::GetEffectManager()->GetScene(); CBaseCamera* pCamera = pScene->GetCurrentCamera(); Matrix4 matViewProj; if (pCamera) { const Matrix4& pView = (CGlobals::GetEffectManager()->GetViewTransform()); const Matrix4& pProj = (CGlobals::GetEffectManager()->GetProjTransform()); matViewProj = (pView) * (pProj); } CEffectFile* pEffect = NULL; pEffectManager->BeginEffect(TECH_BLOCK_FANCY, &pEffect); if (pEffect != 0 && pEffect->begin(false)) { VertexDeclarationPtr pVertexLayout = GetVertexLayout(); pDevice->SetVertexDeclaration(pVertexLayout); // turn off alpha blending to enable early-Z on modern graphic cards. pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE); pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO); pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); ////////////////////////////////////////////////////////////////////////// // set the wave time parameter double time = CGlobals::GetGameTime(); // in case it loses accuracy, we will subtract integer number of 2*PI from time // time -= ((int)(time / (2*MATH_PI)))*(2*MATH_PI); time = (int)(time * 1000) % 1000000; pEffect->setParameter(CEffectFile::k_ConstVector1, Vector4((float)time, 0.f, 0.f, 0.f).ptr()); IDirect3DIndexBuffer9* pIndexBuffer = GetIndexBuffer(); pDevice->SetIndices(pIndexBuffer); for (int nRenderPass = 0; nRenderPass <= BlockRenderPass_AlphaBlended; nRenderPass++) { std::vector<BlockRenderTask*>* pCurRenderQueue = GetRenderQueueByPass((BlockRenderPass)nRenderPass); IDirect3DVertexBuffer9* pCurVB = NULL; uint16_t curTamplerId = 0; int32_t curPass = -1; D3DCULL culling = D3DCULL_CCW; IDirect3DTexture9* pCurTex0 = NULL; if (pCurRenderQueue->size() > 0) { for (uint32_t i = 0; i < pCurRenderQueue->size(); i++) { BlockRenderTask* pRenderTask = (*pCurRenderQueue)[i]; IDirect3DVertexBuffer9* pVB = pRenderTask->GetVertexBuffer(); if (pVB != pCurVB) { pDevice->SetStreamSource(0, pVB, 0, sizeof(BlockVertexCompressed)); pCurVB = pVB; } int32_t passId = 0; if (curTamplerId != pRenderTask->GetTemplateId()) { BlockTemplate* pTempate = pRenderTask->GetTemplate(); if (pTempate->IsShadowCaster()) { passId = 0; } if (curPass != passId) { if (curPass > -1) pEffect->EndPass(); if (pEffect->BeginPass(passId)) { curPass = passId; } else { curPass = -1; continue; } } TextureEntity* pTexEntity = pTempate->GetTexture0(pRenderTask->GetUserData()); if (pTexEntity && pTexEntity->GetTexture() != pCurTex0) { pCurTex0 = pTexEntity->GetTexture(); pDevice->SetTexture(0, pCurTex0); } // culling mode if (pTempate->GetBlockModel().IsDisableFaceCulling()) { if (culling != D3DCULL_NONE) { pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); culling = D3DCULL_NONE; } } else if (nRenderPass != BlockRenderPass_Opaque && m_isUnderLiquid && pRenderTask->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_liquid)) { if (culling != D3DCULL_CW) { pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW); culling = D3DCULL_CW; } } else { if (culling != D3DCULL_CCW) { pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); culling = D3DCULL_CCW; } } } Matrix4 vWorldMatrix(Matrix4::IDENTITY); Uint16x3& vMinPos = pRenderTask->GetMinBlockPos(); vWorldMatrix._11 = vWorldMatrix._22 = vWorldMatrix._33 = fBlockSize; vWorldMatrix._41 = (vMinPos.x - renderBlockOfs.x)*fBlockSize - renderBlockOfs_remain.x; vWorldMatrix._42 = vMinPos.y * fBlockSize - renderOfs.y + verticalOffset; vWorldMatrix._43 = (vMinPos.z - renderBlockOfs.z)*fBlockSize - renderBlockOfs_remain.z; vWorldMatrix = vWorldMatrix * matViewProj; pEffect->setMatrix(CEffectFile::k_worldViewProjMatrix, &vWorldMatrix); pEffect->CommitChanges(); pDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, pRenderTask->GetVertexOfs(), pRenderTask->GetVertexCount(), pRenderTask->GetIndexOfs(), pRenderTask->GetPrimitiveCount()); } } if (curPass > -1) pEffect->EndPass(); pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); } // turn blending on again pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); pEffect->end(); } #endif } void BlockWorldClient::Render(BlockRenderPass nRenderPass, std::vector<BlockRenderTask*>* pCurRenderQueue, int nRenderMethod) { if (!m_isInWorld) return; BlockRenderMethod dwRenderMethod = (nRenderMethod < 0) ? GetBlockRenderMethod() : (BlockRenderMethod)nRenderMethod; // no need to lock if (pCurRenderQueue == 0) pCurRenderQueue = GetRenderQueueByPass(nRenderPass); RenderDevicePtr pDevice = CGlobals::GetRenderDevice(); if (pCurRenderQueue->size() > 0) { const float fBlockSize = BlockConfig::g_blockSize; Vector3 renderOfs = CGlobals::GetScene()->GetRenderOrigin(); float verticalOffset = GetVerticalOffset(); Uint16x3 renderBlockOfs; renderBlockOfs.x = (uint16_t)(renderOfs.x / fBlockSize); renderBlockOfs.z = (uint16_t)(renderOfs.z / fBlockSize); Vector3 renderBlockOfs_remain; renderBlockOfs_remain.x = renderOfs.x - renderBlockOfs.x * fBlockSize; renderBlockOfs_remain.z = renderOfs.z - renderBlockOfs.z * fBlockSize; EffectManager* pEffectManager = CGlobals::GetEffectManager(); CEffectFile* pEffect = NULL; if (dwRenderMethod == BLOCK_RENDER_FANCY_SHADER) { if (nRenderPass != BlockRenderPass_AlphaBlended) { if (!PrepareAllRenderTargets()) { // try a lower shader other than fancy SetBlockRenderMethod(BLOCK_RENDER_FAST_SHADER); return; } pEffectManager->BeginEffect(TECH_BLOCK_FANCY, &pEffect); if (pEffect == 0) { // try a lower shader other than fancy ; SetBlockRenderMethod(BLOCK_RENDER_FAST_SHADER); return; } } else { // use ordinary shader for alpha blended blocks. pEffectManager->BeginEffect(TECH_BLOCK, &pEffect); } } else if (dwRenderMethod == BLOCK_RENDER_FAST_SHADER) { pEffectManager->BeginEffect(TECH_BLOCK, &pEffect); } else if (dwRenderMethod == BLOCK_RENDER_FIXED_FUNCTION) { pEffectManager->BeginEffect(TECH_BLOCK, &pEffect); } // CEffectFile* pEffect = pEffectManager->GetCurrentEffectFile(); if (nRenderPass == BlockRenderPass_AlphaBlended || nRenderPass == BlockRenderPass_ReflectedWater) { pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); } else { if (nRenderPass == BlockRenderPass_AlphaTest) pDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_NONE); // turn off alpha blending to enable early-Z on modern graphic cards. pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE); pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ZERO); pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); } if (pEffect == 0) { #ifdef USE_DIRECTX_RENDERER if (dwRenderMethod != BLOCK_RENDER_FIXED_FUNCTION) { SetBlockRenderMethod(BLOCK_RENDER_FIXED_FUNCTION); return; } ////////////////////////////////////////////////////////////////////////// // render using fixed function pipeline pDevice->SetFVF(block_vertex::FVF); IDirect3DIndexBuffer9* pIndexBuffer = GetIndexBuffer(); pDevice->SetIndices(pIndexBuffer); IDirect3DVertexBuffer9* pCurVB = NULL; uint16_t curTamplerId = 0; int32_t curPass = -1; D3DCULL culling = D3DCULL_CCW; IDirect3DTexture9* pCurTex0 = NULL; IDirect3DTexture9* pCurTex1 = NULL; IDirect3DTexture9* pCurTex2 = NULL; pDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE); pDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_DIFFUSE | D3DTA_ALPHAREPLICATE); for (uint32_t i = 0; i < pCurRenderQueue->size(); i++) { BlockRenderTask* pRenderTask = (*pCurRenderQueue)[i]; IDirect3DVertexBuffer9* pVB = pRenderTask->GetVertexBuffer(); if (pVB != pCurVB) { pDevice->SetStreamSource(0, pVB, 0, sizeof(BlockVertexCompressed)); pCurVB = pVB; } int32_t passId; if (curTamplerId != pRenderTask->GetTemplateId()) { BlockTemplate* pTempate = pRenderTask->GetTemplate(); if (pTempate->IsMatchAttribute(BlockTemplate::batt_twoTexture)) passId = g_twoTexPass; else if (pTempate->IsMatchAttribute(BlockTemplate::batt_transparent)) passId = g_transparentBlockPass; else passId = g_TexPass; if (curPass != passId) { curPass = passId; if (passId == 0) { pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); } else if (passId == 1) { pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE); } else if (passId == 2) { pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE); } else if (passId == 3) { pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE); } else { curPass = -1; continue; } } TextureEntity* pTexEntity = pTempate->GetTexture0(pRenderTask->GetUserData()); if (pTexEntity && pTexEntity->GetTexture() != pCurTex0) { pCurTex0 = pTexEntity->GetTexture(); pDevice->SetTexture(0, pCurTex0); } pTexEntity = pTempate->GetTexture1(); if (pTexEntity && pTexEntity->GetTexture() != pCurTex1) { pCurTex1 = pTexEntity->GetTexture(); pDevice->SetTexture(1, pCurTex1); } /* fixed function never use normal map pTexEntity = pTempate->GetNormalMap(); if(pTexEntity && pTexEntity->GetTexture()!=pCurTex2) { pCurTex2 = pTexEntity->GetTexture(); pDevice->SetTexture(2,pCurTex2); }*/ // culling mode if (pTempate->GetBlockModel().IsDisableFaceCulling()) { if (culling != D3DCULL_NONE) { pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); culling = D3DCULL_NONE; } } else if (nRenderPass != BlockRenderPass_Opaque && m_isUnderLiquid && pRenderTask->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_liquid)) { if (culling != D3DCULL_CW) { pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW); culling = D3DCULL_CW; } } else { if (culling != D3DCULL_CCW) { pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); culling = D3DCULL_CCW; } } } Matrix4 vWorldMatrix(Matrix4::IDENTITY); Uint16x3& vMinPos = pRenderTask->GetMinBlockPos(); vWorldMatrix._11 = vWorldMatrix._22 = vWorldMatrix._33 = fBlockSize; vWorldMatrix._41 = (vMinPos.x - renderBlockOfs.x)*fBlockSize - renderBlockOfs_remain.x; vWorldMatrix._42 = vMinPos.y * fBlockSize - renderOfs.y + verticalOffset; vWorldMatrix._43 = (vMinPos.z - renderBlockOfs.z)*fBlockSize - renderBlockOfs_remain.z; pDevice->SetTransform(D3DTS_WORLD, vWorldMatrix.GetPointer()); RenderDevice::DrawIndexedPrimitive(pDevice, RenderDevice::DRAW_PERF_TRIANGLES_TERRAIN, D3DPT_TRIANGLELIST, 0, pRenderTask->GetVertexOfs(), pRenderTask->GetVertexCount(), pRenderTask->GetIndexOfs(), pRenderTask->GetPrimitiveCount()); } pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); pDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_DISABLE); pDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE); #endif } else if (pEffect != 0 && pEffect->begin(false)) { #ifdef USE_OPENGL_RENDERER if (nRenderPass == BlockRenderPass_AlphaTest) { // ParaEngine's opengl renderer currently does not support shared uniforms between passes, so do this. // Remove this: when you support it. pEffect->BeginPass(g_transparentBlockPass); pEffect->EndPass(); } CGlobals::GetEffectManager()->applyFogParameters(); if (CGlobals::GetEffectManager()->IsUsingShadowMap()) CGlobals::GetEffectManager()->GetShadowMap()->SetShadowTexture(*pEffect, 1); else CGlobals::GetEffectManager()->GetShadowMap()->UnsetShadowTexture(1); #endif VertexDeclarationPtr pVertexLayout = GetVertexLayout(); pDevice->SetVertexDeclaration(pVertexLayout); if (dwRenderMethod == BLOCK_RENDER_FANCY_SHADER) { ////////////////////////////////////////////////////////////////////////// // set the wave time parameter double time = CGlobals::GetGameTime(); // in case it loses accuracy, we will subtract integer number of 2*PI from time // time -= ((int)(time / (2*MATH_PI)))*(2*MATH_PI); time = (int)(time * 1000) % 1000000; pEffect->setParameter(CEffectFile::k_ConstVector1, Vector4((float)time, 0.f, 0.f, 0.f).ptr()); } else { Vector3 vDir = -CGlobals::GetScene()->GetSunLight().GetSunDirection(); Vector4 vDir_(vDir.x, vDir.y, vDir.z, 1.0f); pEffect->setParameter(CEffectFile::k_sunVector, &vDir_); } IndexBufferDevicePtr_type pIndexBuffer = GetIndexBuffer(); pDevice->SetIndices(pIndexBuffer); VertexBufferDevicePtr_type pCurVB = 0; uint16_t curTamplerId = 0; int32_t curPass = -1; D3DCULL culling = D3DCULL_CCW; DeviceTexturePtr_type pCurTex0 = 0; DeviceTexturePtr_type pCurTex1 = 0; DeviceTexturePtr_type pCurTex2 = 0; IScene* pScene = CGlobals::GetEffectManager()->GetScene(); CBaseCamera* pCamera = pScene->GetCurrentCamera(); Matrix4 matViewProj; if (pCamera) { const Matrix4& pView = (CGlobals::GetEffectManager()->GetViewTransform()); const Matrix4& pProj = (CGlobals::GetEffectManager()->GetProjTransform()); matViewProj = (pView) * (pProj); } /** block light params and sun intensity*/ Vector4 vLightParams(m_vBlockLightColor.r, m_vBlockLightColor.g, m_vBlockLightColor.b, m_sunIntensity); pEffect->setParameter(CEffectFile::k_ConstVector0, (const void*)(&vLightParams)); for (uint32_t i = 0; i < pCurRenderQueue->size(); i++) { BlockRenderTask* pRenderTask = (*pCurRenderQueue)[i]; VertexBufferDevicePtr_type pVB = pRenderTask->GetVertexBuffer(); if (pVB != pCurVB) { pDevice->SetStreamSource(0, pVB, 0, sizeof(BlockVertexCompressed)); pCurVB = pVB; } int32_t passId; if (curTamplerId != pRenderTask->GetTemplateId()) { BlockTemplate* pTempate = pRenderTask->GetTemplate(); if (pTempate->IsMatchAttribute(BlockTemplate::batt_twoTexture)) passId = g_twoTexPass; else if (nRenderPass == BlockRenderPass_AlphaTest) { passId = g_transparentBlockPass; } else if (nRenderPass == BlockRenderPass_AlphaBlended || nRenderPass == BlockRenderPass_ReflectedWater) { passId = g_TexPass; if (pTempate->GetCategoryID() == 8 && dwRenderMethod == BLOCK_RENDER_FANCY_SHADER) { passId = g_waterBlockPass; } } else if (pTempate->GetNormalMap() && dwRenderMethod == BLOCK_RENDER_FANCY_SHADER) { passId = g_bumpyBlockPass; } else passId = g_TexPass; if (curPass != passId) { if (curPass > -1) pEffect->EndPass(); if (pEffect->BeginPass(passId)) { curPass = passId; pCurTex0 = 0; pCurTex1 = 0; pCurTex2 = 0; // pEffect->setMatrix(CEffectFile::k_viewProjMatrix, &matViewProj); // pDevice->SetVertexShaderConstantF(0,&matViewProj._11,4); } else { curPass = -1; continue; } } TextureEntity* pTexEntity = pTempate->GetTexture0(pRenderTask->GetUserData()); if (pTexEntity && pTexEntity->GetTexture() != pCurTex0) { pCurTex0 = pTexEntity->GetTexture(); pDevice->SetTexture(0, pCurTex0); } pTexEntity = pTempate->GetTexture1(); if (pTexEntity && pTexEntity->GetTexture() != pCurTex1) { pCurTex1 = pTexEntity->GetTexture(); pDevice->SetTexture(1, pCurTex1); } pTexEntity = pTempate->GetNormalMap(); if (pTexEntity && pTexEntity->GetTexture() != pCurTex2) { pCurTex2 = pTexEntity->GetTexture(); if (dwRenderMethod == BLOCK_RENDER_FANCY_SHADER) { pDevice->SetTexture(2, pCurTex2); } } // culling mode if (pTempate->GetBlockModel().IsDisableFaceCulling()) { if (culling != D3DCULL_NONE) { pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); culling = D3DCULL_NONE; } } else if (nRenderPass != BlockRenderPass_Opaque && m_isUnderLiquid && pRenderTask->GetTemplate()->IsMatchAttribute(BlockTemplate::batt_liquid)) { if (culling != D3DCULL_CW) { pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW); culling = D3DCULL_CW; } } else { if (culling != D3DCULL_CCW) { pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); culling = D3DCULL_CCW; } } } // Matrix4 vWorldMatrix(Matrix4::IDENTITY); Uint16x3& vMinPos = pRenderTask->GetMinBlockPos(); vWorldMatrix._11 = vWorldMatrix._22 = vWorldMatrix._33 = fBlockSize; vWorldMatrix._41 = (vMinPos.x - renderBlockOfs.x)*fBlockSize - renderBlockOfs_remain.x; vWorldMatrix._42 = vMinPos.y * fBlockSize - renderOfs.y + verticalOffset; vWorldMatrix._43 = (vMinPos.z - renderBlockOfs.z)*fBlockSize - renderBlockOfs_remain.z; Matrix4 mWorldViewProj; mWorldViewProj = vWorldMatrix * matViewProj; pEffect->setMatrix(CEffectFile::k_worldViewProjMatrix, &mWorldViewProj); if (pEffect->isMatrixUsed(CEffectFile::k_worldViewMatrix)) { Matrix4 mWorldView; ParaMatrixMultiply(&mWorldView, &vWorldMatrix, &matViewProj); pEffect->setMatrix(CEffectFile::k_worldViewMatrix, &mWorldView); } if (CGlobals::GetEffectManager()->IsUsingShadowMap() && pEffect->isMatrixUsed(CEffectFile::k_TexWorldViewProjMatrix)) { Matrix4 mTex; ParaMatrixMultiply(&mTex, &vWorldMatrix, CGlobals::GetEffectManager()->GetTexViewProjMatrix()); pEffect->setMatrix(CEffectFile::k_TexWorldViewProjMatrix, &mTex); } { // set the new render origin Vector4 vWorldPos(0, 0, 0, 1.f); /** this is for height shift, using the render origin. */ Vector3 vRenderOrigin = CGlobals::GetScene()->GetRenderOrigin(); vWorldPos.x = vRenderOrigin.x + vWorldMatrix._41; vWorldPos.y = vRenderOrigin.y + vWorldMatrix._42; vWorldPos.z = vRenderOrigin.z + vWorldMatrix._43; pEffect->setParameter(CEffectFile::k_worldPos, &vWorldPos); } pEffect->CommitChanges(); RenderDevice::DrawIndexedPrimitive(pDevice, D3DPT_TRIANGLELIST, D3DPT_TRIANGLELIST, 0, pRenderTask->GetVertexOfs(), pRenderTask->GetVertexCount(), pRenderTask->GetIndexOfs(), pRenderTask->GetPrimitiveCount()); } if (curPass > -1) pEffect->EndPass(); pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); if (dwRenderMethod == BLOCK_RENDER_FANCY_SHADER) { // disable render target again } pEffect->end(); if (pCurVB != 0) { // unbind buffer if any, this fixed a crash bug with OpenGL multi-frame renderer // where the same stream source is used both in multi-frame renderer and main renderer. pDevice->SetStreamSource(0, 0, 0, 0); } } if (nRenderPass != BlockRenderPass_AlphaBlended) { if (nRenderPass == BlockRenderPass_AlphaTest) pDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR); // turn blending on again pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); } } if (nRenderPass == BlockRenderPass_AlphaBlended) { if (dwRenderMethod != BLOCK_RENDER_FANCY_SHADER) { RenderDynamicBlocks(); } } } void BlockWorldClient::RenderWireFrameBlock(int nSelectionIndex, float fScaling, LinearColor* pLineColor) { auto& selectedBlocks = m_selectedBlockMap[nSelectionIndex]; auto& selectedBlockMap = selectedBlocks.m_blocks; if (selectedBlockMap.size() == 0) return; SceneState* sceneState = CGlobals::GetSceneState(); IBatchedElementDraw* pBatchedElementDraw = sceneState->GetBatchedElementDrawer(); if (pBatchedElementDraw == 0) return; Vector3 pVecBounds[8]; int nNumVertices; const float fBlockSize = BlockConfig::g_blockSize; Vector3 renderOfs = CGlobals::GetScene()->GetRenderOrigin(); float verticalOffset = GetVerticalOffset(); int32_t renderBlockOfs_x = (int32_t)(renderOfs.x / fBlockSize); int32_t renderBlockOfs_y = (int32_t)(renderOfs.y / fBlockSize); int32_t renderBlockOfs_z = (int32_t)(renderOfs.z / fBlockSize); Vector3 renderBlockOfs_remain; renderBlockOfs_remain.x = renderOfs.x - renderBlockOfs_x * fBlockSize; renderBlockOfs_remain.y = renderOfs.y - renderBlockOfs_y * fBlockSize; renderBlockOfs_remain.z = renderOfs.z - renderBlockOfs_z * fBlockSize; // scale the block a little to avoid z fighting. float fScaledBlockSize = BlockConfig::g_blockSize*fScaling; if (pBatchedElementDraw) { PARAVECTOR4 color(0.2f, 0.2f, 0.2f, 0.7f); if (pLineColor) { color = *((PARAVECTOR4*)pLineColor); } const float fLineWidth = -2.f; std::map<int64_t, Uint16x3>::iterator itCur, itEnd = selectedBlockMap.end(); for (itCur = selectedBlockMap.begin(); itCur != itEnd; itCur++) { Uint16x3& BlockPos = (*itCur).second; uint16_t x, y, z; x = BlockPos.x; y = BlockPos.y; z = BlockPos.z; BlockTemplate* pBlockTemplate = GetBlockTemplate(x, y, z); if (pBlockTemplate == 0) pBlockTemplate = GetBlockTemplate(1); if (pBlockTemplate) { int nLenCount = 12; CShapeAABB aabb; pBlockTemplate->GetAABB(this, x, y, z, &aabb); Vector3 vOffset((x - renderBlockOfs_x) * fBlockSize, (y - renderBlockOfs_y) * fBlockSize + verticalOffset, (z - renderBlockOfs_z) * fBlockSize); vOffset -= renderBlockOfs_remain; aabb.GetCenter() += vOffset; aabb.GetExtents() *= fScaling; BlockModel::GetBoundingBoxVertices(aabb, pVecBounds, &nNumVertices); { static const int pIndexBuffer[] = { 0,1,2,3,0, // bottom 4,5,6,7,4, // top 5,1,6,2,3,7, // sides }; Vector3 pVertexList[16]; for (int i = 0; i < 16; i++) { pVertexList[i] = pVecBounds[pIndexBuffer[i]]; } pBatchedElementDraw->AddThickLines((PARAVECTOR3*)pVertexList, 10, color, fLineWidth); pBatchedElementDraw->AddThickLines((PARAVECTOR3*)pVertexList + 10, 2, color, fLineWidth); pBatchedElementDraw->AddThickLines((PARAVECTOR3*)pVertexList + 12, 2, color, fLineWidth); pBatchedElementDraw->AddThickLines((PARAVECTOR3*)pVertexList + 14, 2, color, fLineWidth); } } } } } void BlockWorldClient::RenderSelectionBlock(int nSelectionIndex, float fScaledBlockSize, LinearColor* pColor, BOOL bColorAnimate) { auto& selectedBlocks = m_selectedBlockMap[nSelectionIndex]; auto& selectedBlockMap = selectedBlocks.m_blocks; auto& highLightTexture = m_highLightTextures[nSelectionIndex]; if (selectedBlockMap.size() == 0) return; if ((int)m_selectBlockInstData.size() < m_maxSelectBlockPerBatch * 4) m_selectBlockInstData.resize(m_maxSelectBlockPerBatch * 4); RenderDevicePtr pDevice = CGlobals::GetRenderDevice(); float blockSize = BlockConfig::g_blockSize; if (!highLightTexture) { return; } else if (!highLightTexture->IsLoaded()) { highLightTexture->LoadAsset(); return; } BuildSelectionBlockBuffer(); const float fBlockSize = BlockConfig::g_blockSize; Vector3 renderOfs = CGlobals::GetScene()->GetRenderOrigin(); float verticalOffset = GetVerticalOffset(); int32_t renderBlockOfs_x = (int32_t)(renderOfs.x / fBlockSize); int32_t renderBlockOfs_y = (int32_t)(renderOfs.y / fBlockSize); int32_t renderBlockOfs_z = (int32_t)(renderOfs.z / fBlockSize); Vector3 renderBlockOfs_remain; renderBlockOfs_remain.x = renderOfs.x - renderBlockOfs_x * fBlockSize; renderBlockOfs_remain.y = renderOfs.y - renderBlockOfs_y * fBlockSize; renderBlockOfs_remain.z = renderOfs.z - renderBlockOfs_z * fBlockSize; // scale the block a little to avoid z fighting. fScaledBlockSize = BlockConfig::g_blockSize*fScaledBlockSize; int32_t count = (int32)selectedBlockMap.size(); int32_t curInstCount = 0; int32_t instFloatCount = 0; EffectManager* pEffectManager = CGlobals::GetEffectManager(); pEffectManager->BeginEffect(TECH_BLOCK); CEffectFile* pEffect = pEffectManager->GetCurrentEffectFile(); pDevice->SetStreamSource(0, 0, 0, 0); pDevice->SetIndices(0); // culling mode if (selectedBlocks.m_bOnlyRenderClickableArea) { pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); } else { pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); } if (pEffect == 0) { #ifdef USE_DIRECTX_RENDERER // fixed function pipeline pDevice->SetTexture(0, highLightTexture->GetTexture()); pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE); pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE); pDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); pDevice->SetFVF(mesh_vertex_plain::FVF); uint32_t time = CGlobals::GetSceneState()->GetGlobalTime(); uint8 lightScaler = (bColorAnimate) ? (uint8)(abs(sin(time*0.0015f)) * 0.4f * 255) : 0xff; DWORD lightIntensity = COLOR_ARGB(255, lightScaler, lightScaler, lightScaler); pDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CONSTANT); pDevice->SetTextureStageState(0, D3DTSS_CONSTANT, lightIntensity); Matrix4 vWorldMatrix(Matrix4::IDENTITY); vWorldMatrix._41 = -renderBlockOfs_remain.x - (fScaledBlockSize - fBlockSize)*0.5f; vWorldMatrix._42 = -renderBlockOfs_remain.y - (fScaledBlockSize - fBlockSize)*0.5f; vWorldMatrix._43 = -renderBlockOfs_remain.z - (fScaledBlockSize - fBlockSize)*0.5f; pDevice->SetTransform(D3DTS_WORLD, vWorldMatrix.GetPointer()); int nMaxFaceCount = (m_maxSelectBlockPerBatch - 1) * 6; std::map<int64_t, Uint16x3>::iterator itCur, itEnd = selectedBlockMap.end(); for (itCur = selectedBlockMap.begin(); itCur != itEnd; itCur++) { Uint16x3& BlockPos = (*itCur).second; uint16_t x, y, z; x = BlockPos.x; y = BlockPos.y; z = BlockPos.z; if (curInstCount >= nMaxFaceCount) { RenderDevice::DrawIndexedPrimitiveUP(pDevice, RenderDevice::DRAW_PERF_TRIANGLES_TERRAIN, D3DPT_TRIANGLELIST, 0, curInstCount * 4, curInstCount * 2, &(m_select_block_indices[0]), D3DFMT_INDEX16, &(m_select_block_vertices[0]), sizeof(SelectBlockVertex)); curInstCount = 0; instFloatCount = 0; } Vector3 vOffset((x - renderBlockOfs_x) * fBlockSize, (y - renderBlockOfs_y) * fBlockSize + verticalOffset, (z - renderBlockOfs_z) * fBlockSize); int nCount = 0; if (selectedBlocks.m_bOnlyRenderClickableArea) nCount = FillSelectBlockInvert(selectedBlockMap, x, y, z, &(m_select_block_vertices[instFloatCount * 4]), vOffset, fScaledBlockSize); else nCount = FillSelectBlockVertice(&selectedBlockMap, x, y, z, &(m_select_block_vertices[instFloatCount * 4]), vOffset, fScaledBlockSize); instFloatCount += nCount; curInstCount += nCount; } if (curInstCount > 0) { RenderDevice::DrawIndexedPrimitiveUP(pDevice, RenderDevice::DRAW_PERF_TRIANGLES_TERRAIN, D3DPT_TRIANGLELIST, 0, curInstCount * 4, curInstCount * 2, &(m_select_block_indices[0]), D3DFMT_INDEX16, &(m_select_block_vertices[0]), sizeof(SelectBlockVertex)); } pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE); pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); pDevice->SetRenderState(D3DRS_DEPTHBIAS, 0); pDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_CURRENT); #endif } else if (pEffect != 0 && pEffect->begin(false)) { pDevice->SetVertexDeclaration(GetSelectBlockVertexLayout()); if (pEffect->BeginPass(g_selectBlockPass)) { IScene* pScene = CGlobals::GetEffectManager()->GetScene(); CBaseCamera* pCamera = pScene->GetCurrentCamera(); Matrix4 matViewProj; if (pCamera) { const Matrix4& pView = (CGlobals::GetEffectManager()->GetViewTransform()); const Matrix4& pProj = (CGlobals::GetEffectManager()->GetProjTransform()); matViewProj = (pView) * (pProj); } pDevice->SetTexture(0, highLightTexture->GetTexture()); pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ONE); pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE); pDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); uint32_t time = CGlobals::GetSceneState()->GetGlobalTime(); float lightIntensity = 1.f; if (bColorAnimate) lightIntensity = abs(sin(time*0.0015f)) * 0.4f; Vector4 vLightParams(lightIntensity, 0, 0, 0); pEffect->setParameter(CEffectFile::k_ConstVector0, (const void*)(&vLightParams)); Matrix4 vWorldMatrix(Matrix4::IDENTITY); vWorldMatrix._41 = -renderBlockOfs_remain.x - (fScaledBlockSize - fBlockSize)*0.5f; vWorldMatrix._42 = -renderBlockOfs_remain.y - (fScaledBlockSize - fBlockSize)*0.5f; vWorldMatrix._43 = -renderBlockOfs_remain.z - (fScaledBlockSize - fBlockSize)*0.5f; vWorldMatrix = vWorldMatrix * matViewProj; pEffect->setMatrix(CEffectFile::k_worldViewProjMatrix, &vWorldMatrix); pEffect->CommitChanges(); int nMaxFaceCount = (m_maxSelectBlockPerBatch - 1) * 6; std::map<int64_t, Uint16x3>::iterator itCur, itEnd = selectedBlockMap.end(); for (itCur = selectedBlockMap.begin(); itCur != itEnd; itCur++) { Uint16x3& BlockPos = (*itCur).second; uint16_t x, y, z; x = BlockPos.x; y = BlockPos.y; z = BlockPos.z; if (curInstCount >= nMaxFaceCount) { RenderDevice::DrawIndexedPrimitiveUP(pDevice, D3DPT_TRIANGLELIST, D3DPT_TRIANGLELIST, 0, curInstCount * 4, curInstCount * 2, &(m_select_block_indices[0]), D3DFMT_INDEX16, &(m_select_block_vertices[0]), sizeof(SelectBlockVertex)); curInstCount = 0; instFloatCount = 0; } Vector3 vOffset((x - renderBlockOfs_x) * fBlockSize, (y - renderBlockOfs_y) * fBlockSize + verticalOffset, (z - renderBlockOfs_z) * fBlockSize); int nCount = 0; if (selectedBlocks.m_bOnlyRenderClickableArea) nCount = FillSelectBlockInvert(selectedBlockMap, x, y, z, &(m_select_block_vertices[instFloatCount * 4]), vOffset, fScaledBlockSize); else nCount = FillSelectBlockVertice(&selectedBlockMap, x, y, z, &(m_select_block_vertices[instFloatCount * 4]), vOffset, fScaledBlockSize); instFloatCount += nCount; curInstCount += nCount; } if (curInstCount > 0) { RenderDevice::DrawIndexedPrimitiveUP(pDevice, D3DPT_TRIANGLELIST, D3DPT_TRIANGLELIST, 0, curInstCount * 4, curInstCount * 2, &(m_select_block_indices[0]), D3DFMT_INDEX16, &(m_select_block_vertices[0]), sizeof(SelectBlockVertex)); } pEffect->EndPass(); pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); pDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA); pDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA); pDevice->SetRenderState(D3DRS_DEPTHBIAS, 0); } pEffect->end(); } pDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW); } void BlockWorldClient::RenderDamagedBlock() { if (m_damageDegree <= 0) return; #ifdef USE_DIRECTX_RENDERER RenderDevicePtr pDevice = CGlobals::GetRenderDevice(); float blockSize = BlockConfig::g_blockSize; if (!m_damangeTexture) { return; } else if (!m_damangeTexture->IsLoaded()) { m_damangeTexture->LoadAsset(); return; } //----------------------------------------- BuildSelectionBlockBuffer(); const float fBlockSize = BlockConfig::g_blockSize; Vector3 renderOfs = CGlobals::GetScene()->GetRenderOrigin(); float verticalOffset = GetVerticalOffset(); int32_t renderBlockOfs_x = (int32_t)(renderOfs.x / fBlockSize); int32_t renderBlockOfs_y = (int32_t)(renderOfs.y / fBlockSize); int32_t renderBlockOfs_z = (int32_t)(renderOfs.z / fBlockSize); Vector3 renderBlockOfs_remain; renderBlockOfs_remain.x = renderOfs.x - renderBlockOfs_x * fBlockSize; renderBlockOfs_remain.y = renderOfs.y - renderBlockOfs_y * fBlockSize; renderBlockOfs_remain.z = renderOfs.z - renderBlockOfs_z * fBlockSize; // scale the block a little to avoid z fighting. float fScaledBlockSize = BlockConfig::g_blockSize*1.02f; //----------------------------------------- EffectManager* pEffectManager = CGlobals::GetEffectManager(); pEffectManager->BeginEffect(TECH_BLOCK); CEffectFile* pEffect = pEffectManager->GetCurrentEffectFile(); if (pEffect == 0) { // fixed function pipeline pDevice->SetTexture(0, m_damangeTexture->GetTexture()); pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE); pDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); pDevice->SetFVF(mesh_vertex_plain::FVF); Matrix4 vWorldMatrix(Matrix4::IDENTITY); vWorldMatrix._41 = -renderBlockOfs_remain.x - (fScaledBlockSize - fBlockSize)*0.5f; vWorldMatrix._42 = -renderBlockOfs_remain.y - (fScaledBlockSize - fBlockSize)*0.5f; vWorldMatrix._43 = -renderBlockOfs_remain.z - (fScaledBlockSize - fBlockSize)*0.5f; pDevice->SetTransform(D3DTS_WORLD, vWorldMatrix.GetPointer()); int curInstCount = 0; int instFloatCount = 0; { Vector3 vOffset((m_damagedBlockId.x - renderBlockOfs_x) * fBlockSize, (m_damagedBlockId.y - renderBlockOfs_y) * fBlockSize + verticalOffset, (m_damagedBlockId.z - renderBlockOfs_z) * fBlockSize); FillSelectBlockVertice(NULL, 0, 0, 0, &(m_select_block_vertices[instFloatCount * 24]), vOffset, fScaledBlockSize, ((int)(max(m_damageDegree - 0.1f, 0.f) * 8)) / 8.f, 1 / 8.f); instFloatCount++; curInstCount++; } RenderDevice::DrawIndexedPrimitiveUP(pDevice, RenderDevice::DRAW_PERF_TRIANGLES_TERRAIN, D3DPT_TRIANGLELIST, 0, curInstCount * 24, curInstCount * 12, &(m_select_block_indices[0]), D3DFMT_INDEX16, &(m_select_block_vertices[0]), sizeof(SelectBlockVertex)); pDevice->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE); pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); } else if (pEffect != 0 && pEffect->begin(false)) { pDevice->SetVertexDeclaration(GetSelectBlockVertexLayout()); if (pEffect->BeginPass(2)) { IScene* pScene = CGlobals::GetEffectManager()->GetScene(); CBaseCamera* pCamera = pScene->GetCurrentCamera(); Matrix4 matViewProj; if (pCamera) { const Matrix4& pView = (CGlobals::GetEffectManager()->GetViewTransform()); const Matrix4& pProj = (CGlobals::GetEffectManager()->GetProjTransform()); matViewProj = (pView) * (pProj); } pDevice->SetTexture(0, m_damangeTexture->GetTexture()); pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); pDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE); Matrix4 vWorldMatrix(Matrix4::IDENTITY); vWorldMatrix._41 = -renderBlockOfs_remain.x - (fScaledBlockSize - fBlockSize)*0.5f; vWorldMatrix._42 = -renderBlockOfs_remain.y - (fScaledBlockSize - fBlockSize)*0.5f; vWorldMatrix._43 = -renderBlockOfs_remain.z - (fScaledBlockSize - fBlockSize)*0.5f; vWorldMatrix = vWorldMatrix * matViewProj; pEffect->setMatrix(CEffectFile::k_worldViewProjMatrix, &vWorldMatrix); pEffect->CommitChanges(); int curInstCount = 0; int instFloatCount = 0; { Vector3 vOffset((m_damagedBlockId.x - renderBlockOfs_x) * fBlockSize, (m_damagedBlockId.y - renderBlockOfs_y) * fBlockSize + verticalOffset, (m_damagedBlockId.z - renderBlockOfs_z) * fBlockSize); // animate the UV's y offset according to m_damageDegree FillSelectBlockVertice(NULL, 0, 0, 0, &(m_select_block_vertices[instFloatCount * 24]), vOffset, fScaledBlockSize, ((int)(max(m_damageDegree - 0.1f, 0.f) * 8)) / 8.f, 1 / 8.f); instFloatCount++; curInstCount++; } RenderDevice::DrawIndexedPrimitiveUP(pDevice, D3DPT_TRIANGLELIST, D3DPT_TRIANGLELIST, 0, curInstCount * 24, curInstCount * 12, &(m_select_block_indices[0]), D3DFMT_INDEX16, &(m_select_block_vertices[0]), sizeof(SelectBlockVertex)); pEffect->EndPass(); pDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE); pDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); } pEffect->end(); } #endif } int BlockWorldClient::FillSelectBlockInvert(std::map<int64_t, Uint16x3>& selectedBlockMap, uint16_t x, uint16_t y, uint16_t z, SelectBlockVertex* blockModel, const Vector3& vOffset, const float blockSize, float fUV_Y_Offset /*= 0.f*/, float fUV_Y_Size/*=1.f*/) { int nCount = 0; if (GetBlockTemplateIdByIdx(x, y + 1, z) != 0) { //top face blockModel[0].position.x = vOffset.x; blockModel[0].position.y = vOffset.y + blockSize; blockModel[0].position.z = vOffset.z; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x; blockModel[1].position.y = vOffset.y + blockSize; blockModel[1].position.z = vOffset.z + blockSize; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x + blockSize; blockModel[2].position.y = vOffset.y + blockSize; blockModel[2].position.z = vOffset.z + blockSize; blockModel[2].texcoord = Vector2(1, fUV_Y_Offset); blockModel[3].position.x = vOffset.x + blockSize; blockModel[3].position.y = vOffset.y + blockSize; blockModel[3].position.z = vOffset.z; blockModel[3].texcoord = Vector2(1, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } if (GetBlockTemplateIdByIdx(x, y, z - 1) != 0) { //front face blockModel[0].position.x = vOffset.x; blockModel[0].position.y = vOffset.y; blockModel[0].position.z = vOffset.z; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x; blockModel[1].position.y = vOffset.y + blockSize; blockModel[1].position.z = vOffset.z; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x + blockSize; blockModel[2].position.y = vOffset.y + blockSize; blockModel[2].position.z = vOffset.z; blockModel[2].texcoord = Vector2(1.f, fUV_Y_Offset); blockModel[3].position.x = vOffset.x + blockSize; blockModel[3].position.y = vOffset.y; blockModel[3].position.z = vOffset.z; blockModel[3].texcoord = Vector2(1.f, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } if (GetBlockTemplateIdByIdx(x, y - 1, z) != 0) { //bottom face blockModel[0].position.x = vOffset.x; blockModel[0].position.y = vOffset.y; blockModel[0].position.z = vOffset.z + blockSize; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x; blockModel[1].position.y = vOffset.y; blockModel[1].position.z = vOffset.z; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x + blockSize; blockModel[2].position.y = vOffset.y; blockModel[2].position.z = vOffset.z; blockModel[2].texcoord = Vector2(1.f, fUV_Y_Offset); blockModel[3].position.x = vOffset.x + blockSize; blockModel[3].position.y = vOffset.y; blockModel[3].position.z = vOffset.z + blockSize; blockModel[3].texcoord = Vector2(1.f, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } if (GetBlockTemplateIdByIdx(x - 1, y, z) != 0) { //left face blockModel[0].position.x = vOffset.x; blockModel[0].position.y = vOffset.y; blockModel[0].position.z = vOffset.z + blockSize; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x; blockModel[1].position.y = vOffset.y + blockSize; blockModel[1].position.z = vOffset.z + blockSize; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x; blockModel[2].position.y = vOffset.y + blockSize; blockModel[2].position.z = vOffset.z; blockModel[2].texcoord = Vector2(1.f, fUV_Y_Offset); blockModel[3].position.x = vOffset.x; blockModel[3].position.y = vOffset.y; blockModel[3].position.z = vOffset.z; blockModel[3].texcoord = Vector2(1.f, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } if (GetBlockTemplateIdByIdx(x + 1, y, z) != 0) { //right blockModel[0].position.x = vOffset.x + blockSize; blockModel[0].position.y = vOffset.y; blockModel[0].position.z = vOffset.z; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x + blockSize; blockModel[1].position.y = vOffset.y + blockSize; blockModel[1].position.z = vOffset.z; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x + blockSize; blockModel[2].position.y = vOffset.y + blockSize; blockModel[2].position.z = vOffset.z + blockSize; blockModel[2].texcoord = Vector2(1.f, fUV_Y_Offset); blockModel[3].position.x = vOffset.x + blockSize; blockModel[3].position.y = vOffset.y; blockModel[3].position.z = vOffset.z + blockSize; blockModel[3].texcoord = Vector2(1.f, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } if (GetBlockTemplateIdByIdx(x, y, z + 1) != 0) { //back face blockModel[0].position.x = vOffset.x + blockSize; blockModel[0].position.y = vOffset.y; blockModel[0].position.z = vOffset.z + blockSize; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x + blockSize; blockModel[1].position.y = vOffset.y + blockSize; blockModel[1].position.z = vOffset.z + blockSize; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x; blockModel[2].position.y = vOffset.y + blockSize; blockModel[2].position.z = vOffset.z + blockSize; blockModel[2].texcoord = Vector2(1.f, fUV_Y_Offset); blockModel[3].position.x = vOffset.x; blockModel[3].position.y = vOffset.y; blockModel[3].position.z = vOffset.z + blockSize; blockModel[3].texcoord = Vector2(1.f, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } if (nCount == 0) { nCount = FillSelectBlockVertice(&selectedBlockMap, x, y, z, blockModel, vOffset, blockSize, fUV_Y_Offset, fUV_Y_Size); } return nCount; } int BlockWorldClient::FillSelectBlockVertice(std::map<int64_t, Uint16x3>* pSelectedBlockMap, uint16_t x, uint16_t y, uint16_t z, SelectBlockVertex* blockModel, const Vector3& vOffset, const float blockSize, float fUV_Y_Offset, float fUV_Y_Size) { int nCount = 0; if (!pSelectedBlockMap || pSelectedBlockMap->find(GetBlockSparseIndex(x, y + 1, z)) == pSelectedBlockMap->end()) { //top face blockModel[0].position.x = vOffset.x; blockModel[0].position.y = vOffset.y + blockSize; blockModel[0].position.z = vOffset.z; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x; blockModel[1].position.y = vOffset.y + blockSize; blockModel[1].position.z = vOffset.z + blockSize; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x + blockSize; blockModel[2].position.y = vOffset.y + blockSize; blockModel[2].position.z = vOffset.z + blockSize; blockModel[2].texcoord = Vector2(1.f, fUV_Y_Offset); blockModel[3].position.x = vOffset.x + blockSize; blockModel[3].position.y = vOffset.y + blockSize; blockModel[3].position.z = vOffset.z; blockModel[3].texcoord = Vector2(1.f, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } if (!pSelectedBlockMap || pSelectedBlockMap->find(GetBlockSparseIndex(x, y, z - 1)) == pSelectedBlockMap->end()) { //front face blockModel[0].position.x = vOffset.x; blockModel[0].position.y = vOffset.y; blockModel[0].position.z = vOffset.z; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x; blockModel[1].position.y = vOffset.y + blockSize; blockModel[1].position.z = vOffset.z; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x + blockSize; blockModel[2].position.y = vOffset.y + blockSize; blockModel[2].position.z = vOffset.z; blockModel[2].texcoord = Vector2(1.f, fUV_Y_Offset); blockModel[3].position.x = vOffset.x + blockSize; blockModel[3].position.y = vOffset.y; blockModel[3].position.z = vOffset.z; blockModel[3].texcoord = Vector2(1.f, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } if (!pSelectedBlockMap || pSelectedBlockMap->find(GetBlockSparseIndex(x, y - 1, z)) == pSelectedBlockMap->end()) { //bottom face blockModel[0].position.x = vOffset.x; blockModel[0].position.y = vOffset.y; blockModel[0].position.z = vOffset.z + blockSize; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x; blockModel[1].position.y = vOffset.y; blockModel[1].position.z = vOffset.z; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x + blockSize; blockModel[2].position.y = vOffset.y; blockModel[2].position.z = vOffset.z; blockModel[2].texcoord = Vector2(1.f, fUV_Y_Offset); blockModel[3].position.x = vOffset.x + blockSize; blockModel[3].position.y = vOffset.y; blockModel[3].position.z = vOffset.z + blockSize; blockModel[3].texcoord = Vector2(1.f, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } if (!pSelectedBlockMap || pSelectedBlockMap->find(GetBlockSparseIndex(x - 1, y, z)) == pSelectedBlockMap->end()) { //left face blockModel[0].position.x = vOffset.x; blockModel[0].position.y = vOffset.y; blockModel[0].position.z = vOffset.z + blockSize; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x; blockModel[1].position.y = vOffset.y + blockSize; blockModel[1].position.z = vOffset.z + blockSize; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x; blockModel[2].position.y = vOffset.y + blockSize; blockModel[2].position.z = vOffset.z; blockModel[2].texcoord = Vector2(1.f, fUV_Y_Offset); blockModel[3].position.x = vOffset.x; blockModel[3].position.y = vOffset.y; blockModel[3].position.z = vOffset.z; blockModel[3].texcoord = Vector2(1.f, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } if (!pSelectedBlockMap || pSelectedBlockMap->find(GetBlockSparseIndex(x + 1, y, z)) == pSelectedBlockMap->end()) { //right blockModel[0].position.x = vOffset.x + blockSize; blockModel[0].position.y = vOffset.y; blockModel[0].position.z = vOffset.z; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x + blockSize; blockModel[1].position.y = vOffset.y + blockSize; blockModel[1].position.z = vOffset.z; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x + blockSize; blockModel[2].position.y = vOffset.y + blockSize; blockModel[2].position.z = vOffset.z + blockSize; blockModel[2].texcoord = Vector2(1.f, fUV_Y_Offset); blockModel[3].position.x = vOffset.x + blockSize; blockModel[3].position.y = vOffset.y; blockModel[3].position.z = vOffset.z + blockSize; blockModel[3].texcoord = Vector2(1.f, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } if (!pSelectedBlockMap || pSelectedBlockMap->find(GetBlockSparseIndex(x, y, z + 1)) == pSelectedBlockMap->end()) { //back face blockModel[0].position.x = vOffset.x + blockSize; blockModel[0].position.y = vOffset.y; blockModel[0].position.z = vOffset.z + blockSize; blockModel[0].texcoord = Vector2(0, fUV_Y_Offset + fUV_Y_Size); blockModel[1].position.x = vOffset.x + blockSize; blockModel[1].position.y = vOffset.y + blockSize; blockModel[1].position.z = vOffset.z + blockSize; blockModel[1].texcoord = Vector2(0, fUV_Y_Offset); blockModel[2].position.x = vOffset.x; blockModel[2].position.y = vOffset.y + blockSize; blockModel[2].position.z = vOffset.z + blockSize; blockModel[2].texcoord = Vector2(1.f, fUV_Y_Offset); blockModel[3].position.x = vOffset.x; blockModel[3].position.y = vOffset.y; blockModel[3].position.z = vOffset.z + blockSize; blockModel[3].texcoord = Vector2(1.f, fUV_Y_Offset + fUV_Y_Size); blockModel += 4; nCount++; } return nCount; } void BlockWorldClient::BuildSelectionBlockBuffer() { if (m_select_block_vertices.empty()) { float blockSize = BlockConfig::g_blockSize; SelectBlockVertex blockModel[24]; Vector3 vOffset(0, 0, 0); FillSelectBlockVertice(NULL, 0, 0, 0, blockModel, vOffset, BlockConfig::g_blockSize); m_select_block_vertices.resize(24 * m_maxSelectBlockPerBatch); SelectBlockVertex* pVertices = &(m_select_block_vertices[0]); for (int i = 0; i < m_maxSelectBlockPerBatch; i++) { memcpy(pVertices, blockModel, sizeof(SelectBlockVertex) * 24); pVertices += 24; } } if (m_select_block_indices.empty()) { m_select_block_indices.resize(36 * m_maxSelectBlockPerBatch); uint16_t* pIndices = &(m_select_block_indices[0]); for (int i = 0; i < m_maxSelectBlockPerBatch; i++) { uint16_t indexOfs = 24 * i; //top face *pIndices = indexOfs + 0; pIndices++; *pIndices = indexOfs + 1; pIndices++; *pIndices = indexOfs + 3; pIndices++; *pIndices = indexOfs + 1; pIndices++; *pIndices = indexOfs + 2; pIndices++; *pIndices = indexOfs + 3; pIndices++; //front face *pIndices = indexOfs + 4; pIndices++; *pIndices = indexOfs + 5; pIndices++; *pIndices = indexOfs + 7; pIndices++; *pIndices = indexOfs + 5; pIndices++; *pIndices = indexOfs + 6; pIndices++; *pIndices = indexOfs + 7; pIndices++; //bottom face *pIndices = indexOfs + 8; pIndices++; *pIndices = indexOfs + 9; pIndices++; *pIndices = indexOfs + 11; pIndices++; *pIndices = indexOfs + 9; pIndices++; *pIndices = indexOfs + 10; pIndices++; *pIndices = indexOfs + 11; pIndices++; //left face *pIndices = indexOfs + 12; pIndices++; *pIndices = indexOfs + 13; pIndices++; *pIndices = indexOfs + 15; pIndices++; *pIndices = indexOfs + 13; pIndices++; *pIndices = indexOfs + 14; pIndices++; *pIndices = indexOfs + 15; pIndices++; //right face *pIndices = indexOfs + 16; pIndices++; *pIndices = indexOfs + 17; pIndices++; *pIndices = indexOfs + 19; pIndices++; *pIndices = indexOfs + 17; pIndices++; *pIndices = indexOfs + 18; pIndices++; *pIndices = indexOfs + 19; pIndices++; //back face *pIndices = indexOfs + 20; pIndices++; *pIndices = indexOfs + 21; pIndices++; *pIndices = indexOfs + 23; pIndices++; *pIndices = indexOfs + 21; pIndices++; *pIndices = indexOfs + 22; pIndices++; *pIndices = indexOfs + 23; pIndices++; } } } void BlockWorldClient::AddRenderTask(BlockRenderTask* pRenderTask) { GetRenderQueueByPass(pRenderTask->GetTemplate()->GetRenderPass())->push_back(pRenderTask); } IndexBufferDevicePtr_type BlockWorldClient::GetIndexBuffer() { if (!m_sharedIndexBuffer.IsValid()) { // at most 6 indices per face (2 triangles) const int face_count = BlockConfig::g_maxFaceCountPerBatch; int32_t bufferSize = sizeof(uint16_t) * 6 * face_count; // D3DFMT_INDEX16 boundary check PE_ASSERT((face_count * 4) <= 0xffff); m_sharedIndexBuffer.CreateBuffer(bufferSize, D3DFMT_INDEX16, 0); uint16_t* pIndices; if (m_sharedIndexBuffer.Lock((void**)&pIndices, 0, 0)) { for (int i = 0; i < face_count; i++) { uint16_t indexOfs = 4 * i; *pIndices = indexOfs + 0; pIndices++; *pIndices = indexOfs + 1; pIndices++; *pIndices = indexOfs + 3; pIndices++; *pIndices = indexOfs + 1; pIndices++; *pIndices = indexOfs + 2; pIndices++; *pIndices = indexOfs + 3; pIndices++; } m_sharedIndexBuffer.Unlock(); } } return m_sharedIndexBuffer.GetDevicePointer(); } VertexDeclarationPtr BlockWorldClient::GetVertexLayout() { return CGlobals::GetEffectManager()->GetVertexDeclaration(EffectManager::S0_POS_NORM_TEX0_COLOR0_COLOR1); } VertexDeclarationPtr BlockWorldClient::GetSelectBlockVertexLayout() { return CGlobals::GetEffectManager()->GetVertexDeclaration(EffectManager::S0_POS_TEX0); } void BlockWorldClient::DeleteDeviceObjects() { m_sharedIndexBuffer.ReleaseBuffer(); for (uint32_t i = 0; i < m_activeChunks.size(); i++) m_activeChunks[i]->DeleteDeviceObjects(); m_pMultiFrameRenderer->DeleteDeviceObjects(); m_alphaTestRenderTasks.clear(); m_solidRenderTasks.clear(); m_alphaBlendRenderTasks.clear(); m_reflectedWaterRenderTasks.clear(); } void BlockWorldClient::RendererRecreated() { m_sharedIndexBuffer.RendererRecreated(); for (uint32_t i = 0; i < m_activeChunks.size(); i++) m_activeChunks[i]->RendererRecreated(); m_pMultiFrameRenderer->RendererRecreated(); m_alphaTestRenderTasks.clear(); m_solidRenderTasks.clear(); m_alphaBlendRenderTasks.clear(); m_reflectedWaterRenderTasks.clear(); if (IsInBlockWorld()) UpdateAllActiveChunks(); } void BlockWorldClient::SetDamagedBlock(uint16_t x, uint16_t y, uint16_t z) { m_damagedBlockId.x = x; m_damagedBlockId.y = y; m_damagedBlockId.z = z; } void BlockWorldClient::SetDamagedBlockDegree(float degree) { m_damageDegree = degree; } void BlockWorldClient::SetSelectionTexture(const char* textureName) { if (textureName) { char c = textureName[0]; int nIndex = 0; if (textureName[1] == ':' && c >= '0' && c <= '9') { nIndex = c - '0'; textureName += 2; } if (nIndex < BLOCK_GROUP_ID_MAX) { if (m_highLightTextures[nIndex]) { if (m_highLightTextures[nIndex]->GetKey() == textureName) { return; } } m_highLightTextures[nIndex] = CGlobals::GetAssetManager()->LoadTexture("", textureName, TextureEntity::StaticTexture); } } } std::string BlockWorldClient::GetSelectionTexture() { if (m_highLightTextures[0]) { return (m_highLightTextures[0]->GetKey()); } return ""; } void BlockWorldClient::SetDamageTexture(const char* textureName) { if (m_damangeTexture) { if (m_damangeTexture->GetKey() == textureName) { return; } } m_damangeTexture = CGlobals::GetAssetManager()->LoadTexture("", textureName, TextureEntity::StaticTexture); } std::string BlockWorldClient::GetDamageTexture() { if (m_damangeTexture) { return (m_damangeTexture->GetKey()); } return ""; } bool BlockWorldClient::IsPointUnderWater(const Vector3& vPos) { if (IsInBlockWorld()) { // first check block world and then check real world uint16_t block_id = GetBlockTemplateId(vPos.x, vPos.y, vPos.z); if (block_id > 0) { BlockTemplate* pBlockTemplate = GetBlockTemplate(block_id); if (pBlockTemplate != 0 && pBlockTemplate->IsMatchAttribute(BlockTemplate::batt_liquid)) { return true; } } #ifdef USE_DIRECTX_RENDERER return CGlobals::GetOceanManager()->IsPointUnderWater(vPos); #else return false; #endif } else { #ifdef USE_DIRECTX_RENDERER return CGlobals::GetOceanManager()->IsPointUnderWater(vPos); #else return false; #endif } } float BlockWorldClient::GetWaterLevel(float x, float y, float z, int nRayLength) { float fWaterLevel = -1000.f; #ifdef USE_DIRECTX_RENDERER if (m_isInWorld) { Uint16x3 blockIdx; BlockCommon::ConvertToBlockIndex(x, y, z, blockIdx.x, blockIdx.y, blockIdx.z); if (blockIdx.y < BlockConfig::g_regionBlockDimY) { for (int i = 0; i < nRayLength; i++) { uint16_t block_id = GetBlockTemplateIdByIdx(blockIdx.x, blockIdx.y - i, blockIdx.z); if (block_id > 0) { BlockTemplate* pBlockTemplate = GetBlockTemplate(block_id); if (pBlockTemplate != 0 && (pBlockTemplate->IsMatchAttribute(BlockTemplate::batt_liquid) && !pBlockTemplate->IsMatchAttribute(BlockTemplate::batt_solid))) { Vector3 vPos = BlockCommon::ConvertToRealPosition(blockIdx.x, blockIdx.y - i, blockIdx.z, 4); fWaterLevel = vPos.y - BlockConfig::g_blockSize *0.2f; } break; } } } if (CGlobals::GetOceanManager()->OceanEnabled()) { float fLevel = CGlobals::GetOceanManager()->GetWaterLevel(); if (fLevel > fWaterLevel) fWaterLevel = fLevel; } } #endif return fWaterLevel; } void BlockWorldClient::SetBlockRenderMethod(BlockRenderMethod method) { #ifdef USE_DIRECTX_RENDERER if (m_dwBlockRenderMethod != method) { if (method == BLOCK_RENDER_FANCY_SHADER) { if (CGlobals::GetSettings().GetMultiSampleType() != 0) { OUTPUT_LOG("BLOCK_RENDER_FANCY_SHADER can not be set with AA\n"); return; } // check for device compatibilities if (CanUseAdvancedShading()) { // just ensure that game effect set is not too low. if (CGlobals::GetSettings().GetGameEffectSet() >= 1024) { CGlobals::GetSettings().LoadGameEffectSet(0); } // disable glow effect since we are using our own. CGlobals::GetScene()->EnableFullScreenGlow(false); } else { OUTPUT_LOG("warning: your device is too low to use deferred shading. \n"); return; } CShadowMap* pShadowMap = CGlobals::GetEffectManager()->GetShadowMap(); if (pShadowMap != NULL) { if (GetUseSunlightShadowMap()) CGlobals::GetScene()->SetShadow(true); else CGlobals::GetScene()->SetShadow(false); } // always disable instancing CGlobals::GetScene()->EnableInstancing(false); // replacing shader to support multiple render target. if (m_terrain_fancy) { CGlobals::GetEffectManager()->MapHandleToEffect(TECH_TERRAIN, m_terrain_fancy.get()); } if (m_normal_mesh_effect_fancy) { CGlobals::GetEffectManager()->MapHandleToEffect(TECH_SIMPLE_MESH_NORMAL, m_normal_mesh_effect_fancy.get()); CGlobals::GetEffectManager()->MapHandleToEffect(TECH_CHARACTER, m_normal_mesh_effect_fancy.get()); } if (m_bmax_model_effect_fancy) { CGlobals::GetEffectManager()->MapHandleToEffect(TECH_BMAX_MODEL, m_bmax_model_effect_fancy.get()); } } else { // reset effect mapping to default values. CGlobals::GetSettings().LoadGameEffectSet(CGlobals::GetSettings().GetGameEffectSet()); } if (m_dwBlockRenderMethod == BLOCK_RENDER_FANCY_SHADER) { // if switching from fancy shader to plain shader // remove all surfaces SAFE_RELEASE(m_render_target_block_info_surface); SAFE_RELEASE(m_render_target_depth_tex_surface); SAFE_RELEASE(m_render_target_normal_surface); SAFE_RELEASE(m_pDepthStencilSurface); m_render_target_color_hdr.reset(); m_render_target_color.reset(); m_render_target_block_info.reset(); m_render_target_depth_tex.reset(); m_render_target_normal.reset(); CGlobals::GetRenderDevice()->SetRenderTarget(1, NULL); CGlobals::GetRenderDevice()->SetRenderTarget(2, NULL); CGlobals::GetRenderDevice()->SetRenderTarget(3, NULL); } m_dwBlockRenderMethod = method; ClearBlockRenderCache(); } #elif defined(USE_OPENGL_RENDERER) CGlobals::GetSettings().LoadGameEffectSet(0); #endif } void BlockWorldClient::ClearBlockRenderCache() { if (IsInBlockWorld()) { for (int x = 0; x < m_activeChunkDim; x++) { for (int z = 0; z < m_activeChunkDim; z++) { for (int y = 0; y < m_activeChunkDim; y++) { RenderableChunk& chunk = GetActiveChunk(x, y, z); if (!chunk.IsEmptyChunk()) { chunk.SetChunkDirty(true); } } } } } } void BlockWorldClient::SetBlockLightColor(const LinearColor& color) { m_vBlockLightColor = color; } LinearColor BlockWorldClient::GetBlockLightColor() { return m_vBlockLightColor; } bool BlockWorldClient::CompareRenderOrder(BlockRenderTask* v0, BlockRenderTask* v1) { return (v0->GetRenderOrder() < v1->GetRenderOrder()); } bool BlockWorldClient::GetUsePointTextureFiltering() { return m_bUsePointTextureFiltering; } void BlockWorldClient::SetUsePointTextureFiltering(bool bUse) { m_bUsePointTextureFiltering = bUse; } void BlockWorldClient::InitDeviceObjects() { if (IsInBlockWorld()) UpdateAllActiveChunks(); } void BlockWorldClient::RestoreDeviceObjects() { } void BlockWorldClient::InvalidateDeviceObjects() { #ifdef USE_DIRECTX_RENDERER SAFE_RELEASE(m_render_target_block_info_surface); SAFE_RELEASE(m_render_target_depth_tex_surface); SAFE_RELEASE(m_render_target_normal_surface); SAFE_RELEASE(m_pDepthStencilSurface); m_render_target_color_hdr.reset(); m_render_target_color.reset(); m_render_target_block_info.reset(); m_render_target_depth_tex.reset(); m_render_target_normal.reset(); #endif } void BlockWorldClient::RestoreNormalShader() { // restore effect to old one. EffectManager* pEffectManager = CGlobals::GetEffectManager(); pEffectManager->EndEffect(); auto* pEffect = pEffectManager->GetEffectByName("simple_mesh_normal"); if (pEffect) { pEffect->LoadAsset(); pEffectManager->MapHandleToEffect(TECH_SIMPLE_MESH_NORMAL, pEffect); pEffectManager->MapHandleToEffect(TECH_CHARACTER, pEffect); } pEffect = pEffectManager->GetEffectByName("BMaxModel"); if (pEffect) { pEffect->LoadAsset(); pEffectManager->MapHandleToEffect(TECH_BMAX_MODEL, pEffect); } CGlobals::GetSceneState()->SetDeferredShading(true); } void BlockWorldClient::DoPostRenderingProcessing(BlockRenderPass nRenderPass) { #ifdef USE_DIRECTX_RENDERER if (IsInBlockWorld() && GetBlockRenderMethod() == BLOCK_RENDER_FANCY_SHADER) { if (nRenderPass == BlockRenderPass_Opaque) { if (!m_sPostProcessorCallbackScript.empty()) CGlobals::GetNPLRuntime()->GetMainRuntimeState()->DoString(m_sPostProcessorCallbackScript.c_str(), (int)m_sPostProcessorCallbackScript.size()); RenderDynamicBlocks(); RestoreNormalShader(); } else if (nRenderPass == BlockRenderPass_AlphaBlended) { if (!m_sPostProcessorAlphaCallbackScript.empty()) CGlobals::GetNPLRuntime()->GetMainRuntimeState()->DoString(m_sPostProcessorAlphaCallbackScript.c_str(), (int)m_sPostProcessorAlphaCallbackScript.size()); } } #endif } bool BlockWorldClient::PrepareAllRenderTargets(bool bSetRenderTarget /*= true*/) { #ifdef USE_DIRECTX_RENDERER if (GetBlockRenderMethod() == BLOCK_RENDER_FANCY_SHADER) { RenderDevicePtr pDevice = CGlobals::GetRenderDevice(); if (m_block_effect_fancy == 0) { m_block_effect_fancy = CGlobals::GetAssetManager()->LoadEffectFile("blockFancy", "script/apps/Aries/Creator/Game/Shaders/mrt_blocks.fxo"); m_block_effect_fancy->LoadAsset(); if (!m_block_effect_fancy->IsValid()) { // try a lower shader other than fancy return false; } } else if (!m_block_effect_fancy->IsValid()) { // try a lower shader other than fancy return false; } if (!IsInBlockWorld()) { RestoreNormalShader(); return false; } if (m_render_target_block_info == 0) { m_render_target_block_info = CGlobals::GetAssetManager()->LoadTexture("_BlockInfoRT", "_BlockInfoRT", TextureEntity::RenderTarget); m_render_target_block_info->LoadAsset(); SAFE_RELEASE(m_render_target_block_info_surface); m_render_target_block_info->GetTexture()->GetSurfaceLevel(0, &m_render_target_block_info_surface); } if (m_render_target_depth_tex == 0) { m_render_target_depth_tex = CGlobals::GetAssetManager()->LoadTexture("_DepthTexRT_R32F", "_DepthTexRT_R32F", TextureEntity::RenderTarget); m_render_target_depth_tex->LoadAsset(); SAFE_RELEASE(m_render_target_depth_tex_surface); m_render_target_depth_tex->GetTexture()->GetSurfaceLevel(0, &m_render_target_depth_tex_surface); } if (m_render_target_normal == 0) { m_render_target_normal = CGlobals::GetAssetManager()->LoadTexture("_NormalRT", "_NormalRT", TextureEntity::RenderTarget); m_render_target_normal->LoadAsset(); SAFE_RELEASE(m_render_target_normal_surface); m_render_target_normal->GetTexture()->GetSurfaceLevel(0, &m_render_target_normal_surface); } CGlobals::GetEffectManager()->MapHandleToEffect(TECH_BLOCK_FANCY, m_block_effect_fancy.get()); if (m_normal_mesh_effect_fancy == 0) { m_normal_mesh_effect_fancy = CGlobals::GetAssetManager()->LoadEffectFile("mesh_normal_fancy", "script/apps/Aries/Creator/Game/Shaders/mrt_mesh_normal.fxo"); m_normal_mesh_effect_fancy->LoadAsset(); if (!m_normal_mesh_effect_fancy->IsValid()) { // try a lower shader other than fancy return false; } } CGlobals::GetEffectManager()->MapHandleToEffect(TECH_SIMPLE_MESH_NORMAL, m_normal_mesh_effect_fancy.get()); CGlobals::GetEffectManager()->MapHandleToEffect(TECH_CHARACTER, m_normal_mesh_effect_fancy.get()); if (m_effect_light_point == 0) { m_effect_light_point = CGlobals::GetAssetManager()->LoadEffectFile("m_effect_light_point", "script/apps/Aries/Creator/Game/Shaders/DeferredShadingPointLighting.fxo"); m_effect_light_point->LoadAsset(); } if (m_effect_light_spot == 0) { m_effect_light_spot = CGlobals::GetAssetManager()->LoadEffectFile("m_effect_light_spot", "script/apps/Aries/Creator/Game/Shaders/DeferredShadingSpotLighting.fxo"); m_effect_light_spot->LoadAsset(); } if (m_effect_light_directional == 0) { m_effect_light_directional = CGlobals::GetAssetManager()->LoadEffectFile("m_effect_light_directional", "script/apps/Aries/Creator/Game/Shaders/DeferredShadingDirectionalLighting.fxo"); m_effect_light_directional->LoadAsset(); } CGlobals::GetEffectManager()->MapHandleToEffect(TECH_LIGHT_POINT, m_effect_light_point.get()); CGlobals::GetEffectManager()->MapHandleToEffect(TECH_LIGHT_SPOT, m_effect_light_spot.get()); CGlobals::GetEffectManager()->MapHandleToEffect(TECH_LIGHT_DIRECTIONAL, m_effect_light_directional.get()); /*if (m_effect_deferred_lighting == 0) { m_effect_deferred_lighting = CGlobals::GetAssetManager()->LoadEffectFile("m_effect_deferred_lighting", "script/apps/Aries/Creator/Game/Shaders/DeferredLighting.fxo"); m_effect_deferred_lighting->LoadAsset(); } CGlobals::GetEffectManager()->MapHandleToEffect(TECH_DEFERRED_LIGHTING, m_effect_deferred_lighting.get());*/ if (m_bmax_model_effect_fancy == 0) { m_bmax_model_effect_fancy = CGlobals::GetAssetManager()->LoadEffectFile("bmax_model_effect_fancy", "script/apps/Aries/Creator/Game/Shaders/mrt_bmax_model.fxo"); m_bmax_model_effect_fancy->LoadAsset(); if (!m_bmax_model_effect_fancy->IsValid()) { // try a lower shader other than fancy return false; } } CGlobals::GetEffectManager()->MapHandleToEffect(TECH_BMAX_MODEL, m_bmax_model_effect_fancy.get()); if (m_terrain_fancy == 0) { m_terrain_fancy = CGlobals::GetAssetManager()->LoadEffectFile("terrain_normal_fancy", "script/apps/Aries/Creator/Game/Shaders/mrt_terrain_normal.fxo"); m_terrain_fancy->LoadAsset(); if (!m_terrain_fancy->IsValid()) { // try a lower shader other than fancy return false; } } CGlobals::GetEffectManager()->MapHandleToEffect(TECH_TERRAIN, m_terrain_fancy.get()); if (bSetRenderTarget) { if (FAILED(pDevice->SetRenderTarget(1, m_render_target_depth_tex_surface)) || FAILED(pDevice->SetRenderTarget(2, m_render_target_block_info_surface)) || FAILED(pDevice->SetRenderTarget(3, m_render_target_normal_surface))) { return false; } CGlobals::GetSceneState()->SetDeferredShading(true); // clear all other render targets to zero. { static int nLastFrameCount = 0; if (nLastFrameCount != CGlobals::GetSceneState()->GetRenderFrameCount()) { nLastFrameCount = CGlobals::GetSceneState()->GetRenderFrameCount(); LPDIRECT3DSURFACE9 pOldRenderTarget = NULL; pOldRenderTarget = CGlobals::GetDirectXEngine().GetRenderTarget(); pDevice->SetRenderTarget(3, NULL); pDevice->SetRenderTarget(0, m_render_target_normal_surface); pDevice->Clear(0L, NULL, D3DCLEAR_TARGET, 0, 1.0f, 0L); pDevice->SetRenderTarget(0, pOldRenderTarget); pDevice->SetRenderTarget(3, m_render_target_normal_surface); } CGlobals::GetViewportManager()->GetActiveViewPort()->ApplyViewport(); } } } #endif return true; } bool BlockWorldClient::DrawMultiFrameBlockWorld() { if (m_pMultiFrameRenderer) return m_pMultiFrameRenderer->Draw(); return false; } void BlockWorldClient::SetPostProcessingScript(const char* sCallbackScript) { m_sPostProcessorCallbackScript = sCallbackScript; } void BlockWorldClient::SetPostProcessingAlphaScript(const char* sCallbackScript) { m_sPostProcessorAlphaCallbackScript = sCallbackScript; } bool BlockWorldClient::CanUseAdvancedShading() { #ifdef USE_DIRECTX_RENDERER if (CGlobals::GetDirectXEngine().GetVertexShaderVersion() >= 3 && CGlobals::GetDirectXEngine().GetPixelShaderVersion() >= 3 && CGlobals::GetDirectXEngine().m_d3dCaps.NumSimultaneousRTs >= 3) { return true; } #endif return false; } void BlockWorldClient::SetUseSunlightShadowMap(bool bEnable) { m_bUseSunlightShadowMap = bEnable; #ifdef USE_DIRECTX_RENDERER if (GetBlockRenderMethod() == BLOCK_RENDER_FANCY_SHADER) { CShadowMap* pShadowMap = CGlobals::GetEffectManager()->GetShadowMap(); if (pShadowMap != NULL) { CGlobals::GetScene()->SetShadow(m_bUseSunlightShadowMap); } } #endif } bool BlockWorldClient::HasSunlightShadowMap() { return GetUseSunlightShadowMap() && CGlobals::GetScene()->IsShadowMapEnabled(); } bool BlockWorldClient::GetUseSunlightShadowMap() { return m_bUseSunlightShadowMap; } void BlockWorldClient::SetUseWaterReflection(bool bEnable) { m_bUseWaterReflection = bEnable; } bool BlockWorldClient::GetUseWaterReflection() { return m_bUseWaterReflection; } void BlockWorldClient::PrepareShadowCasters(CShadowMap* pShadowMap) { #ifdef USE_DIRECTX_RENDERER if (GetBlockRenderMethod() == BLOCK_RENDER_FANCY_SHADER && GetUseSunlightShadowMap()) { // TODO: add all shadow caster chunks within shadow radius. CShapeAABB aabb; Vector3 camWorldPos = CGlobals::GetSceneState()->vEye; Vector3 renderOrig = CGlobals::GetScene()->GetRenderOrigin(); Vector3 vCenter = camWorldPos - renderOrig; float fRadius = min(CGlobals::GetScene()->GetShadowRadius(), 50.f); Vector3 vExtent(fRadius, fRadius, fRadius); aabb.SetCenterExtents(vCenter, vExtent); pShadowMap->AddShadowCasterPoint(aabb); } #endif } void BlockWorldClient::RenderDynamicBlocks() { // no need to lock int nCount = (int)m_selectedBlockMap.size(); for (int i = 0; i < nCount; ++i) { auto& select_group = m_selectedBlockMap[i]; if (select_group.GetBlocks().size() > 0) { if (select_group.m_bWireFrame) RenderWireFrameBlock(i, select_group.m_fScaling, &select_group.m_color); else RenderSelectionBlock(i, select_group.m_fScaling, &select_group.m_color, select_group.m_bEnableBling); } } if (m_damageDegree > 0) RenderDamagedBlock(); } BlockWorldClient* BlockWorldClient::GetInstance() { return g_pInstance; } void BlockWorldClient::GetMaxBlockHeightWatchingSky(uint16_t blockX_ws, uint16_t blockZ_ws, ChunkMaxHeight* pResult) { CBlockWorld::GetMaxBlockHeightWatchingSky(blockX_ws, blockZ_ws, pResult); #ifdef PARAENGINE_CLIENT ParaTerrain::CGlobalTerrain *pTerrain = CGlobals::GetGlobalTerrain(); uint16_t mask = 0; if (pTerrain->TerrainRenderingEnabled()) { for (int i = 0; i < 5; i++) { float x, z; if (i == 0) { x = blockX_ws * BlockConfig::g_blockSize; z = blockZ_ws * BlockConfig::g_blockSize; } else if (i == 1) { x = (blockX_ws + 1) * BlockConfig::g_blockSize; z = blockZ_ws * BlockConfig::g_blockSize; } else if (i == 2) { x = (blockX_ws - 1) * BlockConfig::g_blockSize; z = blockZ_ws * BlockConfig::g_blockSize; } else if (i == 3) { x = blockX_ws * BlockConfig::g_blockSize; z = (blockZ_ws + 1) * BlockConfig::g_blockSize; } else { x = blockX_ws * BlockConfig::g_blockSize; z = (blockZ_ws - 1) * BlockConfig::g_blockSize; } float elevation = pTerrain->GetElevation(x, z); if (elevation != -FLOAT_POS_INFINITY) { elevation -= GetVerticalOffset(); int32 terrainBlockHeight = (int32)(elevation / BlockConfig::g_blockSize); if (terrainBlockHeight < 0) terrainBlockHeight = 0; if (terrainBlockHeight > BlockConfig::g_regionBlockDimY) terrainBlockHeight = BlockConfig::g_regionBlockDimY; if (terrainBlockHeight > pResult[i].GetMaxHeight()) { pResult[i].SetHeight((int16)terrainBlockHeight); mask |= (1 << i); } } } } pResult[5].SetHeight(mask); #endif } void BlockWorldClient::UpdateVisibleChunks(bool bIsShadowPass /*= false*/) { m_visibleChunks.clear(); // bool is_perspective = CGlobals::GetScene()->GetCurrentCamera()->IsPerspectiveView(); Vector3 camWorldPos = CGlobals::GetSceneState()->vEye; Vector3 renderOrig = CGlobals::GetScene()->GetRenderOrigin(); int nRenderFrameCount = CGlobals::GetSceneState()->GetRenderFrameCount(); CCameraFrustum* frustum; static CCameraFrustum caster_frustum; Vector3 camMin; Vector3 camMax; if (bIsShadowPass) { #ifdef USE_DIRECTX_RENDERER frustum = &caster_frustum; Vector3 vCenter = camWorldPos - renderOrig; float fRadius = min(CGlobals::GetScene()->GetShadowRadius(), 50.f); frustum->UpdateFrustum(CGlobals::GetEffectManager()->GetShadowMap()->GetViewProjMatrix()); camMin = Vector3(vCenter.x - fRadius, vCenter.y - fRadius, vCenter.z - fRadius); camMax = Vector3(vCenter.x + fRadius, vCenter.y + fRadius, vCenter.z + fRadius); #else return; #endif } else { frustum = CGlobals::GetScene()->GetCurrentCamera()->GetFrustum(); // calculate aabb for frustum Vector3* frusCorner = frustum->vecFrustum; camMin = frusCorner[0]; camMax = frusCorner[0]; for (int i = 1; i < 8; i++) { Vector3& v = frusCorner[i]; if (camMin.x > v.x) camMin.x = v.x; if (camMin.y > v.y) camMin.y = v.y; if (camMin.z > v.z) camMin.z = v.z; if (camMax.x < v.x) camMax.x = v.x; if (camMax.y < v.y) camMax.y = v.y; if (camMax.z < v.z) camMax.z = v.z; } } camMax += renderOrig; camMin += renderOrig; Uint16x3 camBlockPos; BlockCommon::ConvertToBlockIndex(camWorldPos.x, camWorldPos.y, camWorldPos.z, camBlockPos.x, camBlockPos.y, camBlockPos.z); SetEyeBlockId(camBlockPos); Uint16x3 startIdx, endIdx; BlockCommon::ConvertToBlockIndex(camMin.x, camMin.y, camMin.z, startIdx.x, startIdx.y, startIdx.z); startIdx.x /= 16; startIdx.y /= 16; startIdx.z /= 16; startIdx.x = startIdx.x > 0 ? startIdx.x - 1 : 0; if (m_minActiveChunkId_ws.x > startIdx.x) startIdx.x = m_minActiveChunkId_ws.x; startIdx.y = startIdx.y > 0 ? (startIdx.y <= 15 ? startIdx.y - 1 : 15) : 0; startIdx.z = startIdx.z > 0 ? startIdx.z - 1 : 0; if (m_minActiveChunkId_ws.z > startIdx.z) startIdx.z = m_minActiveChunkId_ws.z; BlockCommon::ConvertToBlockIndex(camMax.x, camMax.y, camMax.z, endIdx.x, endIdx.y, endIdx.z); endIdx.x /= 16; endIdx.y /= 16; endIdx.z /= 16; if ((m_minActiveChunkId_ws.x + m_activeChunkDim) < endIdx.x) endIdx.x = m_minActiveChunkId_ws.x + m_activeChunkDim; endIdx.y = endIdx.y < 15 ? endIdx.y + 1 : 15; if ((m_minActiveChunkId_ws.z + m_activeChunkDim) < endIdx.z) endIdx.z = m_minActiveChunkId_ws.z + m_activeChunkDim; //float fRenderDist = (std::max)(GetRenderDist(), 16) * BlockConfig::g_blockSize; float fRenderDist = GetRenderDist() * BlockConfig::g_blockSize; CShapeSphere sEyeSphere(camWorldPos, fRenderDist); // cull and update each chunk // we will add using a spiral rectangle path from the center. int32 nIndex = 0; int32 dx = 0; int32 dz = 0; int32 chunkX = GetEyeChunkId().x; int32 chunkY = GetEyeChunkId().y; int32 chunkZ = GetEyeChunkId().z; int32 chunkViewRadius = (std::max)((int)(GetRenderDist() / 16), 1); int32 chunkViewSize = chunkViewRadius * 2; Vector3 vChunkSize(BlockConfig::g_chunkSize, BlockConfig::g_chunkSize, BlockConfig::g_chunkSize); // OUTPUT_LOG("---------------cx %d, cz %d\n", chunkX, chunkZ); for (uint16 y = startIdx.y; y <= endIdx.y; y++) { uint16 x = (uint16)(chunkX); uint16 z = (uint16)(chunkZ); RenderableChunk& chunk = GetActiveChunk(x, y, z); if (x >= startIdx.x && x <= endIdx.x && z >= startIdx.z && z <= endIdx.z && chunk.IsIntersect(sEyeSphere)) { Vector3 vMin = BlockCommon::ConvertToRealPosition(x * 16, y * 16, z * 16, 7); vMin -= renderOrig; Vector3 vMax = vMin + vChunkSize; CShapeAABB box; box.SetMinMax(vMin, vMax); if (frustum->TestBox(&box) && chunk.IsNearbyChunksLoaded()) { AddToVisibleChunk(chunk, 0, nRenderFrameCount); } } } for (int32 length = 1; length <= chunkViewSize; ++length) { for (int32 k = 1; k <= 2; ++k) { int32* dir = &(BlockCommon::g_xzDirectionsConst[(nIndex % 4)][0]); nIndex++; for (int32 i = 0; i < length; ++i) { dx = dx + dir[0]; dz = dz + dir[1]; //OUTPUT_LOG("%d, %d\n", dx, dz); for (uint16 y = startIdx.y; y <= endIdx.y; y++) { uint16 x = (uint16)(chunkX + dx); uint16 z = (uint16)(chunkZ + dz); RenderableChunk& chunk = GetActiveChunk(x, y, z); if (x >= startIdx.x && x <= endIdx.x && z >= startIdx.z && z <= endIdx.z && chunk.IsIntersect(sEyeSphere)) { Vector3 vMin = BlockCommon::ConvertToRealPosition(x * 16, y * 16, z * 16, 7); vMin -= renderOrig; Vector3 vMax = vMin + vChunkSize; CShapeAABB box; box.SetMinMax(vMin, vMax); if (frustum->TestBox(&box) && chunk.IsNearbyChunksLoaded()) { AddToVisibleChunk(chunk, length, nRenderFrameCount); } } } } } } nIndex = (nIndex % 4); for (int32 i = 1; i <= chunkViewSize; ++i) { dx = dx + BlockCommon::g_xzDirectionsConst[nIndex][0]; dz = dz + BlockCommon::g_xzDirectionsConst[nIndex][1]; for (uint16_t y = startIdx.y; y <= endIdx.y; y++) { uint16 x = (uint16)(chunkX + dx); uint16 z = (uint16)(chunkZ + dz); RenderableChunk& chunk = GetActiveChunk(x, y, z); if (x >= startIdx.x && x <= endIdx.x && z >= startIdx.z && z <= endIdx.z && chunk.IsIntersect(sEyeSphere)) { Vector3 vMin = BlockCommon::ConvertToRealPosition(x * 16, y * 16, z * 16, 7); vMin -= renderOrig; Vector3 vMax = vMin + vChunkSize; CShapeAABB box; box.SetMinMax(vMin, vMax); if (frustum->TestBox(&box) && chunk.IsNearbyChunksLoaded()) { AddToVisibleChunk(chunk, chunkViewSize, nRenderFrameCount); } } } } if (!bIsShadowPass) m_isVisibleChunkDirty = false; } void BlockWorldClient::AddToVisibleChunk(RenderableChunk &chunk, int nViewDist, int nRenderFrameCount) { chunk.SetChunkViewDistance((int16)nViewDist); chunk.SetViewIndex((int16)m_visibleChunks.size()); chunk.SetRenderFrameCount(nRenderFrameCount); m_visibleChunks.push_back(&chunk); } void BlockWorldClient::ClearVisibleChunksToByteLimit(bool bIsShadowPass) { int nMaxChunkIndex = (int)m_visibleChunks.size(); if (!bIsShadowPass) { int nCurrentVertexBufferSize = 0; for (int i = 0; i < nMaxChunkIndex; i++) { RenderableChunk* pRenderChunk = m_visibleChunks[i]; int nBufferSize = pRenderChunk->GetLastBufferBytes(); nCurrentVertexBufferSize += nBufferSize; if (nCurrentVertexBufferSize > GetMaxVisibleVertexBufferBytes()) { nMaxChunkIndex = i + 1; m_visibleChunks.resize(nMaxChunkIndex); break; } } } } int BlockWorldClient::ClearActiveChunksToMemLimit(bool bIsShadowPass) { int nMaxChunkIndex = (int)m_visibleChunks.size(); int nUsedBytes = (int)(RenderableChunk::GetVertexBufferPool()->GetTotalBufferBytes()); int nBytesToRemove = nUsedBytes - GetVertexBufferSizeLimit(); if (nBytesToRemove > 0) { if (bIsShadowPass) return 0; static std::set<RenderableChunk*> m_safeVisibleChunks; static std::deque<RenderableChunk*> m_removableChunks; m_safeVisibleChunks.clear(); m_removableChunks.clear(); int nCurrentRenderFrame = (m_visibleChunks.size() > 0) ? m_visibleChunks[0]->GetRenderFrameCount() : 0; if (GetAlwaysInVertexBufferChunkRadius() > 0) { // add all always in cache chunks to safe chunks. int32 chunkX = GetEyeChunkId().x; int32 chunkY = GetEyeChunkId().y; int32 chunkZ = GetEyeChunkId().z; int32 nCacheRadius = GetAlwaysInVertexBufferChunkRadius(); for (int x = chunkX - nCacheRadius; x <= (chunkX + nCacheRadius); x++) { for (int y = chunkY - nCacheRadius; y <= (chunkY + nCacheRadius); y++) { for (int z = chunkZ - nCacheRadius; z <= (chunkZ + nCacheRadius); z++) { if (x >= 0 && y >= 0 && z >= 0) { RenderableChunk& chunk = GetActiveChunk((uint16)x, (uint16)y, (uint16)z); m_safeVisibleChunks.insert(&chunk); } } } } } int nCurrentVertexBufferSize = 0; for (int i = 0; i < nMaxChunkIndex; i++) { RenderableChunk* pRenderChunk = m_visibleChunks[i]; int nBufferSize = pRenderChunk->GetLastBufferBytes(); nCurrentVertexBufferSize += nBufferSize; m_safeVisibleChunks.insert(pRenderChunk); if (nCurrentVertexBufferSize > GetVertexBufferSizeLimit()) { nMaxChunkIndex = i + 1; // if memory is tight, remove chunks that is out of memory range. ChunkVertexBuilderManager::GetInstance().RemovePendingChunks(&m_safeVisibleChunks); break; } } for (int z = 0; z < m_activeChunkDim; z++) { int16_t curChunkWZ = m_minActiveChunkId_ws.z + z; for (int x = 0; x < m_activeChunkDim; x++) { int16_t curChunkWX = m_minActiveChunkId_ws.x + x; { for (int y = 0; y < m_activeChunkDimY; y++) { int16_t curChunkWY = m_minActiveChunkId_ws.y + y; RenderableChunk* pChunk = &GetActiveChunk(curChunkWX, curChunkWY, curChunkWZ); int nBufferSize = pChunk->GetVertexBufferBytes(); if (nBufferSize > 0 && m_safeVisibleChunks.find(pChunk) == m_safeVisibleChunks.end()) { if (nCurrentVertexBufferSize < GetVertexBufferSizeLimit()) { // visible chunks has not exceed memory limit, we will put unused chunks to a sorted queue according to render frame count. if (m_removableChunks.empty() || m_removableChunks.back()->GetRenderFrameCount() > pChunk->GetRenderFrameCount() || (nCurrentRenderFrame == pChunk->GetRenderFrameCount() && m_removableChunks.back()->GetChunkViewDistance() < pChunk->GetChunkViewDistance())) m_removableChunks.push_back(pChunk); else m_removableChunks.push_front(pChunk); } else { // visible chunks already consumes too much memory, we will remove everything else if (nBytesToRemove > nBufferSize) { nBytesToRemove -= nBufferSize; pChunk->ClearChunkData(); } } } } } } } // m_removableChunks is sorted from newest chunk to oldest chunk. // we will remove oldest chunks first. while (!m_removableChunks.empty()) { RenderableChunk* pChunk = m_removableChunks.back(); int nBufferSize = pChunk->GetVertexBufferBytes(); if (nBytesToRemove > nBufferSize) { nBytesToRemove -= nBufferSize; pChunk->ClearChunkData(); m_removableChunks.pop_back(); } else break; } m_removableChunks.clear(); } return nMaxChunkIndex; } void BlockWorldClient::CheckRebuildVisibleChunks(bool bAsyncMode, bool bIsShadowPass) { int nMaxChunkIndex = ClearActiveChunksToMemLimit(bIsShadowPass); m_tempDirtyChunks.clear(); for (int i = 0; i < nMaxChunkIndex; i++) { RenderableChunk* pRenderChunk = m_visibleChunks[i]; BlockChunk* pChunk = pRenderChunk->GetChunk(); if (pChunk/* && pChunk->IsLightingInitialized()*/) { if (pRenderChunk->ShouldRebuildRenderBuffer(this, true, false)) { // new buffer first int nLastDelayTick = pRenderChunk->GetDelayedRebuildTick(); int nViewDist = pRenderChunk->GetChunkViewDistance(); if (nViewDist <= m_nNearCameraChunkDist) pRenderChunk->SetDelayedRebuildTick(nLastDelayTick + 3); else pRenderChunk->SetDelayedRebuildTick(nLastDelayTick + 1); m_tempDirtyChunks.push_back(pRenderChunk); } else if (pRenderChunk->ShouldRebuildRenderBuffer(this, false, true)) { // check update buffer. int nLastDelayTick = pRenderChunk->GetDelayedRebuildTick(); int nViewDist = pRenderChunk->GetChunkViewDistance(); if (nViewDist <= m_nNearCameraChunkDist) pRenderChunk->SetDelayedRebuildTick(nLastDelayTick + 2); else pRenderChunk->SetDelayedRebuildTick(nLastDelayTick + 1); m_tempDirtyChunks.push_back(pRenderChunk); } } } std::stable_sort(m_tempDirtyChunks.begin(), m_tempDirtyChunks.end(), [](RenderableChunk* a, RenderableChunk* b) { return (a->GetDelayedRebuildTick() > b->GetDelayedRebuildTick()); }); int nMaxBufferRebuildPerTick = GetMaxBufferRebuildPerTick(); for (RenderableChunk * pRenderChunk : m_tempDirtyChunks) { if (pRenderChunk->RebuildRenderBuffer(this, bAsyncMode)) { #ifdef PRINT_CHUNK_LOG if (pRenderChunk->IsDirty()) OUTPUT_LOG("rebuild New chunk: pos(%d %d %d) ViewDist:%d DelayCount:%d\n", pRenderChunk->GetChunkPosWs().x, pRenderChunk->GetChunkPosWs().y, pRenderChunk->GetChunkPosWs().z, pRenderChunk->GetChunkViewDistance(), pRenderChunk->GetDelayedRebuildTick()); else OUTPUT_LOG("rebuild chunk: pos(%d %d %d) ViewDist:%d DelayCount:%d\n", pRenderChunk->GetChunkPosWs().x, pRenderChunk->GetChunkPosWs().y, pRenderChunk->GetChunkPosWs().z, pRenderChunk->GetChunkViewDistance(), pRenderChunk->GetDelayedRebuildTick()); #endif m_nBufferRebuildCountThisTick++; if (pRenderChunk->GetChunkViewDistance() > GetNearCameraChunkDist()) { // for far away blocks, we will only rebuild 1 per tick, instead of 3. just in case the view distance is set really high. nMaxBufferRebuildPerTick = GetMaxBufferRebuildPerTick_FarChunk(); } if (bAsyncMode && m_nBufferRebuildCountThisTick >= nMaxBufferRebuildPerTick) break; } else break; } m_tempDirtyChunks.clear(); } std::vector<BlockRenderTask*>* BlockWorldClient::GetRenderQueueByPass(BlockRenderPass nRenderPass) { if (nRenderPass == BlockRenderPass_Opaque) return &m_solidRenderTasks; else if (nRenderPass == BlockRenderPass_AlphaTest) return &m_alphaTestRenderTasks; else if (nRenderPass == BlockRenderPass_ReflectedWater) return &m_reflectedWaterRenderTasks; else return &m_alphaBlendRenderTasks; } bool BlockWorldClient::IsMovieOutputMode() const { return m_bMovieOutputMode; } void BlockWorldClient::EnableMovieOutputMode(bool val) { #ifdef WIN32 if (m_bMovieOutputMode != val) { static int s_lastMaxCacheRegionCount = m_maxCacheRegionCount; static int s_nMaxBufferRebuildPerTick = m_nMaxBufferRebuildPerTick; static int s_nNearCameraChunkDist = m_nNearCameraChunkDist; static int s_nMaxBufferRebuildPerTick_FarChunk = m_nMaxBufferRebuildPerTick_FarChunk; m_bMovieOutputMode = val; if (m_bMovieOutputMode) { s_lastMaxCacheRegionCount = m_maxCacheRegionCount; s_nMaxBufferRebuildPerTick = m_nMaxBufferRebuildPerTick; s_nNearCameraChunkDist = m_nNearCameraChunkDist; s_nMaxBufferRebuildPerTick_FarChunk = m_nMaxBufferRebuildPerTick_FarChunk; m_maxCacheRegionCount = 64; m_nMaxBufferRebuildPerTick = 100; m_nNearCameraChunkDist = 20; m_nMaxBufferRebuildPerTick_FarChunk = 100; ChunkVertexBuilderManager::GetInstance().m_nMaxPendingChunks = 100; ChunkVertexBuilderManager::GetInstance().m_nMaxUploadingChunks = 100; ChunkVertexBuilderManager::GetInstance().m_nMaxChunksToUploadPerTick = 100; OUTPUT_LOG("movie output mode is on\n"); } else { m_maxCacheRegionCount = s_lastMaxCacheRegionCount; m_nMaxBufferRebuildPerTick = s_nMaxBufferRebuildPerTick; m_nNearCameraChunkDist = s_nNearCameraChunkDist; m_nMaxBufferRebuildPerTick_FarChunk = s_nMaxBufferRebuildPerTick_FarChunk; ChunkVertexBuilderManager::GetInstance().m_nMaxPendingChunks = 4; ChunkVertexBuilderManager::GetInstance().m_nMaxUploadingChunks = 4; ChunkVertexBuilderManager::GetInstance().m_nMaxChunksToUploadPerTick = 8; OUTPUT_LOG("movie output mode is off\n"); } } #endif } void BlockWorldClient::UpdateActiveChunk() { CBlockWorld::UpdateActiveChunk(); } int BlockWorldClient::GetVertexBufferSizeLimit() const { return m_nVertexBufferSizeLimit; } void BlockWorldClient::SetVertexBufferSizeLimit(int val) { m_nVertexBufferSizeLimit = val; } IAttributeFields* BlockWorldClient::GetChildAttributeObject(const std::string& sName) { if (sName == "ChunkVertexBuilderManager") { return &(ChunkVertexBuilderManager::GetInstance()); } else if (sName == "LightGrid") { return &(GetLightGrid()); } else if (sName == "CMultiFrameBlockWorldRenderer") { return m_pMultiFrameRenderer; } else return CBlockWorld::GetChildAttributeObject(sName); } int BlockWorldClient::GetChildAttributeColumnCount() { return 2; } IAttributeFields* BlockWorldClient::GetChildAttributeObject(int nRowIndex, int nColumnIndex /*= 0*/) { if (nColumnIndex == 1) { if (nRowIndex == 0) return &(GetLightGrid()); else if (nRowIndex == 1) return &(ChunkVertexBuilderManager::GetInstance()); else if (nRowIndex == 2) return m_pMultiFrameRenderer; } return CBlockWorld::GetChildAttributeObject(nRowIndex, nColumnIndex); } int BlockWorldClient::GetChildAttributeObjectCount(int nColumnIndex /*= 0*/) { if (nColumnIndex == 1) { return 3; } return CBlockWorld::GetChildAttributeObjectCount(nColumnIndex); } int BlockWorldClient::GetAlwaysInVertexBufferChunkRadius() const { return m_nAlwaysInVertexBufferChunkRadius; } void BlockWorldClient::SetAlwaysInVertexBufferChunkRadius(int val) { m_nAlwaysInVertexBufferChunkRadius = val; } int BlockWorldClient::GetMaxVisibleVertexBufferBytes() const { return m_nMaxVisibleVertexBufferBytes; } void BlockWorldClient::SetMaxVisibleVertexBufferBytes(int val) { m_nMaxVisibleVertexBufferBytes = val; } bool BlockWorldClient::IsAsyncChunkMode() const { return m_bAsyncChunkMode; } void BlockWorldClient::SetAsyncChunkMode(bool val) { if (m_bAsyncChunkMode != val) { m_bAsyncChunkMode = val; if (!m_bAsyncChunkMode) { } } } int BlockWorldClient::GetMaxBufferRebuildPerTick() const { return m_nMaxBufferRebuildPerTick; } void BlockWorldClient::SetMaxBufferRebuildPerTick(int val) { m_nMaxBufferRebuildPerTick = val; } int BlockWorldClient::GetNearCameraChunkDist() const { return m_nNearCameraChunkDist; } void BlockWorldClient::SetNearCameraChunkDist(int val) { m_nNearCameraChunkDist = val; } int BlockWorldClient::GetMaxBufferRebuildPerTick_FarChunk() const { return m_nMaxBufferRebuildPerTick_FarChunk; } void BlockWorldClient::SetMaxBufferRebuildPerTick_FarChunk(int val) { m_nMaxBufferRebuildPerTick_FarChunk = val; if (m_nMaxBufferRebuildPerTick_FarChunk > GetMaxBufferRebuildPerTick()) SetMaxBufferRebuildPerTick(m_nMaxBufferRebuildPerTick_FarChunk); } bool BlockWorldClient::DrawMultiFrameBlockWorldOnSky() { return m_pMultiFrameRenderer->DrawToSkybox(); } void BlockWorldClient::RenderDeferredLightsMesh() { return; #ifdef USE_DIRECTX_RENDERER SceneState* sceneState = CGlobals::GetSceneState(); if (!sceneState->IsDeferredShading() || sceneState->listDeferredLightObjects.empty()) return; // sort by light type std::sort(sceneState->listDeferredLightObjects.begin(), sceneState->listDeferredLightObjects.end(), [](CLightObject* a, CLightObject* b) { return (a->GetLightType() < b->GetLightType()); }); // setup shader here for (int i = 0; i < 3; i++) { if (m_lightgeometry_effects[i] == 0) { if (i == 0) m_lightgeometry_effects[i] = CGlobals::GetAssetManager()->LoadEffectFile("blockFancy", "script/apps/Aries/Creator/Game/Shaders/DeferredShadingPointLighting.fxo"); else if (i == 2) m_lightgeometry_effects[i] = CGlobals::GetAssetManager()->LoadEffectFile("blockFancy", "script/apps/Aries/Creator/Game/Shaders/DeferredShadingSpotLighting.fxo"); else m_lightgeometry_effects[i] = CGlobals::GetAssetManager()->LoadEffectFile("blockFancy", "script/apps/Aries/Creator/Game/Shaders/DeferredShadingDirectionalLighting.fxo"); m_lightgeometry_effects[i]->LoadAsset(); } if (!m_lightgeometry_effects[i] || !m_lightgeometry_effects[i]->IsValid()) return; } // sort by type and render light geometry int nLastType = -1; CGlobals::GetEffectManager()->EndEffect(); CEffectFile* pEffectFile = NULL; for (CLightObject* lightObject : sceneState->listDeferredLightObjects) { if (lightObject->GetLightType() != nLastType) { if (pEffectFile) { pEffectFile->end(); } else { // first time, we will switch to declaration auto pDecl = CGlobals::GetEffectManager()->GetVertexDeclaration(EffectManager::S0_POS); if (pDecl) CGlobals::GetRenderDevice()->SetVertexDeclaration(pDecl); } pEffectFile = m_lightgeometry_effects[lightObject->GetLightType() - 1].get(); pEffectFile->begin(); } lightObject->RenderDeferredLightMesh(sceneState); } if (pEffectFile) { pEffectFile->end(); } #endif } void BlockWorldClient::RenderDeferredLighting() { #ifdef USE_DIRECTX_RENDERER SceneState* sceneState = CGlobals::GetSceneState(); if (!sceneState->IsDeferredShading() || sceneState->listDeferredLightObjects.empty()) return; CGlobals::GetEffectManager()->EndEffect(); auto pDevice = sceneState->GetRenderDevice(); ParaScripting::ParaAsset::LoadEffectFile("deferred_point_lighting", "script/apps/Aries/Creator/Game/Shaders/DeferredShadingPointLighting.fxo"); ParaScripting::ParaAsset::LoadEffectFile("deferred_spot_lighting", "script/apps/Aries/Creator/Game/Shaders/DeferredShadingSpotLighting.fxo"); ParaScripting::ParaAsset::LoadEffectFile("deferred_directional_lighting", "script/apps/Aries/Creator/Game/Shaders/DeferredShadingDirectionalLighting.fxo"); ParaScripting::ParaAssetObject effect = NULL; VertexDeclarationPtr pDecl = NULL; ID3DXMesh * pObject = NULL; for (CLightObject* lightObject : sceneState->listDeferredLightObjects) { auto light_param = lightObject->GetLightParams(); auto light_type = light_param->Type; auto light_diffuse = light_param->Diffuse; auto light_specular = light_param->Specular; auto light_ambient = light_param->Ambient; auto light_position = light_param->Position; auto light_direction = lightObject->GetDirection(); auto light_range = light_param->Range; auto light_falloff = light_param->Falloff; auto light_attenuation0 = light_param->Attenuation0; auto light_attenuation1 = light_param->Attenuation1; auto light_attenuation2 = light_param->Attenuation2; auto light_theta = light_param->Theta; auto light_phi = light_param->Phi; // how complicated the mesh is int mesh_slice_num = 50; switch (light_type) { case D3DLIGHT_POINT: effect = ParaScripting::ParaAsset::GetEffectFile("deferred_point_lighting"); D3DXCreateSphere(pDevice, light_range, mesh_slice_num, mesh_slice_num, &pObject, 0); pDecl = CGlobals::GetEffectManager()->GetVertexDeclaration(EffectManager::S0_POS); break; case D3DLIGHT_SPOT: effect = ParaScripting::ParaAsset::GetEffectFile("deferred_spot_lighting"); // FIXME: how to draw a spherical cone but a normal cone //D3DXCreateCylinder(pDevice, 0.0f, 2.0f, 5.0f, 100, 100, &pObject, 0); D3DXCreateSphere(pDevice, light_range, mesh_slice_num, mesh_slice_num, &pObject, 0); pDecl = CGlobals::GetEffectManager()->GetVertexDeclaration(EffectManager::S0_POS); break; case D3DLIGHT_DIRECTIONAL: effect = ParaScripting::ParaAsset::GetEffectFile("deferred_directional_lighting"); pDecl = CGlobals::GetEffectManager()->GetVertexDeclaration(EffectManager::S0_POS_TEX0); break; } if (pDecl) pDevice->SetVertexDeclaration(pDecl); effect.Begin(); auto params = effect.GetParamBlock(); params.SetParam("ViewAspect", "floatViewAspect"); params.SetParam("TanHalfFOV", "floatTanHalfFOV"); params.SetParam("screenParam", "vec2ScreenSize"); params.SetParam("viewportOffset", "vec2ViewportOffset"); params.SetParam("viewportScale", "vec2ViewportScale"); Matrix4 mxWorld; lightObject->GetRenderMatrix(mxWorld); CGlobals::GetWorldMatrixStack().push(mxWorld); params.SetParam("matWorld", "mat4World"); CGlobals::GetWorldMatrixStack().pop(); params.SetParam("matView", "mat4View"); params.SetParam("matProj", "mat4Projection"); params.SetVector4("light_diffuse", light_diffuse.r, light_diffuse.g, light_diffuse.b, light_diffuse.a); params.SetVector4("light_specular", light_specular.r, light_specular.g, light_specular.b, light_specular.a); params.SetVector4("light_ambient", light_ambient.r, light_ambient.g, light_ambient.b, light_ambient.a); params.SetVector3("light_position", light_position.x, light_position.y, light_position.z); params.SetVector3("light_direction", light_direction.x, light_direction.y, light_direction.z); params.SetFloat("light_range", light_range); params.SetFloat("light_falloff", light_falloff); params.SetFloat("light_attenuation0", light_attenuation0); params.SetFloat("light_attenuation1", light_attenuation1); params.SetFloat("light_attenuation2", light_attenuation2); params.SetFloat("light_theta", light_theta); params.SetFloat("light_phi", light_phi); auto _ColorRT = ParaScripting::ParaAsset::LoadTexture("_ColorRT", "_ColorRT", 0); auto originRT = ParaScripting::CParaEngine::GetRenderTarget(); ParaScripting::CParaEngine::StretchRect(originRT, _ColorRT); ParaScripting::CParaEngine::SetRenderTarget(originRT); params.SetTextureObj(0, _ColorRT); params.SetTextureObj(2, ParaScripting::ParaAsset::LoadTexture("_DepthTexRT_R32F", "_DepthTexRT_R32F", 0)); params.SetTextureObj(3, ParaScripting::ParaAsset::LoadTexture("_NormalRT", "_NormalRT", 0)); effect.CommitChanges(); pDevice->Clear(0, 0, D3DCLEAR_STENCIL, 0, 1.0f, 0); switch (light_type) { case D3DLIGHT_POINT: case D3DLIGHT_SPOT: for (int pass = 0; pass < 2; pass++) { if (effect.BeginPass(pass)) { pObject->DrawSubset(0); effect.EndPass(); } } pObject->Release(); break; case D3DLIGHT_DIRECTIONAL: if (effect.BeginPass(0)) { ParaScripting::CParaEngine::DrawQuad(); effect.EndPass(); } break; } effect.End(); } #endif } int BlockWorldClient::InstallFields(CAttributeClass* pClass, bool bOverride) { // install parent fields if there are any. Please replace CBlockWorld with your parent class name. CBlockWorld::InstallFields(pClass, bOverride); PE_ASSERT(pClass != NULL); pClass->AddField("BlockLightColor", FieldType_Vector3, (void*)SetBlockLightColor_s, (void*)GetBlockLightColor_s, NULL, NULL, bOverride); pClass->AddField("PostProcessingScript", FieldType_String, (void*)SetPostProcessingScript_s, NULL, NULL, NULL, bOverride); pClass->AddField("PostProcessingAlphaScript", FieldType_String, (void*)SetPostProcessingAlphaScript_s, NULL, NULL, NULL, bOverride); pClass->AddField("HasSunlightShadowMap", FieldType_Bool, (void*)0, (void*)HasSunlightShadowMap_s, NULL, NULL, bOverride); pClass->AddField("UseSunlightShadowMap", FieldType_Bool, (void*)SetUseSunlightShadowMap_s, (void*)GetUseSunlightShadowMap_s, NULL, NULL, bOverride); pClass->AddField("UseWaterReflection", FieldType_Bool, (void*)SetUseWaterReflection_s, (void*)GetUseWaterReflection_s, NULL, NULL, bOverride); pClass->AddField("CanUseAdvancedShading", FieldType_Bool, NULL, (void*)CanUseAdvancedShading_s, NULL, NULL, bOverride); pClass->AddField("MovieOutputMode", FieldType_Bool, (void*)EnableMovieOutputMode_s, (void*)IsMovieOutputMode_s, NULL, NULL, bOverride); pClass->AddField("AsyncChunkMode", FieldType_Bool, (void*)SetAsyncChunkMode_s, (void*)IsAsyncChunkMode_s, NULL, NULL, bOverride); pClass->AddField("VertexBufferSizeLimit", FieldType_Int, (void*)SetVertexBufferSizeLimit_s, (void*)GetVertexBufferSizeLimit_s, NULL, NULL, bOverride); pClass->AddField("AlwaysInVertexBufferChunkRadius", FieldType_Int, (void*)SetAlwaysInVertexBufferChunkRadius_s, (void*)GetAlwaysInVertexBufferChunkRadius_s, NULL, NULL, bOverride); pClass->AddField("MaxVisibleVertexBufferBytes", FieldType_Int, (void*)SetMaxVisibleVertexBufferBytes_s, (void*)GetMaxVisibleVertexBufferBytes_s, NULL, NULL, bOverride); pClass->AddField("NearCameraChunkDist", FieldType_Int, (void*)SetNearCameraChunkDist_s, (void*)GetNearCameraChunkDist_s, NULL, NULL, bOverride); pClass->AddField("MaxBufferRebuildPerTick", FieldType_Int, (void*)SetMaxBufferRebuildPerTick_s, (void*)GetMaxBufferRebuildPerTick_s, NULL, NULL, bOverride); pClass->AddField("MaxBufferRebuildPerTick_FarChunk", FieldType_Int, (void*)SetMaxBufferRebuildPerTick_FarChunk_s, (void*)GetMaxBufferRebuildPerTick_FarChunk_s, NULL, NULL, bOverride); pClass->AddField("UsePointTextureFiltering", FieldType_Bool, (void*)SetUsePointTextureFiltering_s, (void*)GetUsePointTextureFiltering_s, NULL, NULL, bOverride); return S_OK; } }
LiXizhi/NPLRuntime
Client/trunk/ParaEngineClient/BlockEngine/BlockWorldClient.cpp
C++
gpl-2.0
113,122
from re import compile as re_compile from os import path as os_path, listdir from MenuList import MenuList from Components.Harddisk import harddiskmanager from Tools.Directories import SCOPE_CURRENT_SKIN, resolveFilename, fileExists from enigma import RT_HALIGN_LEFT, eListboxPythonMultiContent, \ eServiceReference, eServiceCenter, gFont from Tools.LoadPixmap import LoadPixmap EXTENSIONS = { "m4a": "music", "mp2": "music", "mp3": "music", "wav": "music", "ogg": "music", "flac": "music", "jpg": "picture", "jpeg": "picture", "png": "picture", "bmp": "picture", "ts": "movie", "avi": "movie", "divx": "movie", "m4v": "movie", "mpg": "movie", "mpeg": "movie", "mkv": "movie", "mp4": "movie", "mov": "movie", "m2ts": "movie", } def FileEntryComponent(name, absolute = None, isDir = False): res = [ (absolute, isDir) ] res.append((eListboxPythonMultiContent.TYPE_TEXT, 35, 1, 470, 20, 0, RT_HALIGN_LEFT, name)) if isDir: png = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "extensions/directory.png")) else: extension = name.split('.') extension = extension[-1].lower() if EXTENSIONS.has_key(extension): png = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "extensions/" + EXTENSIONS[extension] + ".png")) else: png = None if png is not None: res.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 10, 2, 20, 20, png)) return res class FileList(MenuList): def __init__(self, directory, showDirectories = True, showFiles = True, showMountpoints = True, matchingPattern = None, useServiceRef = False, inhibitDirs = False, inhibitMounts = False, isTop = False, enableWrapAround = False, additionalExtensions = None): MenuList.__init__(self, list, enableWrapAround, eListboxPythonMultiContent) self.additional_extensions = additionalExtensions self.mountpoints = [] self.current_directory = None self.current_mountpoint = None self.useServiceRef = useServiceRef self.showDirectories = showDirectories self.showMountpoints = showMountpoints self.showFiles = showFiles self.isTop = isTop # example: matching .nfi and .ts files: "^.*\.(nfi|ts)" self.matchingPattern = matchingPattern self.inhibitDirs = inhibitDirs or [] self.inhibitMounts = inhibitMounts or [] self.refreshMountpoints() self.changeDir(directory) self.l.setFont(0, gFont("Regular", 18)) self.l.setItemHeight(23) self.serviceHandler = eServiceCenter.getInstance() def refreshMountpoints(self): self.mountpoints = [os_path.join(p.mountpoint, "") for p in harddiskmanager.getMountedPartitions()] self.mountpoints.sort(reverse = True) def getMountpoint(self, file): file = os_path.join(os_path.realpath(file), "") for m in self.mountpoints: if file.startswith(m): return m return False def getMountpointLink(self, file): if os_path.realpath(file) == file: return self.getMountpoint(file) else: if file[-1] == "/": file = file[:-1] mp = self.getMountpoint(file) last = file file = os_path.dirname(file) while last != "/" and mp == self.getMountpoint(file): last = file file = os_path.dirname(file) return os_path.join(last, "") def getSelection(self): if self.l.getCurrentSelection() is None: return None return self.l.getCurrentSelection()[0] def getCurrentEvent(self): l = self.l.getCurrentSelection() if not l or l[0][1] == True: return None else: return self.serviceHandler.info(l[0][0]).getEvent(l[0][0]) def getFileList(self): return self.list def inParentDirs(self, dir, parents): dir = os_path.realpath(dir) for p in parents: if dir.startswith(p): return True return False def changeDir(self, directory, select = None): self.list = [] # if we are just entering from the list of mount points: if self.current_directory is None: if directory and self.showMountpoints: self.current_mountpoint = self.getMountpointLink(directory) else: self.current_mountpoint = None self.current_directory = directory directories = [] files = [] if directory is None and self.showMountpoints: # present available mountpoints for p in harddiskmanager.getMountedPartitions(): path = os_path.join(p.mountpoint, "") if path not in self.inhibitMounts and not self.inParentDirs(path, self.inhibitDirs): self.list.append(FileEntryComponent(name = p.description, absolute = path, isDir = True)) files = [ ] directories = [ ] elif directory is None: files = [ ] directories = [ ] elif self.useServiceRef: # we should not use the 'eServiceReference(string)' constructor, because it doesn't allow ':' in the directoryname root = eServiceReference(2, 0, directory) if self.additional_extensions: root.setName(self.additional_extensions) serviceHandler = eServiceCenter.getInstance() list = serviceHandler.list(root) while 1: s = list.getNext() if not s.valid(): del list break if s.flags & s.mustDescent: directories.append(s.getPath()) else: files.append(s) directories.sort() files.sort() else: if fileExists(directory): try: files = listdir(directory) except: files = [] files.sort() tmpfiles = files[:] for x in tmpfiles: if os_path.isdir(directory + x): directories.append(directory + x + "/") files.remove(x) if directory is not None and self.showDirectories and not self.isTop: if directory == self.current_mountpoint and self.showMountpoints: self.list.append(FileEntryComponent(name = "<" +_("List of Storage Devices") + ">", absolute = None, isDir = True)) elif (directory != "/") and not (self.inhibitMounts and self.getMountpoint(directory) in self.inhibitMounts): self.list.append(FileEntryComponent(name = "<" +_("Parent Directory") + ">", absolute = '/'.join(directory.split('/')[:-2]) + '/', isDir = True)) if self.showDirectories: for x in directories: if not (self.inhibitMounts and self.getMountpoint(x) in self.inhibitMounts) and not self.inParentDirs(x, self.inhibitDirs): name = x.split('/')[-2] self.list.append(FileEntryComponent(name = name, absolute = x, isDir = True)) if self.showFiles: for x in files: if self.useServiceRef: path = x.getPath() name = path.split('/')[-1] else: path = directory + x name = x if (self.matchingPattern is None) or re_compile(self.matchingPattern).search(path): self.list.append(FileEntryComponent(name = name, absolute = x , isDir = False)) if self.showMountpoints and len(self.list) == 0: self.list.append(FileEntryComponent(name = _("nothing connected"), absolute = None, isDir = False)) self.l.setList(self.list) if select is not None: i = 0 self.moveToIndex(0) for x in self.list: p = x[0][0] if isinstance(p, eServiceReference): p = p.getPath() if p == select: self.moveToIndex(i) i += 1 def getCurrentDirectory(self): return self.current_directory def canDescent(self): if self.getSelection() is None: return False return self.getSelection()[1] def descent(self): if self.getSelection() is None: return self.changeDir(self.getSelection()[0], select = self.current_directory) def getFilename(self): if self.getSelection() is None: return None x = self.getSelection()[0] if isinstance(x, eServiceReference): x = x.getPath() return x def getServiceRef(self): if self.getSelection() is None: return None x = self.getSelection()[0] if isinstance(x, eServiceReference): return x return None def execBegin(self): harddiskmanager.on_partition_list_change.append(self.partitionListChanged) def execEnd(self): harddiskmanager.on_partition_list_change.remove(self.partitionListChanged) def refresh(self): self.changeDir(self.current_directory, self.getFilename()) def partitionListChanged(self, action, device): self.refreshMountpoints() if self.current_directory is None: self.refresh() def MultiFileSelectEntryComponent(name, absolute = None, isDir = False, selected = False): res = [ (absolute, isDir, selected, name) ] res.append((eListboxPythonMultiContent.TYPE_TEXT, 55, 1, 470, 20, 0, RT_HALIGN_LEFT, name)) if isDir: png = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "extensions/directory.png")) else: extension = name.split('.') extension = extension[-1].lower() if EXTENSIONS.has_key(extension): png = LoadPixmap(resolveFilename(SCOPE_CURRENT_SKIN, "extensions/" + EXTENSIONS[extension] + ".png")) else: png = None if png is not None: res.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 30, 2, 20, 20, png)) if not name.startswith('<'): if selected is False: icon = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/lock_off.png")) res.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 2, 0, 25, 25, icon)) else: icon = LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, "skin_default/icons/lock_on.png")) res.append((eListboxPythonMultiContent.TYPE_PIXMAP_ALPHATEST, 2, 0, 25, 25, icon)) return res class MultiFileSelectList(FileList): def __init__(self, preselectedFiles, directory, showMountpoints = False, matchingPattern = None, showDirectories = True, showFiles = True, useServiceRef = False, inhibitDirs = False, inhibitMounts = False, isTop = False, enableWrapAround = False, additionalExtensions = None): self.selectedFiles = preselectedFiles if self.selectedFiles is None: self.selectedFiles = [] FileList.__init__(self, directory, showMountpoints = showMountpoints, matchingPattern = matchingPattern, showDirectories = showDirectories, showFiles = showFiles, useServiceRef = useServiceRef, inhibitDirs = inhibitDirs, inhibitMounts = inhibitMounts, isTop = isTop, enableWrapAround = enableWrapAround, additionalExtensions = additionalExtensions) self.changeDir(directory) self.l.setItemHeight(25) self.l.setFont(0, gFont("Regular", 20)) self.onSelectionChanged = [ ] def selectionChanged(self): for f in self.onSelectionChanged: f() def changeSelectionState(self): idx = self.l.getCurrentSelectionIndex() count = 0 newList = [] for x in self.list: if idx == count: if x[0][3].startswith('<'): newList.append(x) else: if x[0][1] is True: realPathname = x[0][0] else: realPathname = self.current_directory + x[0][0] if x[0][2] == True: SelectState = False for entry in self.selectedFiles: if entry == realPathname: self.selectedFiles.remove(entry) else: SelectState = True alreadyinList = False for entry in self.selectedFiles: if entry == realPathname: alreadyinList = True if not alreadyinList: self.selectedFiles.append(realPathname) newList.append(MultiFileSelectEntryComponent(name = x[0][3], absolute = x[0][0], isDir = x[0][1], selected = SelectState )) else: newList.append(x) count += 1 self.list = newList self.l.setList(self.list) def getSelectedList(self): return self.selectedFiles def changeDir(self, directory, select = None): self.list = [] # if we are just entering from the list of mount points: if self.current_directory is None: if directory and self.showMountpoints: self.current_mountpoint = self.getMountpointLink(directory) else: self.current_mountpoint = None self.current_directory = directory directories = [] files = [] if directory is None and self.showMountpoints: # present available mountpoints for p in harddiskmanager.getMountedPartitions(): path = os_path.join(p.mountpoint, "") if path not in self.inhibitMounts and not self.inParentDirs(path, self.inhibitDirs): self.list.append(MultiFileSelectEntryComponent(name = p.description, absolute = path, isDir = True)) files = [ ] directories = [ ] elif directory is None: files = [ ] directories = [ ] elif self.useServiceRef: root = eServiceReference("2:0:1:0:0:0:0:0:0:0:" + directory) if self.additional_extensions: root.setName(self.additional_extensions) serviceHandler = eServiceCenter.getInstance() list = serviceHandler.list(root) while 1: s = list.getNext() if not s.valid(): del list break if s.flags & s.mustDescent: directories.append(s.getPath()) else: files.append(s) directories.sort() files.sort() else: if fileExists(directory): try: files = listdir(directory) except: files = [] files.sort() tmpfiles = files[:] for x in tmpfiles: if os_path.isdir(directory + x): directories.append(directory + x + "/") files.remove(x) if directory is not None and self.showDirectories and not self.isTop: if directory == self.current_mountpoint and self.showMountpoints: self.list.append(MultiFileSelectEntryComponent(name = "<" +_("List of Storage Devices") + ">", absolute = None, isDir = True)) elif (directory != "/") and not (self.inhibitMounts and self.getMountpoint(directory) in self.inhibitMounts): self.list.append(MultiFileSelectEntryComponent(name = "<" +_("Parent Directory") + ">", absolute = '/'.join(directory.split('/')[:-2]) + '/', isDir = True)) if self.showDirectories: for x in directories: if not (self.inhibitMounts and self.getMountpoint(x) in self.inhibitMounts) and not self.inParentDirs(x, self.inhibitDirs): name = x.split('/')[-2] alreadySelected = False for entry in self.selectedFiles: if entry == x: alreadySelected = True if alreadySelected: self.list.append(MultiFileSelectEntryComponent(name = name, absolute = x, isDir = True, selected = True)) else: self.list.append(MultiFileSelectEntryComponent(name = name, absolute = x, isDir = True, selected = False)) if self.showFiles: for x in files: if self.useServiceRef: path = x.getPath() name = path.split('/')[-1] else: path = directory + x name = x if (self.matchingPattern is None) or re_compile(self.matchingPattern).search(path): alreadySelected = False for entry in self.selectedFiles: if os_path.basename(entry) == x: alreadySelected = True if alreadySelected: self.list.append(MultiFileSelectEntryComponent(name = name, absolute = x , isDir = False, selected = True)) else: self.list.append(MultiFileSelectEntryComponent(name = name, absolute = x , isDir = False, selected = False)) self.l.setList(self.list) if select is not None: i = 0 self.moveToIndex(0) for x in self.list: p = x[0][0] if isinstance(p, eServiceReference): p = p.getPath() if p == select: self.moveToIndex(i) i += 1
openpli-arm/enigma2-arm
lib/python/Components/FileList.py
Python
gpl-2.0
14,837
<?php /** * Form for translation managers to send a notification * to registered translators. * * @file * @author Amir E. Aharoni * @author Santhosh Thottingal * @author Niklas Laxström * @author Siebrand Mazeland * @copyright Copyright © 2012, Amir E. Aharoni, Santhosh Thottingal * @license GPL-2.0-or-later */ use MediaWiki\MediaWikiServices; /** * Form for translation managers to send a notification * to registered translators. * * @ingroup SpecialPage TranslateSpecialPage */ class SpecialNotifyTranslators extends FormSpecialPage { public static $right = 'translate-manage'; private $notificationText = ''; /** * @var Title */ private $translatablePageTitle; private $deadlineDate = ''; private $priority = ''; private $sourceLanguageCode = ''; public function __construct() { parent::__construct( 'NotifyTranslators', self::$right ); } public function doesWrites() { return true; } protected function getGroupName() { return 'translation'; } protected function getMessagePrefix() { return 'translationnotifications'; } protected function alterForm( HTMLForm $form ) { $form->setId( 'notifytranslators-form' ); $form->setSubmitID( 'translationnotifications-send-notification-button' ); $form->setSubmitTextMsg( 'translationnotifications-send-notification-button' ); $form->setWrapperLegend( false ); } /** * Get the form fields for use by the HTMLForm. * We also set up the JavaScript needed on the form here. * * @return array * @throws ErrorPageError if there is no translatable page on this wiki */ protected function getFormFields() { $this->getOutput()->addModules( 'ext.translationnotifications.notifytranslators' ); $formFields = []; $pages = $this->getTranslatablePages(); if ( count( $pages ) === 0 ) { throw new ErrorPageError( 'notifytranslators', 'translationnotifications-error-no-translatable-pages' ); } $formFields['TranslatablePage'] = [ 'name' => 'tpage', 'type' => 'select', 'label-message' => [ 'translationnotifications-translatablepage-title' ], 'options' => $pages, ]; $contLang = MediaWikiServices::getInstance()->getContentLanguage(); // Dummy dropdown, will be invisible. Used as data source for language name autocompletion. // @todo Implement a proper field with everything needed for this and make this less hackish $languageSelector = Xml::languageSelector( $contLang->getCode(), false, $this->getLanguage()->getCode(), [ 'style' => 'display: none;' ] ); $formFields['LanguagesList'] = [ 'type' => 'info', 'raw' => true, 'default' => $languageSelector[1], ]; // Languages to notify input box $formFields['LanguagesToNotify'] = [ 'type' => 'text', 'rows' => 20, 'cols' => 80, 'label-message' => 'translationnotifications-languages-to-notify-label', 'help-message' => 'translationnotifications-languages-to-notify-label-help-message', ]; // Priority dropdown $priorityOptions = []; $priorities = [ 'unset', 'high', 'medium', 'low' ]; foreach ( $priorities as $priority ) { $priorityMessage = NotificationMessageBuilder::getPriorityMessage( $priority ) ->setContext( $this->getContext() )->text(); $priorityOptions[$priorityMessage] = $priority; } $formFields['Priority'] = [ 'type' => 'select', 'label-message' => [ 'translationnotifications-priority' ], 'options' => $priorityOptions, 'default' => 'unset', ]; // Deadline date input box with datepicker $formFields['DeadlineDate'] = [ 'type' => 'text', 'size' => 20, 'label-message' => 'translationnotifications-deadline-label', ]; // Custom text $formFields['NotificationText'] = [ 'type' => 'textarea', 'rows' => 20, 'cols' => 80, 'label-message' => 'emailmessage', ]; return $formFields; } /** * @return array */ protected function getTranslatablePages() { $translatablePages = MessageGroups::getGroupsByType( 'WikiPageMessageGroup' ); usort( $translatablePages, [ 'MessageGroups', 'groupLabelSort' ] ); $titles = []; // Retrieving article id requires doing DB queries. // Make it more efficient by batching into one query. $lb = new LinkBatch(); /** * @var WikiPageMessageGroup $page */ foreach ( $translatablePages as $page ) { if ( MessageGroups::getPriority( $page ) === 'discouraged' ) { continue; } '@phan-var WikiPageMessageGroup $page'; $title = $page->getTitle(); $lb->addObj( $title ); $titles[] = $title; } $lb->execute(); $translatablePagesOptions = []; foreach ( $titles as $title ) { $translatablePagesOptions[$title->getPrefixedText()] = $title->getArticleID(); } return $translatablePagesOptions; } private function getSourceLanguage() { if ( $this->sourceLanguageCode === '' ) { $translatablePage = TranslatablePage::newFromTitle( $this->translatablePageTitle ); $this->sourceLanguageCode = $translatablePage->getMessageGroup()->getSourceLanguage(); } return $this->sourceLanguageCode; } /** * Callback for the submit button. * * @param array $formData * @return Status|bool * @todo Document */ public function onSubmit( array $formData ) { $this->translatablePageTitle = Title::newFromID( $formData['TranslatablePage'] ); $this->notificationText = $formData['NotificationText']; $this->priority = $formData['Priority']; $this->deadlineDate = $formData['DeadlineDate']; $languagesToNotify = explode( ',', $formData['LanguagesToNotify'] ); $languagesToNotify = array_filter( array_map( 'trim', $languagesToNotify ) ); $pageSourceLangCode = $this->getSourceLanguage(); $notificationLanguages = []; // The default is not to specify any languages and to send the notification to speakers of // all the languages except the source language. When no languages are specified, // an empty string will be sent here and an appropriate message will be shown in the log. if ( count( $languagesToNotify ) ) { // Filter out the source language foreach ( $languagesToNotify as $langCode ) { if ( $langCode !== $pageSourceLangCode ) { $notificationLanguages[] = $langCode; } } if ( $notificationLanguages === [] ) { return Status::newFatal( 'translationnotifications-sourcelang-only' ); } } $requestData = [ 'notificationText' => $this->notificationText, 'priority' => $this->priority, 'languagesToNotify' => $notificationLanguages, 'deadlineDate' => $this->deadlineDate ]; $job = TranslationNotificationsSubmitJob::newJob( $this->translatablePageTitle, $requestData, $this->getUser()->getId(), $this->getLanguage()->getCode() ); MediaWikiServices::getInstance()->getJobQueueGroup()->push( $job ); return true; } public function onSuccess() { $this->getOutput()->addWikiMsg( 'translationnotifications-submit-ok' ); } }
wikimedia/mediawiki-extensions-TranslationNotifications
includes/SpecialNotifyTranslators.php
PHP
gpl-2.0
6,870
<?php /** * Created by JetBrains PhpStorm. * User: gikach * Date: 4/4/13 * Time: 2:41 PM * To change this template use File | Settings | File Templates. */ class QS_Smallinvoice_Model_Receipts_Observer extends Mage_Core_Model_Abstract { protected $_catalogConfig; public function __construct() { parent::__construct(); $this->_catalogConfig = Mage::helper('qs_smallinvoice')->getConfigList(); } protected function _getDataReceipts($invoice) { $customer = Mage::getModel('customer/customer')->reset()->load($invoice->getCustomerId()); $smallInvoiceCustomerId = $customer->getSmallinvoiceCustomerid(); $smallInvoiceMainaddrId = $customer->getSmallinvoiceMainaddrid(); $items = $invoice->getAllItems(); $positions[] = array(); $i=0; foreach ($items as $item) { if($item->getData('parent_item_id')) { //NOTHING TO DO }else{ $positions[$i]['type'] = $this->_catalogConfig['producttype']; $positions[$i]['name'] = $item->getData('name'); $positions[$i]['description'] = $item->getData('description'); $positions[$i]['cost'] = $item->getData('price'); $positions[$i]['unit'] = $this->_catalogConfig['productunit'];// 1 - Hour from configuration, 7-Piece $positions[$i]['amount'] = $item->getData('qty_ordered'); $positions[$i]['vat'] = 0; $positions[$i]['discount'] = ''; $i++; } } $shipping = array( 'type'=>1, 'name'=>'Shipping & Handling', 'description'=>'', 'cost'=>$invoice->getData('shipping_amount'), 'unit'=>$this->_catalogConfig['productunit'], 'amount'=>1, 'vat'=>0, 'discount'=>'' ); $positions[] = $shipping; $tax = array( 'type'=>1, 'name'=>'Tax', 'description'=>'', 'cost'=>$invoice->getData('tax_amount'), 'unit'=>$this->_catalogConfig['productunit'], 'amount'=>1, 'vat'=>0, 'discount'=>'' ); $positions[] = $tax; if(abs($invoice->getData('discount_amount'))>0) { $discount = array( 'type'=>1, 'name'=>'Discount', 'description'=>$invoice->getData('discount_description'), 'cost'=>(0-$invoice->getData('discount_amount')),//must be negative 'unit'=>$this->_catalogConfig['productunit'], 'amount'=>1, 'vat'=>0, 'discount'=>'' ); $positions[] = $discount; } $storeId = $invoice->getStoreId(); $localeCode = Mage::getStoreConfig('general/locale/code', $storeId); $lang = explode('_',$localeCode); $dataReceipts = array( "client_id" => $smallInvoiceCustomerId, "client_address_id" => $smallInvoiceMainaddrId, "currency" => $invoice->getData('order_currency_code'), "title" => $this->_catalogConfig['titlereceipt'], "date" => date('Y-m-d'), "introduction"=>"", "conditions"=>"", "language"=>$lang[0], "vat_included"=>0,//tax_amount "positions"=> $positions ); return $dataReceipts; } public function invoiceSaveAfter(Varien_Event_Observer $observer) { $invoice = $observer->getEvent()->getInvoice(); $dataReceipts = json_encode($this->_getDataReceipts($invoice)); $customerid = $invoice->getCustomerId(); Mage::helper('qs_smallinvoice')->getClient('receipt','add', null, $dataReceipts, null, null, $customerid); } }
miegli/QS_Smallinvoice
app/code/local/QS/Smallinvoice/Model/Receipts/Observer.php
PHP
gpl-2.0
4,217
<?php // $Id$ /** * settingstree.php - Tells the admin menu that there are sub menu pages to * include for this activity. * * @license http://www.gnu.org/copyleft/gpl.html GNU Public License * @package quiz */ require_once($CFG->dirroot . '/mod/quiz/lib.php'); require_once($CFG->dirroot . '/mod/quiz/settingslib.php'); // First get a list of quiz reports with there own settings pages. If there none, // we use a simpler overall menu structure. $reportsbyname = array(); if ($reports = get_list_of_plugins('mod/quiz/report')) { foreach ($reports as $report) { if (file_exists($CFG->dirroot . "/mod/quiz/report/$report/settings.php")) { $strreportname = get_string($report . 'report', 'quiz_'.$report); // Deal with reports which are lacking the language string if ($strreportname[0] == '[') { $textlib = textlib_get_instance(); $strreportname = $textlib->strtotitle($report . ' report'); } $reportsbyname[$strreportname] = $report; } } ksort($reportsbyname); } // Create the quiz settings page. if (empty($reportsbyname)) { $pagetitle = get_string('modulename', 'quiz'); } else { $pagetitle = get_string('generalsettings', 'admin'); } $quizsettings = new admin_settingpage('modsettingquiz', $pagetitle, 'moodle/site:config'); // Introductory explanation that all the settings are defaults for the add quiz form. $quizsettings->add(new admin_setting_heading('quizintro', '', get_string('configintro', 'quiz'))); // Time limit $quizsettings->add(new admin_setting_text_with_advanced('quiz/timelimit', get_string('timelimitsec', 'quiz'), get_string('configtimelimitsec', 'quiz'), array('value' => '0', 'fix' => false), PARAM_INT)); // Number of attempts $options = array(get_string('unlimited')); for ($i = 1; $i <= QUIZ_MAX_ATTEMPT_OPTION; $i++) { $options[$i] = $i; } $quizsettings->add(new admin_setting_combo_with_advanced('quiz/attempts', get_string('attemptsallowed', 'quiz'), get_string('configattemptsallowed', 'quiz'), array('value' => 0, 'fix' => false), $options)); // Grading method. $quizsettings->add(new admin_setting_combo_with_advanced('quiz/grademethod', get_string('grademethod', 'quiz'), get_string('configgrademethod', 'quiz'), array('value' => QUIZ_GRADEHIGHEST, 'fix' => false), quiz_get_grading_options())); // Maximum grade $quizsettings->add(new admin_setting_configtext('quiz/maximumgrade', get_string('maximumgrade'), get_string('configmaximumgrade', 'quiz'), 10, PARAM_INT)); // Shuffle questions $quizsettings->add(new admin_setting_yesno_with_advanced('quiz/shufflequestions', get_string('shufflequestions', 'quiz'), get_string('configshufflequestions', 'quiz'), array('value' => 0, 'fix' => false))); // Questions per page $perpage = array(); $perpage[0] = get_string('never'); $perpage[1] = get_string('aftereachquestion', 'quiz'); for ($i = 2; $i <= QUIZ_MAX_QPP_OPTION; ++$i) { $perpage[$i] = get_string('afternquestions', 'quiz', $i); } $quizsettings->add(new admin_setting_combo_with_advanced('quiz/questionsperpage', get_string('newpageevery', 'quiz'), get_string('confignewpageevery', 'quiz'), array('value' => 1, 'fix' => false), $perpage)); // Shuffle within questions $quizsettings->add(new admin_setting_yesno_with_advanced('quiz/shuffleanswers', get_string('shufflewithin', 'quiz'), get_string('configshufflewithin', 'quiz'), array('value' => 1, 'fix' => false))); // Adaptive mode. $quizsettings->add(new admin_setting_yesno_with_advanced('quiz/optionflags', get_string('adaptive', 'quiz'), get_string('configadaptive', 'quiz'), array('value' => 1, 'fix' => false))); // Apply penalties. $quizsettings->add(new admin_setting_yesno_with_advanced('quiz/penaltyscheme', get_string('penaltyscheme', 'quiz'), get_string('configpenaltyscheme', 'quiz'), array('value' => 1, 'fix' => true))); // Each attempt builds on last. $quizsettings->add(new admin_setting_yesno_with_advanced('quiz/attemptonlast', get_string('eachattemptbuildsonthelast', 'quiz'), get_string('configeachattemptbuildsonthelast', 'quiz'), array('value' => 0, 'fix' => true))); // Review options. $quizsettings->add(new admin_setting_quiz_reviewoptions('quiz/review', get_string('reviewoptions', 'quiz'), get_string('configreviewoptions', 'quiz'), array('value' => QUIZ_REVIEW_IMMEDIATELY | QUIZ_REVIEW_OPEN | QUIZ_REVIEW_CLOSED, 'fix' => false))); // Show the user's picture $quizsettings->add(new admin_setting_yesno_with_advanced('quiz/showuserpicture', get_string('showuserpicture', 'quiz'), get_string('configshowuserpicture', 'quiz'), array('value' => 0, 'fix' => false))); // Decimal places for overall grades. $options = array(); for ($i = 0; $i <= QUIZ_MAX_DECIMAL_OPTION; $i++) { $options[$i] = $i; } $quizsettings->add(new admin_setting_combo_with_advanced('quiz/decimalpoints', get_string('decimalplaces', 'quiz'), get_string('configdecimalplaces', 'quiz'), array('value' => 2, 'fix' => false), $options)); // Decimal places for question grades. $options = array(-1 => get_string('sameasoverall', 'quiz')); for ($i = 0; $i <= QUIZ_MAX_Q_DECIMAL_OPTION; $i++) { $options[$i] = $i; } $quizsettings->add(new admin_setting_combo_with_advanced('quiz/questiondecimalpoints', get_string('decimalplacesquestion', 'quiz'), get_string('configdecimalplacesquestion', 'quiz'), array('value' => -1, 'fix' => true), $options)); // Password. $quizsettings->add(new admin_setting_text_with_advanced('quiz/password', get_string('requirepassword', 'quiz'), get_string('configrequirepassword', 'quiz'), array('value' => '', 'fix' => true), PARAM_TEXT)); // IP restrictions. $quizsettings->add(new admin_setting_text_with_advanced('quiz/subnet', get_string('requiresubnet', 'quiz'), get_string('configrequiresubnet', 'quiz'), array('value' => '', 'fix' => true), PARAM_TEXT)); // Enforced delay between attempts. $quizsettings->add(new admin_setting_text_with_advanced('quiz/delay1', get_string('delay1st2nd', 'quiz'), get_string('configdelay1st2nd', 'quiz'), array('value' => 0, 'fix' => true), PARAM_INTEGER)); $quizsettings->add(new admin_setting_text_with_advanced('quiz/delay2', get_string('delaylater', 'quiz'), get_string('configdelaylater', 'quiz'), array('value' => 0, 'fix' => true), PARAM_INTEGER)); // 'Secure' window. $quizsettings->add(new admin_setting_yesno_with_advanced('quiz/popup', get_string('showinsecurepopup', 'quiz'), get_string('configpopup', 'quiz'), array('value' => 0, 'fix' => true))); /// Now, depending on whether any reports have their own settings page, add /// the quiz setting page to the appropriate place in the tree. if (empty($reportsbyname)) { $ADMIN->add('modsettings', $quizsettings); } else { $ADMIN->add('modsettings', new admin_category('modsettingsquizcat', get_string('modulename', 'quiz'), !$module->visible)); $ADMIN->add('modsettingsquizcat', $quizsettings); /// Add the report pages for the settings.php files in sub directories of mod/quiz/report foreach ($reportsbyname as $strreportname => $report) { $reportname = $report; $settings = new admin_settingpage('modsettingsquizcat'.$reportname, $strreportname, 'moodle/site:config', !$module->visible); if ($ADMIN->fulltree) { include($CFG->dirroot."/mod/quiz/report/$reportname/settings.php"); } $ADMIN->add('modsettingsquizcat', $settings); } }
cwaclawik/moodle
mod/quiz/settingstree.php
PHP
gpl-2.0
7,689
var isc_nb = 0; jQuery(function(){ /** * Hide/Show image list when post/page is loaded */ jQuery('.isc_image_list_title').click(function(){ isc_list = jQuery('.isc_image_list'); if ( isc_list.hasClass('isc-list-up') ) { jQuery('.isc_image_list_title').attr('title', (isc_jstext['hide_list'])); isc_list.toggleClass('isc-list-up isc-list-down'); isc_list.css({ visibility: 'hidden', height: '100%', }); max = isc_list.height(); isc_list.css({ height: '0px', visibility: 'visible' }).animate( {height: max + 'px'}, 1500 ); } else { jQuery('.isc_image_list_title').attr('title', (isc_jstext['show_list'])); isc_list.toggleClass('isc-list-up isc-list-down'); isc_list.animate( {height: 0}, 1500 ); } }); /** * Move caption into image */ jQuery('.isc-source').each(function(){ var main_id = jQuery(this).attr('id'); var att_number = main_id.split('_')[2]; var caption = jQuery(this).children().filter('.isc-source-text').html(); jQuery(this).find('.isc-source-text').remove(); jQuery(this).append(jQuery('<span />').addClass('isc-source-text').html(caption).css({ position: 'absolute', fontSize: '0.9em', backgroundColor: "#333", color: "#fff", opacity: "0.70", padding: '0 0.15em', textShadow: 'none', })); // Some themes handle the bottom padding of the attachment's div with the caption text (which is in between // the image and the bottom border) not with the div itself. The following line set the padding on the bottom equal to the top. jQuery(this).css('padding-bottom', jQuery(this).css('padding-top')); isc_update_captions_positions(); }); jQuery(window).resize(function(){ isc_update_captions_positions(); }); jQuery('.isc-source img').load(function(){ isc_update_captions_positions(); }); }); function isc_update_captions_positions() { jQuery('.isc-source').each(function(){ isc_update_caption_position(jQuery(this)); }); } function isc_update_caption_position(jQ_Obj) { var main_id = jQ_Obj.attr('id'); var att_number = main_id.split('_')[2]; var att = jQ_Obj.find('.wp-image-' + att_number); var attw = att.width(); var atth = att.height(); //relative position var l = att.position().left; //relative position var t = att.position().top; var caption = jQ_Obj.find('.isc-source-text'); //caption width + padding & margin (after moving onto image) var tw = caption.outerWidth(true); //caption height + padding (idem) var th = caption.outerHeight(true); var attpl = parseInt(att.css('padding-left').substring(0, att.css('padding-left').indexOf('px'))); var attml = parseInt(att.css('margin-left').substring(0, att.css('margin-left').indexOf('px'))); var attpt = parseInt(att.css('padding-top').substring(0, att.css('padding-top').indexOf('px'))); var attmt = parseInt(att.css('margin-top').substring(0, att.css('margin-top').indexOf('px'))); //caption horizontal margin var tml = 5; //caption vertical margin var tmt = 5; var pos = isc_front_data.caption_position; var posl = 0; var post = 0; switch (pos) { case 'top-left': posl = l + attpl + attml + tml; post = t + attpt + attmt + tmt; break; case 'top-center': posl = l + (Math.round(attw/2) - (Math.round(tw/2))) + attpl + attml; post = t + attpt + attmt + tmt; break; case 'top-right': posl = l - attpl + attml - tml + attw - tw; post = t + attpt + attmt + tmt; break; case 'center': posl = l + (Math.round(attw/2) - (Math.round(tw/2))) + attpl + attml; post = t + (Math.round(atth/2) - (Math.round(th/2))) + attpt + attmt; break; case 'bottom-left': posl = l + attpl + attml + tml; post = t - attpt + attmt - tmt - th + atth; break; case 'bottom-center': posl = l + (Math.round(attw/2) - (Math.round(tw/2))) + attpl + attml; post = t + attpt + attmt - tmt - th + atth; break; case 'bottom-right': posl = l - attpl + attml - tml + attw - tw; post = t + attpt + attmt - tmt - th + atth; break; } caption.css({ left: posl + 'px', top: post + 'px', zIndex: 9999, }); }
JornalExtraClasse/wordpress
wp-content/plugins/image-source-control-isc/js/front-js.js
JavaScript
gpl-2.0
4,876
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2021 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } */ #ifndef XCSOAR_DEVICE_ENUMERATOR_HPP #define XCSOAR_DEVICE_ENUMERATOR_HPP #include <dirent.h> /** * A class that can enumerate TTY devices on Linux and other POSIX * systems, by reading directory entries in /dev/. */ class TTYEnumerator { DIR *dir; char path[64]; public: #ifdef __linux__ /* on Linux, enumerate /sys/class/tty/ which is faster than /dev/ (searches only the TTY character devices) and shows only the ports that really exist */ /* but use /dev because there is no noticable downside, and it * allows for custom port mapping using udev file */ TTYEnumerator() :dir(opendir("/dev")) {} #else TTYEnumerator() :dir(opendir("/dev")) {} #endif ~TTYEnumerator() { if (dir != nullptr) closedir(dir); } /** * Has the constructor failed? */ bool HasFailed() const { return dir == nullptr; } /** * Find the next device (or the first one, if this method hasn't * been called so far). * * @return the absolute path of the device, or nullptr if there are * no more devices */ const char *Next(); }; #endif
sandrinr/XCSoar
src/Device/Port/TTYEnumerator.hpp
C++
gpl-2.0
2,005
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE TS> <TS version="2.0"> <context> <name>AboutDialog</name> <message> <source>About LMMS</source> <translation type="unfinished"></translation> </message> <message> <source>Version %1 (%2/%3, Qt %4, %5)</source> <translation type="unfinished"></translation> </message> <message> <source>About</source> <translation type="unfinished">درباره</translation> </message> <message> <source>LMMS - easy music production for everyone</source> <translation type="unfinished"></translation> </message> <message> <source>Authors</source> <translation type="unfinished"></translation> </message> <message> <source>Translation</source> <translation type="unfinished"></translation> </message> <message> <source>Current language not translated (or native English). If you&apos;re interested in translating LMMS in another language or want to improve existing translations, you&apos;re welcome to help us! Simply contact the maintainer!</source> <translation type="unfinished"></translation> </message> <message> <source>License</source> <translation type="unfinished"></translation> </message> <message> <source>Copyright (c) 2004-2014, LMMS developers</source> <translation type="unfinished"></translation> </message> <message> <source>&lt;html&gt;&lt;head/&gt;&lt;body&gt;&lt;p&gt;&lt;a href=&quot;http://lmms.io&quot;&gt;&lt;span style=&quot; text-decoration: underline; color:#0000ff;&quot;&gt;http://lmms.io&lt;/span&gt;&lt;/a&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>LMMS</source> <translation type="unfinished"></translation> </message> <message> <source>Involved</source> <translation type="unfinished"></translation> </message> <message> <source>Contributors ordered by number of commits:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AmplifierControlDialog</name> <message> <source>VOL</source> <translation type="unfinished"></translation> </message> <message> <source>Volume:</source> <translation type="unfinished"></translation> </message> <message> <source>PAN</source> <translation type="unfinished"></translation> </message> <message> <source>Panning:</source> <translation type="unfinished"></translation> </message> <message> <source>LEFT</source> <translation type="unfinished"></translation> </message> <message> <source>Left gain:</source> <translation type="unfinished"></translation> </message> <message> <source>RIGHT</source> <translation type="unfinished"></translation> </message> <message> <source>Right gain:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AmplifierControls</name> <message> <source>Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Panning</source> <translation type="unfinished"></translation> </message> <message> <source>Left gain</source> <translation type="unfinished"></translation> </message> <message> <source>Right gain</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AudioAlsa::setupWidget</name> <message> <source>DEVICE</source> <translation type="unfinished"></translation> </message> <message> <source>CHANNELS</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AudioFileProcessorView</name> <message> <source>Open other sample</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to open another audio-file. A dialog will appear where you can select your file. Settings like looping-mode, start and end-points, amplify-value, and so on are not reset. So, it may not sound like the original sample.</source> <translation type="unfinished"></translation> </message> <message> <source>Reverse sample</source> <translation type="unfinished"></translation> </message> <message> <source>If you enable this button, the whole sample is reversed. This is useful for cool effects, e.g. a reversed crash.</source> <translation type="unfinished">اگر این دکمه را فعال کنید,تمام نمونه معکوس می شود.این برای جلوه های جالب مانند یک تصادف معکوس مناسب است.</translation> </message> <message> <source>Amplify:</source> <translation type="unfinished">تقویت:</translation> </message> <message> <source>With this knob you can set the amplify ratio. When you set a value of 100% your sample isn&apos;t changed. Otherwise it will be amplified up or down (your actual sample-file isn&apos;t touched!)</source> <translation type="unfinished"></translation> </message> <message> <source>Startpoint:</source> <translation type="unfinished">نقطه ی شروع:</translation> </message> <message> <source>Endpoint:</source> <translation type="unfinished">نقطه ی پایان:</translation> </message> <message> <source>Continue sample playback across notes</source> <translation type="unfinished"></translation> </message> <message> <source>Enabling this option makes the sample continue playing across different notes - if you change pitch, or the note length stops before the end of the sample, then the next note played will continue where it left off. To reset the playback to the start of the sample, insert a note at the bottom of the keyboard (&lt; 20 Hz)</source> <translation type="unfinished"></translation> </message> <message> <source>Disable loop</source> <translation type="unfinished"></translation> </message> <message> <source>This button disables looping. The sample plays only once from start to end. </source> <translation type="unfinished"></translation> </message> <message> <source>Enable loop</source> <translation type="unfinished"></translation> </message> <message> <source>This button enables forwards-looping. The sample loops between the end point and the loop point.</source> <translation type="unfinished"></translation> </message> <message> <source>This button enables ping-pong-looping. The sample loops backwards and forwards between the end point and the loop point.</source> <translation type="unfinished"></translation> </message> <message> <source>With this knob you can set the point where AudioFileProcessor should begin playing your sample. </source> <translation type="unfinished"></translation> </message> <message> <source>With this knob you can set the point where AudioFileProcessor should stop playing your sample. </source> <translation type="unfinished"></translation> </message> <message> <source>Loopback point:</source> <translation type="unfinished"></translation> </message> <message> <source>With this knob you can set the point where the loop starts. </source> <translation type="unfinished"></translation> </message> </context> <context> <name>AudioFileProcessorWaveView</name> <message> <source>Sample length:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AudioJack</name> <message> <source>JACK client restarted</source> <translation type="unfinished"></translation> </message> <message> <source>LMMS was kicked by JACK for some reason. Therefore the JACK backend of LMMS has been restarted. You will have to make manual connections again.</source> <translation type="unfinished"></translation> </message> <message> <source>JACK server down</source> <translation type="unfinished"></translation> </message> <message> <source>The JACK server seems to have been shutdown and starting a new instance failed. Therefore LMMS is unable to proceed. You should save your project and restart JACK and LMMS.</source> <translation type="unfinished"></translation> </message> <message> <source>CLIENT-NAME</source> <translation type="unfinished"></translation> </message> <message> <source>CHANNELS</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AudioOss::setupWidget</name> <message> <source>DEVICE</source> <translation type="unfinished"></translation> </message> <message> <source>CHANNELS</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AudioPortAudio::setupWidget</name> <message> <source>BACKEND</source> <translation type="unfinished"></translation> </message> <message> <source>DEVICE</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AudioPulseAudio::setupWidget</name> <message> <source>DEVICE</source> <translation type="unfinished"></translation> </message> <message> <source>CHANNELS</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AudioSdl::setupWidget</name> <message> <source>DEVICE</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AutomatableModel</name> <message> <source>&amp;Reset (%1%2)</source> <translation type="unfinished">&amp;باز نشانی (%1%2)</translation> </message> <message> <source>&amp;Copy value (%1%2)</source> <translation type="unfinished">کپی &amp;مقدار (%1%2)</translation> </message> <message> <source>&amp;Paste value (%1%2)</source> <translation type="unfinished">چسباندن &amp;مقدار (%1%2)</translation> </message> <message> <source>Edit song-global automation</source> <translation type="unfinished"></translation> </message> <message> <source>Connected to %1</source> <translation type="unfinished"></translation> </message> <message> <source>Connected to controller</source> <translation type="unfinished"></translation> </message> <message> <source>Edit connection...</source> <translation type="unfinished"></translation> </message> <message> <source>Remove connection</source> <translation type="unfinished"></translation> </message> <message> <source>Connect to controller...</source> <translation type="unfinished"></translation> </message> <message> <source>Remove song-global automation</source> <translation type="unfinished"></translation> </message> <message> <source>Remove all linked controls</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AutomationEditor</name> <message> <source>Please open an automation pattern with the context menu of a control!</source> <translation type="unfinished"></translation> </message> <message> <source>Values copied</source> <translation type="unfinished"></translation> </message> <message> <source>All selected values were copied to the clipboard.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AutomationEditorWindow</name> <message> <source>Play/pause current pattern (Space)</source> <translation type="unfinished">پخش/مکث الگوی جاری (فاصله)</translation> </message> <message> <source>Click here if you want to play the current pattern. This is useful while editing it. The pattern is automatically looped when the end is reached.</source> <translation type="unfinished"></translation> </message> <message> <source>Stop playing of current pattern (Space)</source> <translation type="unfinished">توقف پخش الگوی جاری (فاصله)</translation> </message> <message> <source>Click here if you want to stop playing of the current pattern.</source> <translation type="unfinished"></translation> </message> <message> <source>Draw mode (Shift+D)</source> <translation type="unfinished"></translation> </message> <message> <source>Erase mode (Shift+E)</source> <translation type="unfinished"></translation> </message> <message> <source>Flip vertically</source> <translation type="unfinished"></translation> </message> <message> <source>Flip horizontally</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and the pattern will be inverted.The points are flipped in the y direction. </source> <translation type="unfinished"></translation> </message> <message> <source>Click here and the pattern will be reversed. The points are flipped in the x direction.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and draw-mode will be activated. In this mode you can add and move single values. This is the default mode which is used most of the time. You can also press &apos;Shift+D&apos; on your keyboard to activate this mode.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and erase-mode will be activated. In this mode you can erase single values. You can also press &apos;Shift+E&apos; on your keyboard to activate this mode.</source> <translation type="unfinished"></translation> </message> <message> <source>Discrete progression</source> <translation type="unfinished"></translation> </message> <message> <source>Linear progression</source> <translation type="unfinished"></translation> </message> <message> <source>Cubic Hermite progression</source> <translation type="unfinished"></translation> </message> <message> <source>Tension value for spline</source> <translation type="unfinished"></translation> </message> <message> <source>A higher tension value may make a smoother curve but overshoot some values. A low tension value will cause the slope of the curve to level off at each control point.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to choose discrete progressions for this automation pattern. The value of the connected object will remain constant between control points and be set immediately to the new value when each control point is reached.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to choose linear progressions for this automation pattern. The value of the connected object will change at a steady rate over time between control points to reach the correct value at each control point without a sudden change.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to choose cubic hermite progressions for this automation pattern. The value of the connected object will change in a smooth curve and ease in to the peaks and valleys.</source> <translation type="unfinished"></translation> </message> <message> <source>Cut selected values (Ctrl+X)</source> <translation type="unfinished"></translation> </message> <message> <source>Copy selected values (Ctrl+C)</source> <translation type="unfinished"></translation> </message> <message> <source>Paste values from clipboard Ctrl+V)</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and selected values will be cut into the clipboard. You can paste them anywhere in any pattern by clicking on the paste button.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and selected values will be copied into the clipboard. You can paste them anywhere in any pattern by clicking on the paste button.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and the values from the clipboard will be pasted at the first visible measure.</source> <translation type="unfinished"></translation> </message> <message> <source>Tension: </source> <translation type="unfinished"></translation> </message> <message> <source>Automation Editor - no pattern</source> <translation type="unfinished"></translation> </message> <message> <source>Automation Editor - %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AutomationPattern</name> <message> <source>Drag a control while pressing &lt;Ctrl&gt;</source> <translation type="unfinished"></translation> </message> <message> <source>Model is already connected to this pattern.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AutomationPatternView</name> <message> <source>double-click to open this pattern in automation editor</source> <translation type="unfinished"></translation> </message> <message> <source>Open in Automation editor</source> <translation type="unfinished"></translation> </message> <message> <source>Clear</source> <translation type="unfinished"></translation> </message> <message> <source>Reset name</source> <translation type="unfinished">باز نشانی نام</translation> </message> <message> <source>Change name</source> <translation type="unfinished">تغییر نام</translation> </message> <message> <source>%1 Connections</source> <translation type="unfinished"></translation> </message> <message> <source>Disconnect &quot;%1&quot;</source> <translation type="unfinished"></translation> </message> <message> <source>Set/clear record</source> <translation type="unfinished"></translation> </message> <message> <source>Flip Vertically (Visible)</source> <translation type="unfinished"></translation> </message> <message> <source>Flip Horizontally (Visible)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>AutomationTrack</name> <message> <source>Automation track</source> <translation type="unfinished"></translation> </message> </context> <context> <name>BBEditor</name> <message> <source>Beat+Bassline Editor</source> <translation type="unfinished">ویرایشگر خط-بم/تپش</translation> </message> <message> <source>Play/pause current beat/bassline (Space)</source> <translation type="unfinished">پخش/درنگ خط-بم/تپش جاری(فاصله)</translation> </message> <message> <source>Stop playback of current beat/bassline (Space)</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to play the current beat/bassline. The beat/bassline is automatically looped when its end is reached.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to stop playing of current beat/bassline.</source> <translation type="unfinished"></translation> </message> <message> <source>Add beat/bassline</source> <translation type="unfinished">اضافه ی خط بم/تپش (beat/baseline)</translation> </message> <message> <source>Add automation-track</source> <translation type="unfinished"></translation> </message> <message> <source>Remove steps</source> <translation type="unfinished"></translation> </message> <message> <source>Add steps</source> <translation type="unfinished"></translation> </message> </context> <context> <name>BBTCOView</name> <message> <source>Open in Beat+Bassline-Editor</source> <translation type="unfinished">در ویرایشگر خط-بم/تپش باز کن</translation> </message> <message> <source>Reset name</source> <translation type="unfinished">باز نشانی نام</translation> </message> <message> <source>Change name</source> <translation type="unfinished">تغییر نام</translation> </message> <message> <source>Change color</source> <translation type="unfinished">تغییر رنگ</translation> </message> <message> <source>Reset color to default</source> <translation type="unfinished"></translation> </message> </context> <context> <name>BBTrack</name> <message> <source>Beat/Bassline %1</source> <translation type="unfinished">خط-بم/تپش %1</translation> </message> <message> <source>Clone of %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>BassBoosterControlDialog</name> <message> <source>FREQ</source> <translation type="unfinished"></translation> </message> <message> <source>Frequency:</source> <translation type="unfinished"></translation> </message> <message> <source>GAIN</source> <translation type="unfinished"></translation> </message> <message> <source>Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>RATIO</source> <translation type="unfinished"></translation> </message> <message> <source>Ratio:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>BassBoosterControls</name> <message> <source>Frequency</source> <translation type="unfinished"></translation> </message> <message> <source>Gain</source> <translation type="unfinished"></translation> </message> <message> <source>Ratio</source> <translation type="unfinished"></translation> </message> </context> <context> <name>BitcrushControlDialog</name> <message> <source>IN</source> <translation type="unfinished"></translation> </message> <message> <source>OUT</source> <translation type="unfinished"></translation> </message> <message> <source>GAIN</source> <translation type="unfinished"></translation> </message> <message> <source>Input Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>NOIS</source> <translation type="unfinished"></translation> </message> <message> <source>Input Noise:</source> <translation type="unfinished"></translation> </message> <message> <source>Output Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>CLIP</source> <translation type="unfinished"></translation> </message> <message> <source>Output Clip:</source> <translation type="unfinished"></translation> </message> <message> <source>Rate</source> <translation type="unfinished"></translation> </message> <message> <source>Rate Enabled</source> <translation type="unfinished"></translation> </message> <message> <source>Enable samplerate-crushing</source> <translation type="unfinished"></translation> </message> <message> <source>Depth</source> <translation type="unfinished"></translation> </message> <message> <source>Depth Enabled</source> <translation type="unfinished"></translation> </message> <message> <source>Enable bitdepth-crushing</source> <translation type="unfinished"></translation> </message> <message> <source>Sample rate:</source> <translation type="unfinished"></translation> </message> <message> <source>STD</source> <translation type="unfinished"></translation> </message> <message> <source>Stereo difference:</source> <translation type="unfinished"></translation> </message> <message> <source>Levels</source> <translation type="unfinished"></translation> </message> <message> <source>Levels:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>CaptionMenu</name> <message> <source>&amp;Help</source> <translation type="unfinished">&amp;راهنما</translation> </message> <message> <source>Help (not available)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>CarlaInstrumentView</name> <message> <source>Show GUI</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to show or hide the graphical user interface (GUI) of Carla.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Controller</name> <message> <source>Controller %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ControllerConnectionDialog</name> <message> <source>Connection Settings</source> <translation type="unfinished"></translation> </message> <message> <source>MIDI CONTROLLER</source> <translation type="unfinished"></translation> </message> <message> <source>Input channel</source> <translation type="unfinished"></translation> </message> <message> <source>CHANNEL</source> <translation type="unfinished"></translation> </message> <message> <source>Input controller</source> <translation type="unfinished"></translation> </message> <message> <source>CONTROLLER</source> <translation type="unfinished"></translation> </message> <message> <source>Auto Detect</source> <translation type="unfinished"></translation> </message> <message> <source>MIDI-devices to receive MIDI-events from</source> <translation type="unfinished"></translation> </message> <message> <source>USER CONTROLLER</source> <translation type="unfinished"></translation> </message> <message> <source>MAPPING FUNCTION</source> <translation type="unfinished"></translation> </message> <message> <source>OK</source> <translation type="unfinished"></translation> </message> <message> <source>Cancel</source> <translation type="unfinished">لغو</translation> </message> <message> <source>LMMS</source> <translation type="unfinished"></translation> </message> <message> <source>Cycle Detected.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ControllerRackView</name> <message> <source>Controller Rack</source> <translation type="unfinished"></translation> </message> <message> <source>Add</source> <translation type="unfinished"></translation> </message> <message> <source>Confirm Delete</source> <translation type="unfinished"></translation> </message> <message> <source>Confirm delete? There are existing connection(s) associted with this controller. There is no way to undo.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ControllerView</name> <message> <source>Controls</source> <translation type="unfinished"></translation> </message> <message> <source>Controllers are able to automate the value of a knob, slider, and other controls.</source> <translation type="unfinished"></translation> </message> <message> <source>Rename controller</source> <translation type="unfinished"></translation> </message> <message> <source>Enter the new name for this controller</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Remove this plugin</source> <translation type="unfinished"></translation> </message> </context> <context> <name>CrossoverEQControlDialog</name> <message> <source>Band 1/2 Crossover:</source> <translation type="unfinished"></translation> </message> <message> <source>Band 2/3 Crossover:</source> <translation type="unfinished"></translation> </message> <message> <source>Band 3/4 Crossover:</source> <translation type="unfinished"></translation> </message> <message> <source>Band 1 Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>Band 2 Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>Band 3 Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>Band 4 Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>Band 1 Mute</source> <translation type="unfinished"></translation> </message> <message> <source>Mute Band 1</source> <translation type="unfinished"></translation> </message> <message> <source>Band 2 Mute</source> <translation type="unfinished"></translation> </message> <message> <source>Mute Band 2</source> <translation type="unfinished"></translation> </message> <message> <source>Band 3 Mute</source> <translation type="unfinished"></translation> </message> <message> <source>Mute Band 3</source> <translation type="unfinished"></translation> </message> <message> <source>Band 4 Mute</source> <translation type="unfinished"></translation> </message> <message> <source>Mute Band 4</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DelayControls</name> <message> <source>Delay Samples</source> <translation type="unfinished"></translation> </message> <message> <source>Feedback</source> <translation type="unfinished"></translation> </message> <message> <source>Lfo Frequency</source> <translation type="unfinished"></translation> </message> <message> <source>Lfo Amount</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DelayControlsDialog</name> <message> <source>Delay</source> <translation type="unfinished"></translation> </message> <message> <source>Delay Time</source> <translation type="unfinished"></translation> </message> <message> <source>Regen</source> <translation type="unfinished"></translation> </message> <message> <source>Feedback Amount</source> <translation type="unfinished"></translation> </message> <message> <source>Rate</source> <translation type="unfinished"></translation> </message> <message> <source>Lfo</source> <translation type="unfinished"></translation> </message> <message> <source>Lfo Amt</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DetuningHelper</name> <message> <source>Note detuning</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DualFilterControlDialog</name> <message> <source>Filter 1 enabled</source> <translation type="unfinished"></translation> </message> <message> <source>Filter 2 enabled</source> <translation type="unfinished"></translation> </message> <message> <source>Click to enable/disable Filter 1</source> <translation type="unfinished"></translation> </message> <message> <source>Click to enable/disable Filter 2</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DualFilterControls</name> <message> <source>Filter 1 enabled</source> <translation type="unfinished"></translation> </message> <message> <source>Filter 1 type</source> <translation type="unfinished"></translation> </message> <message> <source>Cutoff 1 frequency</source> <translation type="unfinished"></translation> </message> <message> <source>Q/Resonance 1</source> <translation type="unfinished"></translation> </message> <message> <source>Gain 1</source> <translation type="unfinished"></translation> </message> <message> <source>Mix</source> <translation type="unfinished"></translation> </message> <message> <source>Filter 2 enabled</source> <translation type="unfinished"></translation> </message> <message> <source>Filter 2 type</source> <translation type="unfinished"></translation> </message> <message> <source>Cutoff 2 frequency</source> <translation type="unfinished"></translation> </message> <message> <source>Q/Resonance 2</source> <translation type="unfinished"></translation> </message> <message> <source>Gain 2</source> <translation type="unfinished"></translation> </message> <message> <source>LowPass</source> <translation type="unfinished">پایین گذر</translation> </message> <message> <source>HiPass</source> <translation type="unfinished">بالا گذر</translation> </message> <message> <source>BandPass csg</source> <translation type="unfinished">میان گذر csg</translation> </message> <message> <source>BandPass czpg</source> <translation type="unfinished">میان گذر czpg</translation> </message> <message> <source>Notch</source> <translation type="unfinished">نچ</translation> </message> <message> <source>Allpass</source> <translation type="unfinished">تمام گذر</translation> </message> <message> <source>Moog</source> <translation type="unfinished">موگ Moog</translation> </message> <message> <source>2x LowPass</source> <translation type="unfinished">پایین گذر 2x</translation> </message> <message> <source>RC LowPass 12dB</source> <translation type="unfinished"></translation> </message> <message> <source>RC BandPass 12dB</source> <translation type="unfinished"></translation> </message> <message> <source>RC HighPass 12dB</source> <translation type="unfinished"></translation> </message> <message> <source>RC LowPass 24dB</source> <translation type="unfinished"></translation> </message> <message> <source>RC BandPass 24dB</source> <translation type="unfinished"></translation> </message> <message> <source>RC HighPass 24dB</source> <translation type="unfinished"></translation> </message> <message> <source>Vocal Formant Filter</source> <translation type="unfinished"></translation> </message> <message> <source>2x Moog</source> <translation type="unfinished"></translation> </message> <message> <source>SV LowPass</source> <translation type="unfinished"></translation> </message> <message> <source>SV BandPass</source> <translation type="unfinished"></translation> </message> <message> <source>SV HighPass</source> <translation type="unfinished"></translation> </message> <message> <source>SV Notch</source> <translation type="unfinished"></translation> </message> <message> <source>Fast Formant</source> <translation type="unfinished"></translation> </message> <message> <source>Tripole</source> <translation type="unfinished"></translation> </message> </context> <context> <name>DummyEffect</name> <message> <source>NOT FOUND</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Editor</name> <message> <source>Play (Space)</source> <translation type="unfinished"></translation> </message> <message> <source>Stop (Space)</source> <translation type="unfinished"></translation> </message> <message> <source>Record</source> <translation type="unfinished"></translation> </message> <message> <source>Record while playing</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Effect</name> <message> <source>Effect enabled</source> <translation type="unfinished"></translation> </message> <message> <source>Wet/Dry mix</source> <translation type="unfinished"></translation> </message> <message> <source>Gate</source> <translation type="unfinished">مدخل</translation> </message> <message> <source>Decay</source> <translation type="unfinished"></translation> </message> </context> <context> <name>EffectChain</name> <message> <source>Effects enabled</source> <translation type="unfinished"></translation> </message> </context> <context> <name>EffectRackView</name> <message> <source>EFFECTS CHAIN</source> <translation type="unfinished"></translation> </message> <message> <source>Add effect</source> <translation type="unfinished"></translation> </message> </context> <context> <name>EffectSelectDialog</name> <message> <source>Add effect</source> <translation type="unfinished"></translation> </message> <message> <source>Plugin description</source> <translation type="unfinished"></translation> </message> </context> <context> <name>EffectView</name> <message> <source>Toggles the effect on or off.</source> <translation type="unfinished"></translation> </message> <message> <source>On/Off</source> <translation type="unfinished"></translation> </message> <message> <source>W/D</source> <translation type="unfinished"></translation> </message> <message> <source>Wet Level:</source> <translation type="unfinished"></translation> </message> <message> <source>The Wet/Dry knob sets the ratio between the input signal and the effect signal that forms the output.</source> <translation type="unfinished"></translation> </message> <message> <source>DECAY</source> <translation type="unfinished">محو-DECAY</translation> </message> <message> <source>Time:</source> <translation type="unfinished"></translation> </message> <message> <source>The Decay knob controls how many buffers of silence must pass before the plugin stops processing. Smaller values will reduce the CPU overhead but run the risk of clipping the tail on delay and reverb effects.</source> <translation type="unfinished"></translation> </message> <message> <source>GATE</source> <translation type="unfinished"></translation> </message> <message> <source>Gate:</source> <translation type="unfinished"></translation> </message> <message> <source>The Gate knob controls the signal level that is considered to be &apos;silence&apos; while deciding when to stop processing signals.</source> <translation type="unfinished"></translation> </message> <message> <source>Controls</source> <translation type="unfinished"></translation> </message> <message> <source>Effect plugins function as a chained series of effects where the signal will be processed from top to bottom. The On/Off switch allows you to bypass a given plugin at any point in time. The Wet/Dry knob controls the balance between the input signal and the effected signal that is the resulting output from the effect. The input for the stage is the output from the previous stage. So, the &apos;dry&apos; signal for effects lower in the chain contains all of the previous effects. The Decay knob controls how long the signal will continue to be processed after the notes have been released. The effect will stop processing signals when the volume has dropped below a given threshold for a given length of time. This knob sets the &apos;given length of time&apos;. Longer times will require more CPU, so this number should be set low for most effects. It needs to be bumped up for effects that produce lengthy periods of silence, e.g. delays. The Gate knob controls the &apos;given threshold&apos; for the effect&apos;s auto shutdown. The clock for the &apos;given length of time&apos; will begin as soon as the processed signal level drops below the level specified with this knob. The Controls button opens a dialog for editing the effect&apos;s parameters. Right clicking will bring up a context menu where you can change the order in which the effects are processed or delete an effect altogether.</source> <translation type="unfinished"></translation> </message> <message> <source>Move &amp;up</source> <translation type="unfinished"></translation> </message> <message> <source>Move &amp;down</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Remove this plugin</source> <translation type="unfinished"></translation> </message> </context> <context> <name>EnvelopeAndLfoParameters</name> <message> <source>Predelay</source> <translation type="unfinished"></translation> </message> <message> <source>Attack</source> <translation type="unfinished"></translation> </message> <message> <source>Hold</source> <translation type="unfinished"></translation> </message> <message> <source>Decay</source> <translation type="unfinished"></translation> </message> <message> <source>Sustain</source> <translation type="unfinished"></translation> </message> <message> <source>Release</source> <translation type="unfinished"></translation> </message> <message> <source>Modulation</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Predelay</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Attack</source> <translation type="unfinished"></translation> </message> <message> <source>LFO speed</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Modulation</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Wave Shape</source> <translation type="unfinished"></translation> </message> <message> <source>Freq x 100</source> <translation type="unfinished"></translation> </message> <message> <source>Modulate Env-Amount</source> <translation type="unfinished"></translation> </message> </context> <context> <name>EnvelopeAndLfoView</name> <message> <source>DEL</source> <translation type="unfinished"></translation> </message> <message> <source>Predelay:</source> <translation type="unfinished">پبش تاخیر(Predelay):</translation> </message> <message> <source>Use this knob for setting predelay of the current envelope. The bigger this value the longer the time before start of actual envelope.</source> <translation type="unfinished">از این دستگیره برای تنظیم پیش تاخیر پاکت جاری استفاده کنید.هرچه این مقدار بیشتر باشد زمان بیشتری قبل از شروع واقعی پاکت طول می کشد.</translation> </message> <message> <source>ATT</source> <translation type="unfinished"></translation> </message> <message> <source>Attack:</source> <translation type="unfinished">تهاجم(Attack):</translation> </message> <message> <source>Use this knob for setting attack-time of the current envelope. The bigger this value the longer the envelope needs to increase to attack-level. Choose a small value for instruments like pianos and a big value for strings.</source> <translation type="unfinished">از این دستگیره برای تنظیم زمان تهاجم پاکت جاری استفاده کنید.هرچه این مقدار بیشتر باشد پاکت زمان بیشتزی برای افزایش تا سطح تهاجم نیاز دازد.مقدار کم را برای دستگاه هایی مانند پیانو و مقدار زیاد را برای زهی استفاده کنید.</translation> </message> <message> <source>HOLD</source> <translation type="unfinished">نگهداری-HOLD</translation> </message> <message> <source>Hold:</source> <translation type="unfinished">نگهداری(Hold):</translation> </message> <message> <source>Use this knob for setting hold-time of the current envelope. The bigger this value the longer the envelope holds attack-level before it begins to decrease to sustain-level.</source> <translation type="unfinished">از این دستگیره برای تنظیم زمان تامل پاکت جاری استفاده کنید.هرچه این مقدار بیشتر باشد بیشتر طول می کشد تا پاکت سطح تهاجم را قبل از کاهش یه سطح تقویت(sustain-level) نگهدارد.</translation> </message> <message> <source>DEC</source> <translation type="unfinished"></translation> </message> <message> <source>Decay:</source> <translation type="unfinished">محو شدن(Decay):</translation> </message> <message> <source>Use this knob for setting decay-time of the current envelope. The bigger this value the longer the envelope needs to decrease from attack-level to sustain-level. Choose a small value for instruments like pianos.</source> <translation type="unfinished">از این دستگیره برای تنظیم زمان محو شدن پاکت جاری استفاده کنید. هرچه این مقدار بیشتر باشد زمان بیشتری برای کاهش از سطح تهاجم به سطح تقویت طول کشد.مقدار کمی را برای دستگاه هایی مانند پیانو انتخاب کنید.</translation> </message> <message> <source>SUST</source> <translation type="unfinished"></translation> </message> <message> <source>Sustain:</source> <translation type="unfinished">تقویت(Sustain):</translation> </message> <message> <source>Use this knob for setting sustain-level of the current envelope. The bigger this value the higher the level on which the envelope stays before going down to zero.</source> <translation type="unfinished">از این دستگیره برای تنظیم سطح تقویت(Sustain Level) پاکت جاری استفاده کنید. هرچه این مقدار بیشتر باشد پاکت در سطح بالاتری قبل از نزول به صفر قرار می گیرد.</translation> </message> <message> <source>REL</source> <translation type="unfinished"></translation> </message> <message> <source>Release:</source> <translation type="unfinished">رهایی(Release):</translation> </message> <message> <source>Use this knob for setting release-time of the current envelope. The bigger this value the longer the envelope needs to decrease from sustain-level to zero. Choose a big value for soft instruments like strings.</source> <translation type="unfinished">از این دستگیره برای تنظیم زمان رهایی پاکت جاری استفاده کنید. هرچه این مقدار بیشتر باشد زمان بیشتری برای کاهش از سطح تقویت به صفر طول کشد.مقدار زیاد را برای دستگاه های زهی انتخاب کنید.</translation> </message> <message> <source>AMT</source> <translation type="unfinished"></translation> </message> <message> <source>Modulation amount:</source> <translation type="unfinished">میزان مدولاسیون:</translation> </message> <message> <source>Use this knob for setting modulation amount of the current envelope. The bigger this value the more the according size (e.g. volume or cutoff-frequency) will be influenced by this envelope.</source> <translation type="unfinished">از این دسته برای تنظیم مقدار مذولاسیون پاکت جاری استفاده کنید.هرچه این مقدار بیشتر باشد اندازه ی منتخب بیشتری(برای مثال حجم یا فرکانس گوشه ای) تحت تاثیر این پاکت قرار می گیرد.</translation> </message> <message> <source>LFO predelay:</source> <translation type="unfinished"></translation> </message> <message> <source>Use this knob for setting predelay-time of the current LFO. The bigger this value the the time until the LFO starts to oscillate.</source> <translation type="unfinished">ار این دستگیره برای تنظیم زمان پیش تاخیر LFO جاری استفاده کنید.هرچه این مقدار بیشتر باشد زمان بیشتزی تا شروع نوسان LFO طول می کشد.</translation> </message> <message> <source>LFO- attack:</source> <translation type="unfinished"></translation> </message> <message> <source>Use this knob for setting attack-time of the current LFO. The bigger this value the longer the LFO needs to increase its amplitude to maximum.</source> <translation type="unfinished">از این دستگیره برای تنظیم زمان تهاجم LFO جاری استفاده کنید.هرچه این مقدار بیشتر باشد LFO زمان بیشتزی برای افزایش دامنه به مقدار ماکزیمم نیاز دازد.</translation> </message> <message> <source>SPD</source> <translation type="unfinished"></translation> </message> <message> <source>LFO speed:</source> <translation type="unfinished"></translation> </message> <message> <source>Use this knob for setting speed of the current LFO. The bigger this value the faster the LFO oscillates and the faster will be your effect.</source> <translation type="unfinished">از این دستگیره برای تنظیم سرعت LFO استفاده کنید. هرچه این مقدار بیشتر باشد LFO سریع تر نوسان می کند و جلوه ی شما سریع تر خواهد بود.</translation> </message> <message> <source>Use this knob for setting modulation amount of the current LFO. The bigger this value the more the selected size (e.g. volume or cutoff-frequency) will be influenced by this LFO.</source> <translation type="unfinished">از این دسته برای تنظیم مقدار مذولاسیون LFO جاری استفاده کنید.هرچه این مقدار بیشتر باشد اندازه ی منتخب بیشتری(برای مثال حجم یا فرکانس گوشه ای) تحت تاثیر این LFO قرار می گیرد.</translation> </message> <message> <source>Click here for a sine-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a triangle-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a saw-wave for current.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a square-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a user-defined wave. Afterwards, drag an according sample-file onto the LFO graph.</source> <translation type="unfinished"></translation> </message> <message> <source>FREQ x 100</source> <translation type="unfinished"></translation> </message> <message> <source>Click here if the frequency of this LFO should be multiplied by 100.</source> <translation type="unfinished"></translation> </message> <message> <source>multiply LFO-frequency by 100</source> <translation type="unfinished"></translation> </message> <message> <source>MODULATE ENV-AMOUNT</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to make the envelope-amount controlled by this LFO.</source> <translation type="unfinished">برای اینکه میزان پاکت توسط این LFO کنترل شود اینجا را کلیک کنید.</translation> </message> <message> <source>control envelope-amount by this LFO</source> <translation type="unfinished">کنترل مقدار پاکت توسط این LFO</translation> </message> <message> <source>ms/LFO:</source> <translation type="unfinished">ms/LFO:</translation> </message> <message> <source>Hint</source> <translation type="unfinished"></translation> </message> <message> <source>Drag a sample from somewhere and drop it in this window.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for random wave.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>EqControls</name> <message> <source>Input gain</source> <translation type="unfinished"></translation> </message> <message> <source>Output gain</source> <translation type="unfinished"></translation> </message> <message> <source>Low shelf gain</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 1 gain</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 2 gain</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 3 gain</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 4 gain</source> <translation type="unfinished"></translation> </message> <message> <source>High Shelf gain</source> <translation type="unfinished"></translation> </message> <message> <source>HP res</source> <translation type="unfinished"></translation> </message> <message> <source>Low Shelf res</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 1 BW</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 2 BW</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 3 BW</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 4 BW</source> <translation type="unfinished"></translation> </message> <message> <source>High Shelf res</source> <translation type="unfinished"></translation> </message> <message> <source>LP res</source> <translation type="unfinished"></translation> </message> <message> <source>HP freq</source> <translation type="unfinished"></translation> </message> <message> <source>Low Shelf freq</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 1 freq</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 2 freq</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 3 freq</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 4 freq</source> <translation type="unfinished"></translation> </message> <message> <source>High shelf freq</source> <translation type="unfinished"></translation> </message> <message> <source>LP freq</source> <translation type="unfinished"></translation> </message> <message> <source>HP active</source> <translation type="unfinished"></translation> </message> <message> <source>Low shelf active</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 1 active</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 2 active</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 3 active</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 4 active</source> <translation type="unfinished"></translation> </message> <message> <source>High shelf active</source> <translation type="unfinished"></translation> </message> <message> <source>LP active</source> <translation type="unfinished"></translation> </message> <message> <source>LP 12</source> <translation type="unfinished"></translation> </message> <message> <source>LP 24</source> <translation type="unfinished"></translation> </message> <message> <source>LP 48</source> <translation type="unfinished"></translation> </message> <message> <source>HP 12</source> <translation type="unfinished"></translation> </message> <message> <source>HP 24</source> <translation type="unfinished"></translation> </message> <message> <source>HP 48</source> <translation type="unfinished"></translation> </message> <message> <source>low pass type</source> <translation type="unfinished"></translation> </message> <message> <source>high pass type</source> <translation type="unfinished"></translation> </message> </context> <context> <name>EqControlsDialog</name> <message> <source>HP</source> <translation type="unfinished"></translation> </message> <message> <source>Low Shelf</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 1</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 2</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 3</source> <translation type="unfinished"></translation> </message> <message> <source>Peak 4</source> <translation type="unfinished"></translation> </message> <message> <source>High Shelf</source> <translation type="unfinished"></translation> </message> <message> <source>LP</source> <translation type="unfinished"></translation> </message> <message> <source>In Gain</source> <translation type="unfinished"></translation> </message> <message> <source>Gain</source> <translation type="unfinished"></translation> </message> <message> <source>Out Gain</source> <translation type="unfinished"></translation> </message> <message> <source>Bandwidth: </source> <translation type="unfinished"></translation> </message> <message> <source>Resonance : </source> <translation type="unfinished"></translation> </message> <message> <source>Frequency:</source> <translation type="unfinished"></translation> </message> <message> <source>12dB</source> <translation type="unfinished"></translation> </message> <message> <source>24dB</source> <translation type="unfinished"></translation> </message> <message> <source>48dB</source> <translation type="unfinished"></translation> </message> <message> <source>lp grp</source> <translation type="unfinished"></translation> </message> <message> <source>hp grp</source> <translation type="unfinished"></translation> </message> </context> <context> <name>EqParameterWidget</name> <message> <source>Hz </source> <translation type="unfinished"></translation> </message> </context> <context> <name>ExportProjectDialog</name> <message> <source>Export project</source> <translation type="unfinished"></translation> </message> <message> <source>Output</source> <translation type="unfinished"></translation> </message> <message> <source>File format:</source> <translation type="unfinished"></translation> </message> <message> <source>Samplerate:</source> <translation type="unfinished"></translation> </message> <message> <source>44100 Hz</source> <translation type="unfinished"></translation> </message> <message> <source>48000 Hz</source> <translation type="unfinished"></translation> </message> <message> <source>88200 Hz</source> <translation type="unfinished"></translation> </message> <message> <source>96000 Hz</source> <translation type="unfinished"></translation> </message> <message> <source>192000 Hz</source> <translation type="unfinished"></translation> </message> <message> <source>Bitrate:</source> <translation type="unfinished"></translation> </message> <message> <source>64 KBit/s</source> <translation type="unfinished"></translation> </message> <message> <source>128 KBit/s</source> <translation type="unfinished"></translation> </message> <message> <source>160 KBit/s</source> <translation type="unfinished"></translation> </message> <message> <source>192 KBit/s</source> <translation type="unfinished"></translation> </message> <message> <source>256 KBit/s</source> <translation type="unfinished"></translation> </message> <message> <source>320 KBit/s</source> <translation type="unfinished"></translation> </message> <message> <source>Depth:</source> <translation type="unfinished"></translation> </message> <message> <source>16 Bit Integer</source> <translation type="unfinished"></translation> </message> <message> <source>32 Bit Float</source> <translation type="unfinished"></translation> </message> <message> <source>Please note that not all of the parameters above apply for all file formats.</source> <translation type="unfinished"></translation> </message> <message> <source>Quality settings</source> <translation type="unfinished"></translation> </message> <message> <source>Interpolation:</source> <translation type="unfinished"></translation> </message> <message> <source>Zero Order Hold</source> <translation type="unfinished"></translation> </message> <message> <source>Sinc Fastest</source> <translation type="unfinished"></translation> </message> <message> <source>Sinc Medium (recommended)</source> <translation type="unfinished"></translation> </message> <message> <source>Sinc Best (very slow!)</source> <translation type="unfinished"></translation> </message> <message> <source>Oversampling (use with care!):</source> <translation type="unfinished"></translation> </message> <message> <source>1x (None)</source> <translation type="unfinished"></translation> </message> <message> <source>2x</source> <translation type="unfinished"></translation> </message> <message> <source>4x</source> <translation type="unfinished"></translation> </message> <message> <source>8x</source> <translation type="unfinished"></translation> </message> <message> <source>Start</source> <translation type="unfinished"></translation> </message> <message> <source>Cancel</source> <translation type="unfinished">لغو</translation> </message> <message> <source>Export as loop (remove end silence)</source> <translation type="unfinished"></translation> </message> <message> <source>Export between loop markers</source> <translation type="unfinished"></translation> </message> <message> <source>Could not open file</source> <translation type="unfinished">پرونده باز نشد</translation> </message> <message> <source>Could not open file %1 for writing. Please make sure you have write-permission to the file and the directory containing the file and try again!</source> <translation type="unfinished"></translation> </message> <message> <source>Export project to %1</source> <translation type="unfinished">استخراج پرونده به %1</translation> </message> <message> <source>Error</source> <translation type="unfinished"></translation> </message> <message> <source>Error while determining file-encoder device. Please try to choose a different output format.</source> <translation type="unfinished"></translation> </message> <message> <source>Rendering: %1%</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Fader</name> <message> <source>Please enter a new value between %1 and %2:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>FileBrowser</name> <message> <source>Browser</source> <translation type="unfinished"></translation> </message> </context> <context> <name>FileBrowserTreeWidget</name> <message> <source>Send to active instrument-track</source> <translation type="unfinished"></translation> </message> <message> <source>Open in new instrument-track/Song-Editor</source> <translation type="unfinished"></translation> </message> <message> <source>Open in new instrument-track/B+B Editor</source> <translation type="unfinished"></translation> </message> <message> <source>Loading sample</source> <translation type="unfinished"></translation> </message> <message> <source>Please wait, loading sample for preview...</source> <translation type="unfinished"></translation> </message> <message> <source>--- Factory files ---</source> <translation type="unfinished"></translation> </message> </context> <context> <name>FlangerControls</name> <message> <source>Delay Samples</source> <translation type="unfinished"></translation> </message> <message> <source>Lfo Frequency</source> <translation type="unfinished"></translation> </message> <message> <source>Seconds</source> <translation type="unfinished"></translation> </message> <message> <source>Regen</source> <translation type="unfinished"></translation> </message> <message> <source>Noise</source> <translation type="unfinished"></translation> </message> <message> <source>Invert</source> <translation type="unfinished"></translation> </message> </context> <context> <name>FlangerControlsDialog</name> <message> <source>Delay</source> <translation type="unfinished"></translation> </message> <message> <source>Delay Time:</source> <translation type="unfinished"></translation> </message> <message> <source>Lfo Hz</source> <translation type="unfinished"></translation> </message> <message> <source>Lfo:</source> <translation type="unfinished"></translation> </message> <message> <source>Amt</source> <translation type="unfinished"></translation> </message> <message> <source>Amt:</source> <translation type="unfinished"></translation> </message> <message> <source>Regen</source> <translation type="unfinished"></translation> </message> <message> <source>Feedback Amount:</source> <translation type="unfinished"></translation> </message> <message> <source>Noise</source> <translation type="unfinished"></translation> </message> <message> <source>White Noise Amount:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>FxLine</name> <message> <source>Channel send amount</source> <translation type="unfinished"></translation> </message> <message> <source>The FX channel receives input from one or more instrument tracks. It in turn can be routed to multiple other FX channels. LMMS automatically takes care of preventing infinite loops for you and doesn&apos;t allow making a connection that would result in an infinite loop. In order to route the channel to another channel, select the FX channel and click on the &quot;send&quot; button on the channel you want to send to. The knob under the send button controls the level of signal that is sent to the channel. You can remove and move FX channels in the context menu, which is accessed by right-clicking the FX channel. </source> <translation type="unfinished"></translation> </message> <message> <source>Move &amp;left</source> <translation type="unfinished"></translation> </message> <message> <source>Move &amp;right</source> <translation type="unfinished"></translation> </message> <message> <source>Rename &amp;channel</source> <translation type="unfinished"></translation> </message> <message> <source>R&amp;emove channel</source> <translation type="unfinished"></translation> </message> <message> <source>Remove &amp;unused channels</source> <translation type="unfinished"></translation> </message> </context> <context> <name>FxMixer</name> <message> <source>Master</source> <translation type="unfinished"></translation> </message> <message> <source>FX %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>FxMixerView</name> <message> <source>Rename FX channel</source> <translation type="unfinished"></translation> </message> <message> <source>Enter the new name for this FX channel</source> <translation type="unfinished"></translation> </message> <message> <source>FX-Mixer</source> <translation type="unfinished"></translation> </message> <message> <source>FX Fader %1</source> <translation type="unfinished"></translation> </message> <message> <source>Mute</source> <translation type="unfinished"></translation> </message> <message> <source>Mute this FX channel</source> <translation type="unfinished"></translation> </message> <message> <source>Solo</source> <translation type="unfinished"></translation> </message> <message> <source>Solo FX channel</source> <translation type="unfinished"></translation> </message> </context> <context> <name>FxRoute</name> <message> <source>Amount to send from channel %1 to channel %2</source> <translation type="unfinished"></translation> </message> </context> <context> <name>GigInstrument</name> <message> <source>Bank</source> <translation type="unfinished"></translation> </message> <message> <source>Patch</source> <translation type="unfinished"></translation> </message> <message> <source>Gain</source> <translation type="unfinished"></translation> </message> </context> <context> <name>GigInstrumentView</name> <message> <source>Open other GIG file</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to open another GIG file</source> <translation type="unfinished"></translation> </message> <message> <source>Choose the patch</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to change which patch of the GIG file to use</source> <translation type="unfinished"></translation> </message> <message> <source>Change which instrument of the GIG file is being played</source> <translation type="unfinished"></translation> </message> <message> <source>Which GIG file is currently being used</source> <translation type="unfinished"></translation> </message> <message> <source>Which patch of the GIG file is currently being used</source> <translation type="unfinished"></translation> </message> <message> <source>Gain</source> <translation type="unfinished"></translation> </message> <message> <source>Factor to multiply samples by</source> <translation type="unfinished"></translation> </message> <message> <source>Open GIG file</source> <translation type="unfinished"></translation> </message> <message> <source>GIG Files (*.gig)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>InstrumentFunctionArpeggio</name> <message> <source>Arpeggio</source> <translation type="unfinished">آرپگیو(Arpeggio)</translation> </message> <message> <source>Arpeggio type</source> <translation type="unfinished"></translation> </message> <message> <source>Arpeggio range</source> <translation type="unfinished">محدوده ی آرپگیو</translation> </message> <message> <source>Arpeggio time</source> <translation type="unfinished">زمان أرپگیو</translation> </message> <message> <source>Arpeggio gate</source> <translation type="unfinished">مدخل أرپگیو</translation> </message> <message> <source>Arpeggio direction</source> <translation type="unfinished"></translation> </message> <message> <source>Arpeggio mode</source> <translation type="unfinished"></translation> </message> <message> <source>Up</source> <translation type="unfinished"></translation> </message> <message> <source>Down</source> <translation type="unfinished"></translation> </message> <message> <source>Up and down</source> <translation type="unfinished"></translation> </message> <message> <source>Random</source> <translation type="unfinished"></translation> </message> <message> <source>Free</source> <translation type="unfinished"></translation> </message> <message> <source>Sort</source> <translation type="unfinished"></translation> </message> <message> <source>Sync</source> <translation type="unfinished"></translation> </message> <message> <source>Down and up</source> <translation type="unfinished"></translation> </message> </context> <context> <name>InstrumentFunctionArpeggioView</name> <message> <source>ARPEGGIO</source> <translation type="unfinished"></translation> </message> <message> <source>An arpeggio is a method playing (especially plucked) instruments, which makes the music much livelier. The strings of such instruments (e.g. harps) are plucked like chords. The only difference is that this is done in a sequential order, so the notes are not played at the same time. Typical arpeggios are major or minor triads, but there are a lot of other possible chords, you can select.</source> <translation type="unfinished"></translation> </message> <message> <source>RANGE</source> <translation type="unfinished"></translation> </message> <message> <source>Arpeggio range:</source> <translation type="unfinished">محدوده ی أرپگیو:</translation> </message> <message> <source>octave(s)</source> <translation type="unfinished">نت (ها)</translation> </message> <message> <source>Use this knob for setting the arpeggio range in octaves. The selected arpeggio will be played within specified number of octaves.</source> <translation type="unfinished"></translation> </message> <message> <source>TIME</source> <translation type="unfinished"></translation> </message> <message> <source>Arpeggio time:</source> <translation type="unfinished">زمان آرپگیو:</translation> </message> <message> <source>ms</source> <translation type="unfinished">م ث</translation> </message> <message> <source>Use this knob for setting the arpeggio time in milliseconds. The arpeggio time specifies how long each arpeggio-tone should be played.</source> <translation type="unfinished">از این دستگیره برای تنظیم زمان در آرپگیو به میلی ثانیه استفاده کنید.زمان آرپگیو مشخص می کند که چه مدت هر آهنگ آرپگیو پخش شود.</translation> </message> <message> <source>GATE</source> <translation type="unfinished"></translation> </message> <message> <source>Arpeggio gate:</source> <translation type="unfinished">مدخل آرپگیو:</translation> </message> <message> <source>%</source> <translation type="unfinished">%</translation> </message> <message> <source>Use this knob for setting the arpeggio gate. The arpeggio gate specifies the percent of a whole arpeggio-tone that should be played. With this you can make cool staccato arpeggios.</source> <translation type="unfinished"></translation> </message> <message> <source>Chord:</source> <translation type="unfinished"></translation> </message> <message> <source>Direction:</source> <translation type="unfinished">جهت:</translation> </message> <message> <source>Mode:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>InstrumentFunctionNoteStacking</name> <message> <source>octave</source> <translation type="unfinished">نت</translation> </message> <message> <source>Major</source> <translation type="unfinished">Major</translation> </message> <message> <source>Majb5</source> <translation type="unfinished">Majb5</translation> </message> <message> <source>minor</source> <translation type="unfinished">minor</translation> </message> <message> <source>minb5</source> <translation type="unfinished">mollb5</translation> </message> <message> <source>sus2</source> <translation type="unfinished">sus2</translation> </message> <message> <source>sus4</source> <translation type="unfinished">sus4</translation> </message> <message> <source>aug</source> <translation type="unfinished">aug</translation> </message> <message> <source>augsus4</source> <translation type="unfinished">augsus4</translation> </message> <message> <source>tri</source> <translation type="unfinished">tri</translation> </message> <message> <source>6</source> <translation type="unfinished">6</translation> </message> <message> <source>6sus4</source> <translation type="unfinished">6sus4</translation> </message> <message> <source>6add9</source> <translation type="unfinished">madd9</translation> </message> <message> <source>m6</source> <translation type="unfinished">m6</translation> </message> <message> <source>m6add9</source> <translation type="unfinished">m6add9</translation> </message> <message> <source>7</source> <translation type="unfinished">7</translation> </message> <message> <source>7sus4</source> <translation type="unfinished">7sus4</translation> </message> <message> <source>7#5</source> <translation type="unfinished">7#5</translation> </message> <message> <source>7b5</source> <translation type="unfinished">7b5</translation> </message> <message> <source>7#9</source> <translation type="unfinished">7#9</translation> </message> <message> <source>7b9</source> <translation type="unfinished">7b9</translation> </message> <message> <source>7#5#9</source> <translation type="unfinished">7#5#9</translation> </message> <message> <source>7#5b9</source> <translation type="unfinished">7#5b9</translation> </message> <message> <source>7b5b9</source> <translation type="unfinished">7b5b9</translation> </message> <message> <source>7add11</source> <translation type="unfinished">7add11</translation> </message> <message> <source>7add13</source> <translation type="unfinished">7add13</translation> </message> <message> <source>7#11</source> <translation type="unfinished">7#11</translation> </message> <message> <source>Maj7</source> <translation type="unfinished">Maj7</translation> </message> <message> <source>Maj7b5</source> <translation type="unfinished">Maj7b5</translation> </message> <message> <source>Maj7#5</source> <translation type="unfinished">Maj7#5</translation> </message> <message> <source>Maj7#11</source> <translation type="unfinished">Maj7#11</translation> </message> <message> <source>Maj7add13</source> <translation type="unfinished">Maj7add13</translation> </message> <message> <source>m7</source> <translation type="unfinished">m7</translation> </message> <message> <source>m7b5</source> <translation type="unfinished">m7b5</translation> </message> <message> <source>m7b9</source> <translation type="unfinished">m7b9</translation> </message> <message> <source>m7add11</source> <translation type="unfinished">m7add11</translation> </message> <message> <source>m7add13</source> <translation type="unfinished">m7add13</translation> </message> <message> <source>m-Maj7</source> <translation type="unfinished">m-Maj7</translation> </message> <message> <source>m-Maj7add11</source> <translation type="unfinished">m-Maj7add11</translation> </message> <message> <source>m-Maj7add13</source> <translation type="unfinished">m-Maj7add13</translation> </message> <message> <source>9</source> <translation type="unfinished">9</translation> </message> <message> <source>9sus4</source> <translation type="unfinished">9sus4</translation> </message> <message> <source>add9</source> <translation type="unfinished">add9</translation> </message> <message> <source>9#5</source> <translation type="unfinished">9#5</translation> </message> <message> <source>9b5</source> <translation type="unfinished">9b5</translation> </message> <message> <source>9#11</source> <translation type="unfinished">9#11</translation> </message> <message> <source>9b13</source> <translation type="unfinished">9b13</translation> </message> <message> <source>Maj9</source> <translation type="unfinished">Maj9</translation> </message> <message> <source>Maj9sus4</source> <translation type="unfinished">Maj9sus4</translation> </message> <message> <source>Maj9#5</source> <translation type="unfinished">Maj9#5</translation> </message> <message> <source>Maj9#11</source> <translation type="unfinished">Maj9#11</translation> </message> <message> <source>m9</source> <translation type="unfinished">m9</translation> </message> <message> <source>madd9</source> <translation type="unfinished">madd9</translation> </message> <message> <source>m9b5</source> <translation type="unfinished">m9b5</translation> </message> <message> <source>m9-Maj7</source> <translation type="unfinished">m9-Maj7</translation> </message> <message> <source>11</source> <translation type="unfinished">11</translation> </message> <message> <source>11b9</source> <translation type="unfinished">11b9</translation> </message> <message> <source>Maj11</source> <translation type="unfinished">Maj11</translation> </message> <message> <source>m11</source> <translation type="unfinished">m11</translation> </message> <message> <source>m-Maj11</source> <translation type="unfinished">m-Maj11</translation> </message> <message> <source>13</source> <translation type="unfinished">13</translation> </message> <message> <source>13#9</source> <translation type="unfinished">13#9</translation> </message> <message> <source>13b9</source> <translation type="unfinished">13b9</translation> </message> <message> <source>13b5b9</source> <translation type="unfinished">13b5b9</translation> </message> <message> <source>Maj13</source> <translation type="unfinished">Maj13</translation> </message> <message> <source>m13</source> <translation type="unfinished">m13</translation> </message> <message> <source>m-Maj13</source> <translation type="unfinished">m-Maj13</translation> </message> <message> <source>Harmonic minor</source> <translation type="unfinished">Harmonic minor</translation> </message> <message> <source>Melodic minor</source> <translation type="unfinished">Melodic minor</translation> </message> <message> <source>Whole tone</source> <translation type="unfinished">Whole tone</translation> </message> <message> <source>Diminished</source> <translation type="unfinished">Diminished</translation> </message> <message> <source>Major pentatonic</source> <translation type="unfinished">Major pentatonic</translation> </message> <message> <source>Minor pentatonic</source> <translation type="unfinished">Minor pentatonic</translation> </message> <message> <source>Jap in sen</source> <translation type="unfinished">Jap in sen</translation> </message> <message> <source>Major bebop</source> <translation type="unfinished">Major bebop</translation> </message> <message> <source>Dominant bebop</source> <translation type="unfinished">Dominant bebop</translation> </message> <message> <source>Blues</source> <translation type="unfinished">Blues</translation> </message> <message> <source>Arabic</source> <translation type="unfinished">Arabic</translation> </message> <message> <source>Enigmatic</source> <translation type="unfinished">Enigmatic</translation> </message> <message> <source>Neopolitan</source> <translation type="unfinished">Neopolitan</translation> </message> <message> <source>Neopolitan minor</source> <translation type="unfinished">Neopolitan minor</translation> </message> <message> <source>Hungarian minor</source> <translation type="unfinished">Hungarian minor</translation> </message> <message> <source>Dorian</source> <translation type="unfinished">Dorian</translation> </message> <message> <source>Phrygolydian</source> <translation type="unfinished">Phrygolydian</translation> </message> <message> <source>Lydian</source> <translation type="unfinished">Lydian</translation> </message> <message> <source>Mixolydian</source> <translation type="unfinished">Mixolydian</translation> </message> <message> <source>Aeolian</source> <translation type="unfinished">Aeolian</translation> </message> <message> <source>Locrian</source> <translation type="unfinished">Locrian</translation> </message> <message> <source>Chords</source> <translation type="unfinished">تار ها(Chords)</translation> </message> <message> <source>Chord type</source> <translation type="unfinished"></translation> </message> <message> <source>Chord range</source> <translation type="unfinished">محدوده ی تار</translation> </message> <message> <source>Minor</source> <translation type="unfinished"></translation> </message> <message> <source>Chromatic</source> <translation type="unfinished"></translation> </message> <message> <source>Half-Whole Diminished</source> <translation type="unfinished"></translation> </message> <message> <source>5</source> <translation type="unfinished"></translation> </message> </context> <context> <name>InstrumentFunctionNoteStackingView</name> <message> <source>RANGE</source> <translation type="unfinished"></translation> </message> <message> <source>Chord range:</source> <translation type="unfinished">محدوده ی تار ها :</translation> </message> <message> <source>octave(s)</source> <translation type="unfinished">نت (ها)</translation> </message> <message> <source>Use this knob for setting the chord range in octaves. The selected chord will be played within specified number of octaves.</source> <translation type="unfinished"></translation> </message> <message> <source>STACKING</source> <translation type="unfinished"></translation> </message> <message> <source>Chord:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>InstrumentMidiIOView</name> <message> <source>ENABLE MIDI INPUT</source> <translation type="unfinished"></translation> </message> <message> <source>CHANNEL</source> <translation type="unfinished"></translation> </message> <message> <source>VELOCITY</source> <translation type="unfinished"></translation> </message> <message> <source>ENABLE MIDI OUTPUT</source> <translation type="unfinished"></translation> </message> <message> <source>PROGRAM</source> <translation type="unfinished"></translation> </message> <message> <source>MIDI devices to receive MIDI events from</source> <translation type="unfinished"></translation> </message> <message> <source>MIDI devices to send MIDI events to</source> <translation type="unfinished"></translation> </message> <message> <source>NOTE</source> <translation type="unfinished"></translation> </message> <message> <source>CUSTOM BASE VELOCITY</source> <translation type="unfinished"></translation> </message> <message> <source>Specify the velocity normalization base for MIDI-based instruments at note volume 100%</source> <translation type="unfinished"></translation> </message> <message> <source>BASE VELOCITY</source> <translation type="unfinished"></translation> </message> </context> <context> <name>InstrumentMiscView</name> <message> <source>MASTER PITCH</source> <translation type="unfinished"></translation> </message> <message> <source>Enables the use of Master Pitch</source> <translation type="unfinished"></translation> </message> </context> <context> <name>InstrumentSoundShaping</name> <message> <source>VOLUME</source> <translation type="unfinished">حجم</translation> </message> <message> <source>Volume</source> <translation type="unfinished"></translation> </message> <message> <source>CUTOFF</source> <translation type="unfinished"></translation> </message> <message> <source>Cutoff frequency</source> <translation type="unfinished"></translation> </message> <message> <source>RESO</source> <translation type="unfinished"></translation> </message> <message> <source>Resonance</source> <translation type="unfinished"></translation> </message> <message> <source>Envelopes/LFOs</source> <translation type="unfinished"></translation> </message> <message> <source>Filter type</source> <translation type="unfinished"></translation> </message> <message> <source>Q/Resonance</source> <translation type="unfinished">Q/رزونانس</translation> </message> <message> <source>LowPass</source> <translation type="unfinished">پایین گذر</translation> </message> <message> <source>HiPass</source> <translation type="unfinished">بالا گذر</translation> </message> <message> <source>BandPass csg</source> <translation type="unfinished">میان گذر csg</translation> </message> <message> <source>BandPass czpg</source> <translation type="unfinished">میان گذر czpg</translation> </message> <message> <source>Notch</source> <translation type="unfinished">نچ</translation> </message> <message> <source>Allpass</source> <translation type="unfinished">تمام گذر</translation> </message> <message> <source>Moog</source> <translation type="unfinished">موگ Moog</translation> </message> <message> <source>2x LowPass</source> <translation type="unfinished">پایین گذر 2x</translation> </message> <message> <source>RC LowPass 12dB</source> <translation type="unfinished"></translation> </message> <message> <source>RC BandPass 12dB</source> <translation type="unfinished"></translation> </message> <message> <source>RC HighPass 12dB</source> <translation type="unfinished"></translation> </message> <message> <source>RC LowPass 24dB</source> <translation type="unfinished"></translation> </message> <message> <source>RC BandPass 24dB</source> <translation type="unfinished"></translation> </message> <message> <source>RC HighPass 24dB</source> <translation type="unfinished"></translation> </message> <message> <source>Vocal Formant Filter</source> <translation type="unfinished"></translation> </message> <message> <source>2x Moog</source> <translation type="unfinished"></translation> </message> <message> <source>SV LowPass</source> <translation type="unfinished"></translation> </message> <message> <source>SV BandPass</source> <translation type="unfinished"></translation> </message> <message> <source>SV HighPass</source> <translation type="unfinished"></translation> </message> <message> <source>SV Notch</source> <translation type="unfinished"></translation> </message> <message> <source>Fast Formant</source> <translation type="unfinished"></translation> </message> <message> <source>Tripole</source> <translation type="unfinished"></translation> </message> </context> <context> <name>InstrumentSoundShapingView</name> <message> <source>TARGET</source> <translation type="unfinished"></translation> </message> <message> <source>These tabs contain envelopes. They&apos;re very important for modifying a sound, in that they are almost always necessary for substractive synthesis. For example if you have a volume envelope, you can set when the sound should have a specific volume. If you want to create some soft strings then your sound has to fade in and out very softly. This can be done by setting large attack and release times. It&apos;s the same for other envelope targets like panning, cutoff frequency for the used filter and so on. Just monkey around with it! You can really make cool sounds out of a saw-wave with just some envelopes...!</source> <translation type="unfinished"></translation> </message> <message> <source>FILTER</source> <translation type="unfinished"></translation> </message> <message> <source>Here you can select the built-in filter you want to use for this instrument-track. Filters are very important for changing the characteristics of a sound.</source> <translation type="unfinished"></translation> </message> <message> <source>Hz</source> <translation type="unfinished">Hz</translation> </message> <message> <source>Use this knob for setting the cutoff frequency for the selected filter. The cutoff frequency specifies the frequency for cutting the signal by a filter. For example a lowpass-filter cuts all frequencies above the cutoff frequency. A highpass-filter cuts all frequencies below cutoff frequency, and so on...</source> <translation type="unfinished"></translation> </message> <message> <source>RESO</source> <translation type="unfinished"></translation> </message> <message> <source>Resonance:</source> <translation type="unfinished"></translation> </message> <message> <source>Use this knob for setting Q/Resonance for the selected filter. Q/Resonance tells the filter how much it should amplify frequencies near Cutoff-frequency.</source> <translation type="unfinished"></translation> </message> <message> <source>FREQ</source> <translation type="unfinished"></translation> </message> <message> <source>cutoff frequency:</source> <translation type="unfinished"></translation> </message> <message> <source>Envelopes, LFOs and filters are not supported by the current instrument.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>InstrumentTrack</name> <message> <source>unnamed_track</source> <translation type="unfinished"></translation> </message> <message> <source>Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Panning</source> <translation type="unfinished"></translation> </message> <message> <source>Pitch</source> <translation type="unfinished"></translation> </message> <message> <source>FX channel</source> <translation type="unfinished"></translation> </message> <message> <source>Default preset</source> <translation type="unfinished"></translation> </message> <message> <source>With this knob you can set the volume of the opened channel.</source> <translation type="unfinished">Mit diesem Knopf können Sie die Lautstärke des geöffneten Kanals ändern.</translation> </message> <message> <source>Base note</source> <translation type="unfinished"></translation> </message> <message> <source>Pitch range</source> <translation type="unfinished"></translation> </message> <message> <source>Master Pitch</source> <translation type="unfinished"></translation> </message> </context> <context> <name>InstrumentTrackView</name> <message> <source>Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Volume:</source> <translation type="unfinished"></translation> </message> <message> <source>VOL</source> <translation type="unfinished"></translation> </message> <message> <source>Panning</source> <translation type="unfinished"></translation> </message> <message> <source>Panning:</source> <translation type="unfinished"></translation> </message> <message> <source>PAN</source> <translation type="unfinished"></translation> </message> <message> <source>MIDI</source> <translation type="unfinished"></translation> </message> <message> <source>Input</source> <translation type="unfinished"></translation> </message> <message> <source>Output</source> <translation type="unfinished"></translation> </message> </context> <context> <name>InstrumentTrackWindow</name> <message> <source>GENERAL SETTINGS</source> <translation type="unfinished"></translation> </message> <message> <source>Instrument volume</source> <translation type="unfinished"></translation> </message> <message> <source>Volume:</source> <translation type="unfinished"></translation> </message> <message> <source>VOL</source> <translation type="unfinished"></translation> </message> <message> <source>Panning</source> <translation type="unfinished"></translation> </message> <message> <source>Panning:</source> <translation type="unfinished"></translation> </message> <message> <source>PAN</source> <translation type="unfinished"></translation> </message> <message> <source>Pitch</source> <translation type="unfinished"></translation> </message> <message> <source>Pitch:</source> <translation type="unfinished"></translation> </message> <message> <source>cents</source> <translation type="unfinished">درصد</translation> </message> <message> <source>PITCH</source> <translation type="unfinished"></translation> </message> <message> <source>FX channel</source> <translation type="unfinished"></translation> </message> <message> <source>ENV/LFO</source> <translation type="unfinished"></translation> </message> <message> <source>FUNC</source> <translation type="unfinished"></translation> </message> <message> <source>FX</source> <translation type="unfinished"></translation> </message> <message> <source>MIDI</source> <translation type="unfinished"></translation> </message> <message> <source>Save preset</source> <translation type="unfinished"></translation> </message> <message> <source>XML preset file (*.xpf)</source> <translation type="unfinished"></translation> </message> <message> <source>PLUGIN</source> <translation type="unfinished">اضافات</translation> </message> <message> <source>Pitch range (semitones)</source> <translation type="unfinished"></translation> </message> <message> <source>RANGE</source> <translation type="unfinished"></translation> </message> <message> <source>Save current instrument track settings in a preset file</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to save current instrument track settings in a preset file. Later you can load this preset by double-clicking it in the preset-browser.</source> <translation type="unfinished"></translation> </message> <message> <source>MISC</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Knob</name> <message> <source>Set linear</source> <translation type="unfinished"></translation> </message> <message> <source>Set logarithmic</source> <translation type="unfinished"></translation> </message> <message> <source>Please enter a new value between -96.0 dBV and 6.0 dBV:</source> <translation type="unfinished"></translation> </message> <message> <source>Please enter a new value between %1 and %2:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LadspaControl</name> <message> <source>Link channels</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LadspaControlDialog</name> <message> <source>Link Channels</source> <translation type="unfinished"></translation> </message> <message> <source>Channel </source> <translation type="unfinished"></translation> </message> </context> <context> <name>LadspaControlView</name> <message> <source>Link channels</source> <translation type="unfinished"></translation> </message> <message> <source>Value:</source> <translation type="unfinished"></translation> </message> <message> <source>Sorry, no help available.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LadspaEffect</name> <message> <source>Unknown LADSPA plugin %1 requested.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LcdSpinBox</name> <message> <source>Please enter a new value between %1 and %2:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LfoController</name> <message> <source>LFO Controller</source> <translation type="unfinished"></translation> </message> <message> <source>Base value</source> <translation type="unfinished"></translation> </message> <message> <source>Oscillator speed</source> <translation type="unfinished"></translation> </message> <message> <source>Oscillator amount</source> <translation type="unfinished"></translation> </message> <message> <source>Oscillator phase</source> <translation type="unfinished"></translation> </message> <message> <source>Oscillator waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Frequency Multiplier</source> <translation type="unfinished"></translation> </message> </context> <context> <name>LfoControllerDialog</name> <message> <source>LFO</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Controller</source> <translation type="unfinished"></translation> </message> <message> <source>BASE</source> <translation type="unfinished"></translation> </message> <message> <source>Base amount:</source> <translation type="unfinished"></translation> </message> <message> <source>todo</source> <translation type="unfinished"></translation> </message> <message> <source>SPD</source> <translation type="unfinished"></translation> </message> <message> <source>LFO-speed:</source> <translation type="unfinished">سرعت-LFO:</translation> </message> <message> <source>Use this knob for setting speed of the LFO. The bigger this value the faster the LFO oscillates and the faster the effect.</source> <translation type="unfinished"></translation> </message> <message> <source>AMT</source> <translation type="unfinished"></translation> </message> <message> <source>Modulation amount:</source> <translation type="unfinished">میزان مدولاسیون:</translation> </message> <message> <source>Use this knob for setting modulation amount of the LFO. The bigger this value, the more the connected control (e.g. volume or cutoff-frequency) will be influenced by the LFO.</source> <translation type="unfinished"></translation> </message> <message> <source>PHS</source> <translation type="unfinished"></translation> </message> <message> <source>Phase offset:</source> <translation type="unfinished"></translation> </message> <message> <source>degrees</source> <translation type="unfinished">درجه ها</translation> </message> <message> <source>With this knob you can set the phase offset of the LFO. That means you can move the point within an oscillation where the oscillator begins to oscillate. For example if you have a sine-wave and have a phase-offset of 180 degrees the wave will first go down. It&apos;s the same with a square-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a sine-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a triangle-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a saw-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a square-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for an exponential wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for white-noise.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a user-defined shape. Double click to pick a file.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a moog saw-wave.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MainWindow</name> <message> <source>Working directory</source> <translation type="unfinished"></translation> </message> <message> <source>The LMMS working directory %1 does not exist. Create it now? You can change the directory later via Edit -&gt; Settings.</source> <translation type="unfinished"></translation> </message> <message> <source>Could not save config-file</source> <translation type="unfinished">پرونده ی تنظیمات ذخیره نشد</translation> </message> <message> <source>Could not save configuration file %1. You&apos;re probably not permitted to write to this file. Please make sure you have write-access to the file and try again.</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;New</source> <translation type="unfinished">&amp;جدید</translation> </message> <message> <source>&amp;Open...</source> <translation type="unfinished">&amp;باز کن...</translation> </message> <message> <source>&amp;Save</source> <translation type="unfinished">&amp;ذخیره کن</translation> </message> <message> <source>Save &amp;As...</source> <translation type="unfinished">ذ&amp;خیره به صورت...</translation> </message> <message> <source>Import...</source> <translation type="unfinished"></translation> </message> <message> <source>E&amp;xport...</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Quit</source> <translation type="unfinished">&amp;خروج</translation> </message> <message> <source>&amp;Edit</source> <translation type="unfinished"></translation> </message> <message> <source>Settings</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Tools</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Help</source> <translation type="unfinished">&amp;راهنما</translation> </message> <message> <source>Help</source> <translation type="unfinished">راهنما</translation> </message> <message> <source>What&apos;s this?</source> <translation type="unfinished">این چیست؟</translation> </message> <message> <source>About</source> <translation type="unfinished">درباره</translation> </message> <message> <source>Create new project</source> <translation type="unfinished">ایجاد پروژه ی جدید</translation> </message> <message> <source>Create new project from template</source> <translation type="unfinished"></translation> </message> <message> <source>Open existing project</source> <translation type="unfinished">باز کردن پروژه ی موجود</translation> </message> <message> <source>Recently opened projects</source> <translation type="unfinished"></translation> </message> <message> <source>Save current project</source> <translation type="unfinished">ذخیره ی پروژه ی جاری</translation> </message> <message> <source>Export current project</source> <translation type="unfinished">استخراج پروژه ی جاری</translation> </message> <message> <source>Show/hide Song-Editor</source> <translation type="unfinished"></translation> </message> <message> <source>By pressing this button, you can show or hide the Song-Editor. With the help of the Song-Editor you can edit song-playlist and specify when which track should be played. You can also insert and move samples (e.g. rap samples) directly into the playlist.</source> <translation type="unfinished"></translation> </message> <message> <source>Show/hide Beat+Bassline Editor</source> <translation type="unfinished"></translation> </message> <message> <source>By pressing this button, you can show or hide the Beat+Bassline Editor. The Beat+Bassline Editor is needed for creating beats, and for opening, adding, and removing channels, and for cutting, copying and pasting beat and bassline-patterns, and for other things like that.</source> <translation type="unfinished"></translation> </message> <message> <source>Show/hide Piano-Roll</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to show or hide the Piano-Roll. With the help of the Piano-Roll you can edit melodies in an easy way.</source> <translation type="unfinished"></translation> </message> <message> <source>Show/hide Automation Editor</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to show or hide the Automation Editor. With the help of the Automation Editor you can edit dynamic values in an easy way.</source> <translation type="unfinished"></translation> </message> <message> <source>Show/hide FX Mixer</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to show or hide the FX Mixer. The FX Mixer is a very powerful tool for managing effects for your song. You can insert effects into different effect-channels.</source> <translation type="unfinished"></translation> </message> <message> <source>Show/hide project notes</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to show or hide the project notes window. In this window you can put down your project notes.</source> <translation type="unfinished"></translation> </message> <message> <source>Show/hide controller rack</source> <translation type="unfinished"></translation> </message> <message> <source>Untitled</source> <translation type="unfinished"></translation> </message> <message> <source>LMMS %1</source> <translation type="unfinished">LMMS %1</translation> </message> <message> <source>Project not saved</source> <translation type="unfinished">پروژه ذخیره نشده</translation> </message> <message> <source>The current project was modified since last saving. Do you want to save it now?</source> <translation type="unfinished">پروژه جاری بعد از آخرین ذخیره تغییر یافته است.آیا اکنون مایل به ذخیره ی آن هستید؟</translation> </message> <message> <source>Help not available</source> <translation type="unfinished"></translation> </message> <message> <source>Currently there&apos;s no help available in LMMS. Please visit http://lmms.sf.net/wiki for documentation on LMMS.</source> <translation type="unfinished"></translation> </message> <message> <source>LMMS (*.mmp *.mmpz)</source> <translation type="unfinished"></translation> </message> <message> <source>Version %1</source> <translation type="unfinished"></translation> </message> <message> <source>Configuration file</source> <translation type="unfinished"></translation> </message> <message> <source>Error while parsing configuration file at line %1:%2: %3</source> <translation type="unfinished"></translation> </message> <message> <source>Volumes</source> <translation type="unfinished"></translation> </message> <message> <source>Undo</source> <translation type="unfinished"></translation> </message> <message> <source>Redo</source> <translation type="unfinished"></translation> </message> <message> <source>LMMS Project </source> <translation type="unfinished"></translation> </message> <message> <source>LMMS Project Template </source> <translation type="unfinished"></translation> </message> <message> <source>My Projects</source> <translation type="unfinished"></translation> </message> <message> <source>My Samples</source> <translation type="unfinished"></translation> </message> <message> <source>My Presets</source> <translation type="unfinished"></translation> </message> <message> <source>My Home</source> <translation type="unfinished"></translation> </message> <message> <source>My Computer</source> <translation type="unfinished"></translation> </message> <message> <source>Root Directory</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;File</source> <translation type="unfinished"></translation> </message> <message> <source>&amp;Recently Opened Projects</source> <translation type="unfinished"></translation> </message> <message> <source>Save as New &amp;Version</source> <translation type="unfinished"></translation> </message> <message> <source>E&amp;xport Tracks...</source> <translation type="unfinished"></translation> </message> <message> <source>Online Help</source> <translation type="unfinished"></translation> </message> <message> <source>What&apos;s This?</source> <translation type="unfinished"></translation> </message> <message> <source>Open Project</source> <translation type="unfinished"></translation> </message> <message> <source>Save Project</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MeterDialog</name> <message> <source>Meter Numerator</source> <translation type="unfinished"></translation> </message> <message> <source>Meter Denominator</source> <translation type="unfinished"></translation> </message> <message> <source>TIME SIG</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MeterModel</name> <message> <source>Numerator</source> <translation type="unfinished"></translation> </message> <message> <source>Denominator</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MidiAlsaRaw::setupWidget</name> <message> <source>DEVICE</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MidiAlsaSeq</name> <message> <source>DEVICE</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MidiController</name> <message> <source>MIDI Controller</source> <translation type="unfinished"></translation> </message> <message> <source>unnamed_midi_controller</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MidiImport</name> <message> <source>Setup incomplete</source> <translation type="unfinished"></translation> </message> <message> <source>You do not have set up a default soundfont in the settings dialog (Edit-&gt;Settings). Therefore no sound will be played back after importing this MIDI file. You should download a General MIDI soundfont, specify it in settings dialog and try again.</source> <translation type="unfinished"></translation> </message> <message> <source>You did not compile LMMS with support for SoundFont2 player, which is used to add default sound to imported MIDI files. Therefore no sound will be played back after importing this MIDI file.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MidiOss::setupWidget</name> <message> <source>DEVICE</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MidiPort</name> <message> <source>Input channel</source> <translation type="unfinished"></translation> </message> <message> <source>Output channel</source> <translation type="unfinished"></translation> </message> <message> <source>Input controller</source> <translation type="unfinished"></translation> </message> <message> <source>Output controller</source> <translation type="unfinished"></translation> </message> <message> <source>Fixed input velocity</source> <translation type="unfinished"></translation> </message> <message> <source>Fixed output velocity</source> <translation type="unfinished"></translation> </message> <message> <source>Output MIDI program</source> <translation type="unfinished"></translation> </message> <message> <source>Receive MIDI-events</source> <translation type="unfinished"></translation> </message> <message> <source>Send MIDI-events</source> <translation type="unfinished"></translation> </message> <message> <source>Fixed output note</source> <translation type="unfinished"></translation> </message> <message> <source>Base velocity</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MonstroInstrument</name> <message> <source>Osc 1 Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 1 Panning</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 1 Coarse detune</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 1 Fine detune left</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 1 Fine detune right</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 1 Stereo phase offset</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 1 Pulse width</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 1 Sync send on rise</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 1 Sync send on fall</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 2 Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 2 Panning</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 2 Coarse detune</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 2 Fine detune left</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 2 Fine detune right</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 2 Stereo phase offset</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 2 Waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 2 Sync Hard</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 2 Sync Reverse</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 3 Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 3 Panning</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 3 Coarse detune</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 3 Stereo phase offset</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 3 Sub-oscillator mix</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 3 Waveform 1</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 3 Waveform 2</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 3 Sync Hard</source> <translation type="unfinished"></translation> </message> <message> <source>Osc 3 Sync Reverse</source> <translation type="unfinished"></translation> </message> <message> <source>LFO 1 Waveform</source> <translation type="unfinished"></translation> </message> <message> <source>LFO 1 Attack</source> <translation type="unfinished"></translation> </message> <message> <source>LFO 1 Rate</source> <translation type="unfinished"></translation> </message> <message> <source>LFO 1 Phase</source> <translation type="unfinished"></translation> </message> <message> <source>LFO 2 Waveform</source> <translation type="unfinished"></translation> </message> <message> <source>LFO 2 Attack</source> <translation type="unfinished"></translation> </message> <message> <source>LFO 2 Rate</source> <translation type="unfinished"></translation> </message> <message> <source>LFO 2 Phase</source> <translation type="unfinished"></translation> </message> <message> <source>Env 1 Pre-delay</source> <translation type="unfinished"></translation> </message> <message> <source>Env 1 Attack</source> <translation type="unfinished"></translation> </message> <message> <source>Env 1 Hold</source> <translation type="unfinished"></translation> </message> <message> <source>Env 1 Decay</source> <translation type="unfinished"></translation> </message> <message> <source>Env 1 Sustain</source> <translation type="unfinished"></translation> </message> <message> <source>Env 1 Release</source> <translation type="unfinished"></translation> </message> <message> <source>Env 1 Slope</source> <translation type="unfinished"></translation> </message> <message> <source>Env 2 Pre-delay</source> <translation type="unfinished"></translation> </message> <message> <source>Env 2 Attack</source> <translation type="unfinished"></translation> </message> <message> <source>Env 2 Hold</source> <translation type="unfinished"></translation> </message> <message> <source>Env 2 Decay</source> <translation type="unfinished"></translation> </message> <message> <source>Env 2 Sustain</source> <translation type="unfinished"></translation> </message> <message> <source>Env 2 Release</source> <translation type="unfinished"></translation> </message> <message> <source>Env 2 Slope</source> <translation type="unfinished"></translation> </message> <message> <source>Osc2-3 modulation</source> <translation type="unfinished"></translation> </message> <message> <source>Selected view</source> <translation type="unfinished"></translation> </message> <message> <source>Vol1-Env1</source> <translation type="unfinished"></translation> </message> <message> <source>Vol1-Env2</source> <translation type="unfinished"></translation> </message> <message> <source>Vol1-LFO1</source> <translation type="unfinished"></translation> </message> <message> <source>Vol1-LFO2</source> <translation type="unfinished"></translation> </message> <message> <source>Vol2-Env1</source> <translation type="unfinished"></translation> </message> <message> <source>Vol2-Env2</source> <translation type="unfinished"></translation> </message> <message> <source>Vol2-LFO1</source> <translation type="unfinished"></translation> </message> <message> <source>Vol2-LFO2</source> <translation type="unfinished"></translation> </message> <message> <source>Vol3-Env1</source> <translation type="unfinished"></translation> </message> <message> <source>Vol3-Env2</source> <translation type="unfinished"></translation> </message> <message> <source>Vol3-LFO1</source> <translation type="unfinished"></translation> </message> <message> <source>Vol3-LFO2</source> <translation type="unfinished"></translation> </message> <message> <source>Phs1-Env1</source> <translation type="unfinished"></translation> </message> <message> <source>Phs1-Env2</source> <translation type="unfinished"></translation> </message> <message> <source>Phs1-LFO1</source> <translation type="unfinished"></translation> </message> <message> <source>Phs1-LFO2</source> <translation type="unfinished"></translation> </message> <message> <source>Phs2-Env1</source> <translation type="unfinished"></translation> </message> <message> <source>Phs2-Env2</source> <translation type="unfinished"></translation> </message> <message> <source>Phs2-LFO1</source> <translation type="unfinished"></translation> </message> <message> <source>Phs2-LFO2</source> <translation type="unfinished"></translation> </message> <message> <source>Phs3-Env1</source> <translation type="unfinished"></translation> </message> <message> <source>Phs3-Env2</source> <translation type="unfinished"></translation> </message> <message> <source>Phs3-LFO1</source> <translation type="unfinished"></translation> </message> <message> <source>Phs3-LFO2</source> <translation type="unfinished"></translation> </message> <message> <source>Pit1-Env1</source> <translation type="unfinished"></translation> </message> <message> <source>Pit1-Env2</source> <translation type="unfinished"></translation> </message> <message> <source>Pit1-LFO1</source> <translation type="unfinished"></translation> </message> <message> <source>Pit1-LFO2</source> <translation type="unfinished"></translation> </message> <message> <source>Pit2-Env1</source> <translation type="unfinished"></translation> </message> <message> <source>Pit2-Env2</source> <translation type="unfinished"></translation> </message> <message> <source>Pit2-LFO1</source> <translation type="unfinished"></translation> </message> <message> <source>Pit2-LFO2</source> <translation type="unfinished"></translation> </message> <message> <source>Pit3-Env1</source> <translation type="unfinished"></translation> </message> <message> <source>Pit3-Env2</source> <translation type="unfinished"></translation> </message> <message> <source>Pit3-LFO1</source> <translation type="unfinished"></translation> </message> <message> <source>Pit3-LFO2</source> <translation type="unfinished"></translation> </message> <message> <source>PW1-Env1</source> <translation type="unfinished"></translation> </message> <message> <source>PW1-Env2</source> <translation type="unfinished"></translation> </message> <message> <source>PW1-LFO1</source> <translation type="unfinished"></translation> </message> <message> <source>PW1-LFO2</source> <translation type="unfinished"></translation> </message> <message> <source>Sub3-Env1</source> <translation type="unfinished"></translation> </message> <message> <source>Sub3-Env2</source> <translation type="unfinished"></translation> </message> <message> <source>Sub3-LFO1</source> <translation type="unfinished"></translation> </message> <message> <source>Sub3-LFO2</source> <translation type="unfinished"></translation> </message> <message> <source>Sine wave</source> <translation type="unfinished"></translation> </message> <message> <source>Bandlimited Triangle wave</source> <translation type="unfinished"></translation> </message> <message> <source>Bandlimited Saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Bandlimited Ramp wave</source> <translation type="unfinished"></translation> </message> <message> <source>Bandlimited Square wave</source> <translation type="unfinished"></translation> </message> <message> <source>Bandlimited Moog saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Soft square wave</source> <translation type="unfinished"></translation> </message> <message> <source>Absolute sine wave</source> <translation type="unfinished"></translation> </message> <message> <source>Exponential wave</source> <translation type="unfinished"></translation> </message> <message> <source>White noise</source> <translation type="unfinished"></translation> </message> <message> <source>Digital Triangle wave</source> <translation type="unfinished"></translation> </message> <message> <source>Digital Saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Digital Ramp wave</source> <translation type="unfinished"></translation> </message> <message> <source>Digital Square wave</source> <translation type="unfinished"></translation> </message> <message> <source>Digital Moog saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Triangle wave</source> <translation type="unfinished"></translation> </message> <message> <source>Saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Ramp wave</source> <translation type="unfinished"></translation> </message> <message> <source>Square wave</source> <translation type="unfinished"></translation> </message> <message> <source>Moog saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Abs. sine wave</source> <translation type="unfinished"></translation> </message> <message> <source>Random</source> <translation type="unfinished"></translation> </message> <message> <source>Random smooth</source> <translation type="unfinished"></translation> </message> </context> <context> <name>MonstroView</name> <message> <source>Operators view</source> <translation type="unfinished"></translation> </message> <message> <source>The Operators view contains all the operators. These include both audible operators (oscillators) and inaudible operators, or modulators: Low-frequency oscillators and Envelopes. Knobs and other widgets in the Operators view have their own what&apos;s this -texts, so you can get more specific help for them that way. </source> <translation type="unfinished"></translation> </message> <message> <source>Matrix view</source> <translation type="unfinished"></translation> </message> <message> <source>The Matrix view contains the modulation matrix. Here you can define the modulation relationships between the various operators: Each audible operator (oscillators 1-3) has 3-4 properties that can be modulated by any of the modulators. Using more modulations consumes more CPU power. The view is divided to modulation targets, grouped by the target oscillator. Available targets are volume, pitch, phase, pulse width and sub-osc ratio. Note: some targets are specific to one oscillator only. Each modulation target has 4 knobs, one for each modulator. By default the knobs are at 0, which means no modulation. Turning a knob to 1 causes that modulator to affect the modulation target as much as possible. Turning it to -1 does the same, but the modulation is inversed. </source> <translation type="unfinished"></translation> </message> <message> <source>Mix Osc2 with Osc3</source> <translation type="unfinished"></translation> </message> <message> <source>Modulate amplitude of Osc3 with Osc2</source> <translation type="unfinished"></translation> </message> <message> <source>Modulate frequency of Osc3 with Osc2</source> <translation type="unfinished"></translation> </message> <message> <source>Modulate phase of Osc3 with Osc2</source> <translation type="unfinished"></translation> </message> <message> <source>The CRS knob changes the tuning of oscillator 1 in semitone steps. </source> <translation type="unfinished"></translation> </message> <message> <source>The CRS knob changes the tuning of oscillator 2 in semitone steps. </source> <translation type="unfinished"></translation> </message> <message> <source>The CRS knob changes the tuning of oscillator 3 in semitone steps. </source> <translation type="unfinished"></translation> </message> <message> <source>FTL and FTR change the finetuning of the oscillator for left and right channels respectively. These can add stereo-detuning to the oscillator which widens the stereo image and causes an illusion of space. </source> <translation type="unfinished"></translation> </message> <message> <source>The SPO knob modifies the difference in phase between left and right channels. Higher difference creates a wider stereo image. </source> <translation type="unfinished"></translation> </message> <message> <source>The PW knob controls the pulse width, also known as duty cycle, of oscillator 1. Oscillator 1 is a digital pulse wave oscillator, it doesn&apos;t produce bandlimited output, which means that you can use it as an audible oscillator but it will cause aliasing. You can also use it as an inaudible source of a sync signal, which can be used to synchronize oscillators 2 and 3. </source> <translation type="unfinished"></translation> </message> <message> <source>Send Sync on Rise: When enabled, the Sync signal is sent every time the state of oscillator 1 changes from low to high, ie. when the amplitude changes from -1 to 1. Oscillator 1&apos;s pitch, phase and pulse width may affect the timing of syncs, but its volume has no effect on them. Sync signals are sent independently for both left and right channels. </source> <translation type="unfinished"></translation> </message> <message> <source>Send Sync on Fall: When enabled, the Sync signal is sent every time the state of oscillator 1 changes from high to low, ie. when the amplitude changes from 1 to -1. Oscillator 1&apos;s pitch, phase and pulse width may affect the timing of syncs, but its volume has no effect on them. Sync signals are sent independently for both left and right channels. </source> <translation type="unfinished"></translation> </message> <message> <source>Hard sync: Every time the oscillator receives a sync signal from oscillator 1, its phase is reset to 0 + whatever its phase offset is. </source> <translation type="unfinished"></translation> </message> <message> <source>Reverse sync: Every time the oscillator receives a sync signal from oscillator 1, the amplitude of the oscillator gets inverted. </source> <translation type="unfinished"></translation> </message> <message> <source>Choose waveform for oscillator 2. </source> <translation type="unfinished"></translation> </message> <message> <source>Choose waveform for oscillator 3&apos;s first sub-osc. Oscillator 3 can smoothly interpolate between two different waveforms. </source> <translation type="unfinished"></translation> </message> <message> <source>Choose waveform for oscillator 3&apos;s second sub-osc. Oscillator 3 can smoothly interpolate between two different waveforms. </source> <translation type="unfinished"></translation> </message> <message> <source>The SUB knob changes the mixing ratio of the two sub-oscs of oscillator 3. Each sub-osc can be set to produce a different waveform, and oscillator 3 can smoothly interpolate between them. All incoming modulations to oscillator 3 are applied to both sub-oscs/waveforms in the exact same way. </source> <translation type="unfinished"></translation> </message> <message> <source>In addition to dedicated modulators, Monstro allows oscillator 3 to be modulated by the output of oscillator 2. Mix mode means no modulation: the outputs of the oscillators are simply mixed together. </source> <translation type="unfinished"></translation> </message> <message> <source>In addition to dedicated modulators, Monstro allows oscillator 3 to be modulated by the output of oscillator 2. AM means amplitude modulation: Oscillator 3&apos;s amplitude (volume) is modulated by oscillator 2. </source> <translation type="unfinished"></translation> </message> <message> <source>In addition to dedicated modulators, Monstro allows oscillator 3 to be modulated by the output of oscillator 2. FM means frequency modulation: Oscillator 3&apos;s frequency (pitch) is modulated by oscillator 2. The frequency modulation is implemented as phase modulation, which gives a more stable overall pitch than &quot;pure&quot; frequency modulation. </source> <translation type="unfinished"></translation> </message> <message> <source>In addition to dedicated modulators, Monstro allows oscillator 3 to be modulated by the output of oscillator 2. PM means phase modulation: Oscillator 3&apos;s phase is modulated by oscillator 2. It differs from frequency modulation in that the phase changes are not cumulative. </source> <translation type="unfinished"></translation> </message> <message> <source>Select the waveform for LFO 1. &quot;Random&quot; and &quot;Random smooth&quot; are special waveforms: they produce random output, where the rate of the LFO controls how often the state of the LFO changes. The smooth version interpolates between these states with cosine interpolation. These random modes can be used to give &quot;life&quot; to your presets - add some of that analog unpredictability... </source> <translation type="unfinished"></translation> </message> <message> <source>Select the waveform for LFO 2. &quot;Random&quot; and &quot;Random smooth&quot; are special waveforms: they produce random output, where the rate of the LFO controls how often the state of the LFO changes. The smooth version interpolates between these states with cosine interpolation. These random modes can be used to give &quot;life&quot; to your presets - add some of that analog unpredictability... </source> <translation type="unfinished"></translation> </message> <message> <source>Attack causes the LFO to come on gradually from the start of the note. </source> <translation type="unfinished"></translation> </message> <message> <source>Rate sets the speed of the LFO, measured in milliseconds per cycle. Can be synced to tempo. </source> <translation type="unfinished"></translation> </message> <message> <source>PHS controls the phase offset of the LFO. </source> <translation type="unfinished"></translation> </message> <message> <source>PRE, or pre-delay, delays the start of the envelope from the start of the note. 0 means no delay. </source> <translation type="unfinished"></translation> </message> <message> <source>ATT, or attack, controls how fast the envelope ramps up at start, measured in milliseconds. A value of 0 means instant. </source> <translation type="unfinished"></translation> </message> <message> <source>HOLD controls how long the envelope stays at peak after the attack phase. </source> <translation type="unfinished"></translation> </message> <message> <source>DEC, or decay, controls how fast the envelope falls off from its peak, measured in milliseconds it would take to go from peak to zero. The actual decay may be shorter if sustain is used. </source> <translation type="unfinished"></translation> </message> <message> <source>SUS, or sustain, controls the sustain level of the envelope. The decay phase will not go below this level as long as the note is held. </source> <translation type="unfinished"></translation> </message> <message> <source>REL, or release, controls how long the release is for the note, measured in how long it would take to fall from peak to zero. Actual release may be shorter, depending on at what phase the note is released. </source> <translation type="unfinished"></translation> </message> <message> <source>The slope knob controls the curve or shape of the envelope. A value of 0 creates straight rises and falls. Negative values create curves that start slowly, peak quickly and fall of slowly again. Positive values create curves that start and end quickly, and stay longer near the peaks. </source> <translation type="unfinished"></translation> </message> </context> <context> <name>MultitapEchoControlDialog</name> <message> <source>Length</source> <translation type="unfinished"></translation> </message> <message> <source>Step length:</source> <translation type="unfinished"></translation> </message> <message> <source>Dry</source> <translation type="unfinished"></translation> </message> <message> <source>Dry Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>Stages</source> <translation type="unfinished"></translation> </message> <message> <source>Lowpass stages:</source> <translation type="unfinished"></translation> </message> <message> <source>Swap inputs</source> <translation type="unfinished"></translation> </message> <message> <source>Swap left and right input channel for reflections</source> <translation type="unfinished"></translation> </message> </context> <context> <name>NesInstrument</name> <message> <source>Channel 1 Coarse detune</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 1 Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 1 Envelope length</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 1 Duty cycle</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 1 Sweep amount</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 1 Sweep rate</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 2 Coarse detune</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 2 Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 2 Envelope length</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 2 Duty cycle</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 2 Sweep amount</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 2 Sweep rate</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 3 Coarse detune</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 3 Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 4 Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 4 Envelope length</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 4 Noise frequency</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 4 Noise frequency sweep</source> <translation type="unfinished"></translation> </message> <message> <source>Master volume</source> <translation type="unfinished"></translation> </message> <message> <source>Vibrato</source> <translation type="unfinished"></translation> </message> </context> <context> <name>OscillatorObject</name> <message> <source>Osc %1 volume</source> <translation type="unfinished">حجم نوسان ساز %1</translation> </message> <message> <source>Osc %1 panning</source> <translation type="unfinished">تراز نوسان ساز %1</translation> </message> <message> <source>Osc %1 coarse detuning</source> <translation type="unfinished">کوک زمختی نوسان ساز %1</translation> </message> <message> <source>Osc %1 fine detuning left</source> <translation type="unfinished">کوک دقیق چپ نوسان ساز %1</translation> </message> <message> <source>Osc %1 fine detuning right</source> <translation type="unfinished">کوک دقیق راست نوسان ساز %1</translation> </message> <message> <source>Osc %1 phase-offset</source> <translation type="unfinished">انحراف فاز نوسان ساز %1</translation> </message> <message> <source>Osc %1 stereo phase-detuning</source> <translation type="unfinished">کوک فاز استریوی نوسان ساز %1</translation> </message> <message> <source>Osc %1 wave shape</source> <translation type="unfinished"></translation> </message> <message> <source>Modulation type %1</source> <translation type="unfinished"></translation> </message> <message> <source>Osc %1 waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Osc %1 harmonic</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PatmanView</name> <message> <source>Open other patch</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to open another patch-file. Loop and Tune settings are not reset.</source> <translation type="unfinished"></translation> </message> <message> <source>Loop</source> <translation type="unfinished"></translation> </message> <message> <source>Loop mode</source> <translation type="unfinished"></translation> </message> <message> <source>Here you can toggle the Loop mode. If enabled, PatMan will use the loop information available in the file.</source> <translation type="unfinished"></translation> </message> <message> <source>Tune</source> <translation type="unfinished"></translation> </message> <message> <source>Tune mode</source> <translation type="unfinished"></translation> </message> <message> <source>Here you can toggle the Tune mode. If enabled, PatMan will tune the sample to match the note&apos;s frequency.</source> <translation type="unfinished"></translation> </message> <message> <source>No file selected</source> <translation type="unfinished"></translation> </message> <message> <source>Open patch file</source> <translation type="unfinished"></translation> </message> <message> <source>Patch-Files (*.pat)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PatternView</name> <message> <source>double-click to open this pattern in piano-roll use mouse wheel to set volume of a step</source> <translation type="unfinished"></translation> </message> <message> <source>Open in piano-roll</source> <translation type="unfinished">در غلتک پیانو باز کن</translation> </message> <message> <source>Clear all notes</source> <translation type="unfinished">پاک کردن تمامی نت ها</translation> </message> <message> <source>Reset name</source> <translation type="unfinished">باز نشانی نام</translation> </message> <message> <source>Change name</source> <translation type="unfinished">تغییر نام</translation> </message> <message> <source>Add steps</source> <translation type="unfinished"></translation> </message> <message> <source>Remove steps</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PeakController</name> <message> <source>Peak Controller</source> <translation type="unfinished"></translation> </message> <message> <source>Peak Controller Bug</source> <translation type="unfinished"></translation> </message> <message> <source>Due to a bug in older version of LMMS, the peak controllers may not be connect properly. Please ensure that peak controllers are connected properly and re-save this file. Sorry for any inconvenience caused.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PeakControllerDialog</name> <message> <source>PEAK</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Controller</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PeakControllerEffectControlDialog</name> <message> <source>BASE</source> <translation type="unfinished"></translation> </message> <message> <source>Base amount:</source> <translation type="unfinished"></translation> </message> <message> <source>Modulation amount:</source> <translation type="unfinished">میزان مدولاسیون:</translation> </message> <message> <source>Attack:</source> <translation type="unfinished">تهاجم(Attack):</translation> </message> <message> <source>Release:</source> <translation type="unfinished">رهایی(Release):</translation> </message> <message> <source>AMNT</source> <translation type="unfinished"></translation> </message> <message> <source>MULT</source> <translation type="unfinished"></translation> </message> <message> <source>Amount Multiplicator:</source> <translation type="unfinished"></translation> </message> <message> <source>ATCK</source> <translation type="unfinished"></translation> </message> <message> <source>DCAY</source> <translation type="unfinished"></translation> </message> <message> <source>TRES</source> <translation type="unfinished"></translation> </message> <message> <source>Treshold:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PeakControllerEffectControls</name> <message> <source>Base value</source> <translation type="unfinished"></translation> </message> <message> <source>Modulation amount</source> <translation type="unfinished">مقدار مدولاسیون</translation> </message> <message> <source>Mute output</source> <translation type="unfinished"></translation> </message> <message> <source>Attack</source> <translation type="unfinished"></translation> </message> <message> <source>Release</source> <translation type="unfinished"></translation> </message> <message> <source>Abs Value</source> <translation type="unfinished"></translation> </message> <message> <source>Amount Multiplicator</source> <translation type="unfinished"></translation> </message> <message> <source>Treshold</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PianoRoll</name> <message> <source>Piano-Roll - %1</source> <translation>غلتک پیانو - %1</translation> </message> <message> <source>Piano-Roll - no pattern</source> <translation>غلتک پیانو - بدون الگو</translation> </message> <message> <source>Please open a pattern by double-clicking on it!</source> <translation>لطفا یک الگو را با دوبار کلیک روی أن باز کنید!</translation> </message> <message> <source>Last note</source> <translation type="unfinished"></translation> </message> <message> <source>Note lock</source> <translation type="unfinished"></translation> </message> <message> <source>Note Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Note Panning</source> <translation type="unfinished"></translation> </message> <message> <source>Mark/unmark current semitone</source> <translation type="unfinished"></translation> </message> <message> <source>Mark current scale</source> <translation type="unfinished"></translation> </message> <message> <source>Mark current chord</source> <translation type="unfinished"></translation> </message> <message> <source>Unmark all</source> <translation type="unfinished"></translation> </message> <message> <source>No scale</source> <translation type="unfinished"></translation> </message> <message> <source>No chord</source> <translation type="unfinished"></translation> </message> <message> <source>Volume: %1%</source> <translation type="unfinished"></translation> </message> <message> <source>Panning: %1% left</source> <translation type="unfinished"></translation> </message> <message> <source>Panning: %1% right</source> <translation type="unfinished"></translation> </message> <message> <source>Panning: center</source> <translation type="unfinished"></translation> </message> <message> <source>Please enter a new value between %1 and %2:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PianoRollWindow</name> <message> <source>Play/pause current pattern (Space)</source> <translation type="unfinished">پخش/مکث الگوی جاری (فاصله)</translation> </message> <message> <source>Record notes from MIDI-device/channel-piano</source> <translation type="unfinished"></translation> </message> <message> <source>Record notes from MIDI-device/channel-piano while playing song or BB track</source> <translation type="unfinished"></translation> </message> <message> <source>Stop playing of current pattern (Space)</source> <translation type="unfinished">توقف پخش الگوی جاری (فاصله)</translation> </message> <message> <source>Click here to play the current pattern. This is useful while editing it. The pattern is automatically looped when its end is reached.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to record notes from a MIDI-device or the virtual test-piano of the according channel-window to the current pattern. When recording all notes you play will be written to this pattern and you can play and edit them afterwards.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to record notes from a MIDI-device or the virtual test-piano of the according channel-window to the current pattern. When recording all notes you play will be written to this pattern and you will hear the song or BB track in the background.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to stop playback of current pattern.</source> <translation type="unfinished"></translation> </message> <message> <source>Draw mode (Shift+D)</source> <translation type="unfinished"></translation> </message> <message> <source>Erase mode (Shift+E)</source> <translation type="unfinished"></translation> </message> <message> <source>Select mode (Shift+S)</source> <translation type="unfinished"></translation> </message> <message> <source>Detune mode (Shift+T)</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and draw mode will be activated. In this mode you can add, resize and move notes. This is the default mode which is used most of the time. You can also press &apos;Shift+D&apos; on your keyboard to activate this mode. In this mode, hold Ctrl to temporarily go into select mode.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and erase mode will be activated. In this mode you can erase notes. You can also press &apos;Shift+E&apos; on your keyboard to activate this mode.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and select mode will be activated. In this mode you can select notes. Alternatively, you can hold Ctrl in draw mode to temporarily use select mode.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and detune mode will be activated. In this mode you can click a note to open its automation detuning. You can utilize this to slide notes from one to another. You can also press &apos;Shift+T&apos; on your keyboard to activate this mode.</source> <translation type="unfinished"></translation> </message> <message> <source>Cut selected notes (Ctrl+X)</source> <translation type="unfinished">برش نت های انتخاب شده(Ctrl+X)</translation> </message> <message> <source>Copy selected notes (Ctrl+C)</source> <translation type="unfinished">کپی نت های انتخاب شده(Ctrl+C)</translation> </message> <message> <source>Paste notes from clipboard (Ctrl+V)</source> <translation type="unfinished">چسباندن نت ها از حافظه ی موقت(Ctrl+V)</translation> </message> <message> <source>Click here and the selected notes will be cut into the clipboard. You can paste them anywhere in any pattern by clicking on the paste button.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and the selected notes will be copied into the clipboard. You can paste them anywhere in any pattern by clicking on the paste button.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here and the notes from the clipboard will be pasted at the first visible measure.</source> <translation type="unfinished"></translation> </message> <message> <source>This controls the magnification of an axis. It can be helpful to choose magnification for a specific task. For ordinary editing, the magnification should be fitted to your smallest notes. </source> <translation type="unfinished"></translation> </message> <message> <source>The &apos;Q&apos; stands for quantization, and controls the grid size notes and control points snap to. With smaller quantization values, you can draw shorter notes in Piano Roll, and more exact control points in the Automation Editor.</source> <translation type="unfinished"></translation> </message> <message> <source>This lets you select the length of new notes. &apos;Last Note&apos; means that LMMS will use the note length of the note you last edited</source> <translation type="unfinished"></translation> </message> <message> <source>The feature is directly connected to the context-menu on the virtual keyboard, to the left in Piano Roll. After you have chosen the scale you want in this drop-down menu, you can right click on a desired key in the virtual keyboard, and then choose &apos;Mark current Scale&apos;. LMMS will highlight all notes that belongs to the chosen scale, and in the key you have selected!</source> <translation type="unfinished"></translation> </message> <message> <source>Let you select a chord which LMMS then can draw or highlight.You can find the most common chords in this drop-down menu. After you have selected a chord, click anywhere to place the chord, and right click on the virtual keyboard to open context menu and highlight the chord. To return to single note placement, you need to choose &apos;No chord&apos; in this drop-down menu.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PianoView</name> <message> <source>Base note</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Plugin</name> <message> <source>Plugin not found</source> <translation type="unfinished"></translation> </message> <message> <source>The plugin &quot;%1&quot; wasn&apos;t found or could not be loaded! Reason: &quot;%2&quot;</source> <translation type="unfinished"></translation> </message> <message> <source>Error while loading plugin</source> <translation type="unfinished">در بارگذاری اضافات اشتباه رخ داد</translation> </message> <message> <source>Failed to load plugin &quot;%1&quot;!</source> <translation type="unfinished"></translation> </message> <message> <source>LMMS plugin %1 does not have a plugin descriptor named %2!</source> <translation type="unfinished"></translation> </message> </context> <context> <name>PluginBrowser</name> <message> <source>Instrument plugins</source> <translation type="unfinished"></translation> </message> <message> <source>Instrument browser</source> <translation type="unfinished"></translation> </message> <message> <source>Drag an instrument into either the Song-Editor, the Beat+Bassline Editor or into an existing instrument track.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ProjectNotes</name> <message> <source>Project notes</source> <translation type="unfinished">یادداشت های پروژه</translation> </message> <message> <source>Put down your project notes here.</source> <translation type="unfinished">یادداشت های پروژه ی خود را اینجا قرار دهید.</translation> </message> <message> <source>Edit Actions</source> <translation type="unfinished">ویرایش کنش ها</translation> </message> <message> <source>&amp;Undo</source> <translation type="unfinished">&amp;واچینی</translation> </message> <message> <source>Ctrl+Z</source> <translation type="unfinished">Ctrl+Z</translation> </message> <message> <source>&amp;Redo</source> <translation type="unfinished">&amp;بازچینی</translation> </message> <message> <source>Ctrl+Y</source> <translation type="unfinished">Ctrl+Y</translation> </message> <message> <source>&amp;Copy</source> <translation type="unfinished">&amp;کپی</translation> </message> <message> <source>Ctrl+C</source> <translation type="unfinished">Ctrl+C</translation> </message> <message> <source>Cu&amp;t</source> <translation type="unfinished">&amp;برش</translation> </message> <message> <source>Ctrl+X</source> <translation type="unfinished">Ctrl+X</translation> </message> <message> <source>&amp;Paste</source> <translation type="unfinished">&amp;چسباندن</translation> </message> <message> <source>Ctrl+V</source> <translation type="unfinished">Ctrl+V</translation> </message> <message> <source>Format Actions</source> <translation type="unfinished">قالب بندی کنش ها</translation> </message> <message> <source>&amp;Bold</source> <translation type="unfinished">&amp;برجسته</translation> </message> <message> <source>Ctrl+B</source> <translation type="unfinished">Ctrl+B</translation> </message> <message> <source>&amp;Italic</source> <translation type="unfinished">&amp;خوابیده</translation> </message> <message> <source>Ctrl+I</source> <translation type="unfinished">Ctrl+I</translation> </message> <message> <source>&amp;Underline</source> <translation type="unfinished">&amp;زیرخط</translation> </message> <message> <source>Ctrl+U</source> <translation type="unfinished">Ctrl+U</translation> </message> <message> <source>&amp;Left</source> <translation type="unfinished">&amp;چپ</translation> </message> <message> <source>Ctrl+L</source> <translation type="unfinished">Ctrl+L</translation> </message> <message> <source>C&amp;enter</source> <translation type="unfinished">&amp;مرکز</translation> </message> <message> <source>Ctrl+E</source> <translation type="unfinished">Ctrl+E</translation> </message> <message> <source>&amp;Right</source> <translation type="unfinished">&amp;راست</translation> </message> <message> <source>Ctrl+R</source> <translation type="unfinished">Ctrl+R</translation> </message> <message> <source>&amp;Justify</source> <translation type="unfinished">&amp;تراز</translation> </message> <message> <source>Ctrl+J</source> <translation type="unfinished">Ctrl+J</translation> </message> <message> <source>&amp;Color...</source> <translation type="unfinished">&amp;رنگ...</translation> </message> </context> <context> <name>ProjectRenderer</name> <message> <source>WAV-File (*.wav)</source> <translation type="unfinished"></translation> </message> <message> <source>Compressed OGG-File (*.ogg)</source> <translation type="unfinished">پرونده ی OGG فشرده شده(*.ogg)</translation> </message> </context> <context> <name>QObject</name> <message> <source>C</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>Db</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>C#</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>D</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>Eb</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>D#</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>E</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>Fb</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>Gb</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>F#</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>G</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>Ab</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>G#</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>A</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>Bb</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>A#</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> <message> <source>B</source> <comment>Note name</comment> <translation type="unfinished"></translation> </message> </context> <context> <name>QWidget</name> <message> <source>Name: </source> <translation type="unfinished"></translation> </message> <message> <source>Maker: </source> <translation type="unfinished"></translation> </message> <message> <source>Copyright: </source> <translation type="unfinished"></translation> </message> <message> <source>Requires Real Time: </source> <translation type="unfinished"></translation> </message> <message> <source>Yes</source> <translation type="unfinished"></translation> </message> <message> <source>No</source> <translation type="unfinished"></translation> </message> <message> <source>Real Time Capable: </source> <translation type="unfinished"></translation> </message> <message> <source>In Place Broken: </source> <translation type="unfinished"></translation> </message> <message> <source>Channels In: </source> <translation type="unfinished"></translation> </message> <message> <source>Channels Out: </source> <translation type="unfinished"></translation> </message> <message> <source>File: </source> <translation type="unfinished"></translation> </message> <message> <source>File: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>RenameDialog</name> <message> <source>Rename...</source> <translation type="unfinished">تغییر نام...</translation> </message> </context> <context> <name>SampleBuffer</name> <message> <source>Open audio file</source> <translation type="unfinished">باز کردن پرونده ی صوتی</translation> </message> <message> <source>Wave-Files (*.wav)</source> <translation type="unfinished"> Wave- پرونده های(*.wav)</translation> </message> <message> <source>OGG-Files (*.ogg)</source> <translation type="unfinished">OGG-پرونده های (*.ogg)</translation> </message> <message> <source>DrumSynth-Files (*.ds)</source> <translation type="unfinished"></translation> </message> <message> <source>FLAC-Files (*.flac)</source> <translation type="unfinished"></translation> </message> <message> <source>SPEEX-Files (*.spx)</source> <translation type="unfinished"></translation> </message> <message> <source>VOC-Files (*.voc)</source> <translation type="unfinished">VOC-پرونده های (*.voc)</translation> </message> <message> <source>AIFF-Files (*.aif *.aiff)</source> <translation type="unfinished">AIFF-پرونده های (*.aif *.aiff)</translation> </message> <message> <source>AU-Files (*.au)</source> <translation type="unfinished">AU-پرونده های (*.au)</translation> </message> <message> <source>RAW-Files (*.raw)</source> <translation type="unfinished">RAW-پرونده های (*.raw)</translation> </message> <message> <source>All Audio-Files (*.wav *.ogg *.ds *.flac *.spx *.voc *.aif *.aiff *.au *.raw)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SampleTCOView</name> <message> <source>double-click to select sample</source> <translation type="unfinished">برای انتخاب نمونه دوبار کلیک کنید</translation> </message> <message> <source>Delete (middle mousebutton)</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished">برش</translation> </message> <message> <source>Copy</source> <translation type="unfinished">کپی</translation> </message> <message> <source>Paste</source> <translation type="unfinished">چسباندن</translation> </message> <message> <source>Mute/unmute (&lt;Ctrl&gt; + middle click)</source> <translation type="unfinished"></translation> </message> <message> <source>Set/clear record</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SampleTrack</name> <message> <source>Sample track</source> <translation type="unfinished">تراک نمونه</translation> </message> <message> <source>Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Panning</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SampleTrackView</name> <message> <source>Track volume</source> <translation type="unfinished"></translation> </message> <message> <source>Channel volume:</source> <translation type="unfinished">حجم کانال:</translation> </message> <message> <source>VOL</source> <translation type="unfinished"></translation> </message> <message> <source>Panning</source> <translation type="unfinished"></translation> </message> <message> <source>Panning:</source> <translation type="unfinished"></translation> </message> <message> <source>PAN</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SetupDialog</name> <message> <source>Setup LMMS</source> <translation type="unfinished">برپایی LMMS</translation> </message> <message> <source>General settings</source> <translation type="unfinished"></translation> </message> <message> <source>BUFFER SIZE</source> <translation type="unfinished"></translation> </message> <message> <source>Reset to default-value</source> <translation type="unfinished"></translation> </message> <message> <source>MISC</source> <translation type="unfinished"></translation> </message> <message> <source>Enable tooltips</source> <translation type="unfinished"></translation> </message> <message> <source>Show restart warning after changing settings</source> <translation type="unfinished"></translation> </message> <message> <source>Display volume as dBV </source> <translation type="unfinished"></translation> </message> <message> <source>Compress project files per default</source> <translation type="unfinished"></translation> </message> <message> <source>One instrument track window mode</source> <translation type="unfinished"></translation> </message> <message> <source>HQ-mode for output audio-device</source> <translation type="unfinished"></translation> </message> <message> <source>Compact track buttons</source> <translation type="unfinished"></translation> </message> <message> <source>Sync VST plugins to host playback</source> <translation type="unfinished"></translation> </message> <message> <source>Enable note labels in piano roll</source> <translation type="unfinished"></translation> </message> <message> <source>Enable waveform display by default</source> <translation type="unfinished"></translation> </message> <message> <source>Keep effects running even without input</source> <translation type="unfinished"></translation> </message> <message> <source>Create backup file when saving a project</source> <translation type="unfinished"></translation> </message> <message> <source>LANGUAGE</source> <translation type="unfinished"></translation> </message> <message> <source>Paths</source> <translation type="unfinished"></translation> </message> <message> <source>LMMS working directory</source> <translation type="unfinished"></translation> </message> <message> <source>VST-plugin directory</source> <translation type="unfinished"></translation> </message> <message> <source>Artwork directory</source> <translation type="unfinished"></translation> </message> <message> <source>Background artwork</source> <translation type="unfinished"></translation> </message> <message> <source>FL Studio installation directory</source> <translation type="unfinished"></translation> </message> <message> <source>LADSPA plugin paths</source> <translation type="unfinished"></translation> </message> <message> <source>STK rawwave directory</source> <translation type="unfinished"></translation> </message> <message> <source>Default Soundfont File</source> <translation type="unfinished"></translation> </message> <message> <source>Performance settings</source> <translation type="unfinished"></translation> </message> <message> <source>UI effects vs. performance</source> <translation type="unfinished"></translation> </message> <message> <source>Smooth scroll in Song Editor</source> <translation type="unfinished"></translation> </message> <message> <source>Enable auto save feature</source> <translation type="unfinished"></translation> </message> <message> <source>Show playback cursor in AudioFileProcessor</source> <translation type="unfinished"></translation> </message> <message> <source>Audio settings</source> <translation type="unfinished"></translation> </message> <message> <source>AUDIO INTERFACE</source> <translation type="unfinished"></translation> </message> <message> <source>MIDI settings</source> <translation type="unfinished"></translation> </message> <message> <source>MIDI INTERFACE</source> <translation type="unfinished"></translation> </message> <message> <source>OK</source> <translation type="unfinished"></translation> </message> <message> <source>Cancel</source> <translation type="unfinished">لغو</translation> </message> <message> <source>Restart LMMS</source> <translation type="unfinished"></translation> </message> <message> <source>Please note that most changes won&apos;t take effect until you restart LMMS!</source> <translation type="unfinished"></translation> </message> <message> <source>Frames: %1 Latency: %2 ms</source> <translation type="unfinished"></translation> </message> <message> <source>Here you can setup the internal buffer-size used by LMMS. Smaller values result in a lower latency but also may cause unusable sound or bad performance, especially on older computers or systems with a non-realtime kernel.</source> <translation type="unfinished"></translation> </message> <message> <source>Choose LMMS working directory</source> <translation type="unfinished"></translation> </message> <message> <source>Choose your VST-plugin directory</source> <translation type="unfinished"></translation> </message> <message> <source>Choose artwork-theme directory</source> <translation type="unfinished"></translation> </message> <message> <source>Choose FL Studio installation directory</source> <translation type="unfinished"></translation> </message> <message> <source>Choose LADSPA plugin directory</source> <translation type="unfinished"></translation> </message> <message> <source>Choose STK rawwave directory</source> <translation type="unfinished"></translation> </message> <message> <source>Choose default SoundFont</source> <translation type="unfinished"></translation> </message> <message> <source>Choose background artwork</source> <translation type="unfinished"></translation> </message> <message> <source>Here you can select your preferred audio-interface. Depending on the configuration of your system during compilation time you can choose between ALSA, JACK, OSS and more. Below you see a box which offers controls to setup the selected audio-interface.</source> <translation type="unfinished"></translation> </message> <message> <source>Here you can select your preferred MIDI-interface. Depending on the configuration of your system during compilation time you can choose between ALSA, OSS and more. Below you see a box which offers controls to setup the selected MIDI-interface.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Song</name> <message> <source>Tempo</source> <translation type="unfinished"></translation> </message> <message> <source>Master volume</source> <translation type="unfinished"></translation> </message> <message> <source>Master pitch</source> <translation type="unfinished"></translation> </message> <message> <source>Project saved</source> <translation type="unfinished"></translation> </message> <message> <source>The project %1 is now saved.</source> <translation type="unfinished"></translation> </message> <message> <source>Project NOT saved.</source> <translation type="unfinished">پروژه ذخیره نشد.</translation> </message> <message> <source>The project %1 was not saved!</source> <translation type="unfinished"></translation> </message> <message> <source>Import file</source> <translation type="unfinished">وارد کردن پرونده</translation> </message> <message> <source>MIDI sequences</source> <translation type="unfinished"></translation> </message> <message> <source>FL Studio projects</source> <translation type="unfinished"></translation> </message> <message> <source>Hydrogen projects</source> <translation type="unfinished"></translation> </message> <message> <source>All file types</source> <translation type="unfinished"></translation> </message> <message> <source>Empty project</source> <translation type="unfinished"></translation> </message> <message> <source>This project is empty so exporting makes no sense. Please put some items into Song Editor first!</source> <translation type="unfinished"></translation> </message> <message> <source>Select directory for writing exported tracks...</source> <translation type="unfinished"></translation> </message> <message> <source>untitled</source> <translation type="unfinished">بدون نام</translation> </message> <message> <source>Select file for project-export...</source> <translation type="unfinished">پرونده را برای استخراج پروژه مشخص کنید...</translation> </message> <message> <source>The following errors occured while loading: </source> <translation type="unfinished"></translation> </message> </context> <context> <name>SongEditor</name> <message> <source>Could not open file</source> <translation>پرونده باز نشد</translation> </message> <message> <source>Could not write file</source> <translation>پرونده نوشته نشد</translation> </message> <message> <source>Could not open file %1. You probably have no permissions to read this file. Please make sure to have at least read permissions to the file and try again.</source> <translation type="unfinished"></translation> </message> <message> <source>Error in file</source> <translation type="unfinished"></translation> </message> <message> <source>The file %1 seems to contain errors and therefore can&apos;t be loaded.</source> <translation type="unfinished"></translation> </message> <message> <source>Tempo</source> <translation type="unfinished"></translation> </message> <message> <source>TEMPO/BPM</source> <translation type="unfinished"></translation> </message> <message> <source>tempo of song</source> <translation type="unfinished">گام ترانه(tempo)</translation> </message> <message> <source>The tempo of a song is specified in beats per minute (BPM). If you want to change the tempo of your song, change this value. Every measure has four beats, so the tempo in BPM specifies, how many measures / 4 should be played within a minute (or how many measures should be played within four minutes).</source> <translation type="unfinished"></translation> </message> <message> <source>High quality mode</source> <translation type="unfinished"></translation> </message> <message> <source>Master volume</source> <translation type="unfinished"></translation> </message> <message> <source>master volume</source> <translation type="unfinished"></translation> </message> <message> <source>Master pitch</source> <translation type="unfinished"></translation> </message> <message> <source>master pitch</source> <translation type="unfinished">دانگ صدا(Pitch)</translation> </message> <message> <source>Value: %1%</source> <translation type="unfinished"></translation> </message> <message> <source>Value: %1 semitones</source> <translation type="unfinished"></translation> </message> <message> <source>Could not open %1 for writing. You probably are not permitted to write to this file. Please make sure you have write-access to the file and try again.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SongEditorWindow</name> <message> <source>Song-Editor</source> <translation type="unfinished">ویرایشگر ترانه</translation> </message> <message> <source>Play song (Space)</source> <translation type="unfinished">پخش ترانه(فاصله)</translation> </message> <message> <source>Record samples from Audio-device</source> <translation type="unfinished"></translation> </message> <message> <source>Record samples from Audio-device while playing song or BB track</source> <translation type="unfinished"></translation> </message> <message> <source>Stop song (Space)</source> <translation type="unfinished">توقف ترانه (فاصله)</translation> </message> <message> <source>Add beat/bassline</source> <translation type="unfinished">اضافه ی خط بم/تپش (beat/baseline)</translation> </message> <message> <source>Add sample-track</source> <translation type="unfinished">اضافه ی باریکه ی نمونه</translation> </message> <message> <source>Add automation-track</source> <translation type="unfinished"></translation> </message> <message> <source>Draw mode</source> <translation type="unfinished"></translation> </message> <message> <source>Edit mode (select and move)</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to play your whole song. Playing will be started at the song-position-marker (green). You can also move it while playing.</source> <translation type="unfinished">اگر می خواهید تمام ترانه ی خود را پخش کنید اینجا را کلیک کنید.پخش از محل سازنده ی موقعیت شروع خواهد شد(سبز).همچنین می توانید در حال پخش آن را جابجا کنید.</translation> </message> <message> <source>Click here, if you want to stop playing of your song. The song-position-marker will be set to the start of your song.</source> <translation type="unfinished">اگر می خواهید پخش ترانه ی خود را متوقف کنید اینجا را کلیک کنید.سازنده موقعیت ترانه به شروع ترانه تنظیم خواهد شد.</translation> </message> </context> <context> <name>SpectrumAnalyzerControlDialog</name> <message> <source>Linear spectrum</source> <translation type="unfinished"></translation> </message> <message> <source>Linear Y axis</source> <translation type="unfinished"></translation> </message> </context> <context> <name>SpectrumAnalyzerControls</name> <message> <source>Linear spectrum</source> <translation type="unfinished"></translation> </message> <message> <source>Linear Y axis</source> <translation type="unfinished"></translation> </message> <message> <source>Channel mode</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TabWidget</name> <message> <source>Settings for %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TempoSyncKnob</name> <message> <source>Tempo Sync</source> <translation type="unfinished"></translation> </message> <message> <source>No Sync</source> <translation type="unfinished"></translation> </message> <message> <source>Eight beats</source> <translation type="unfinished"></translation> </message> <message> <source>Whole note</source> <translation type="unfinished"></translation> </message> <message> <source>Half note</source> <translation type="unfinished"></translation> </message> <message> <source>Quarter note</source> <translation type="unfinished"></translation> </message> <message> <source>8th note</source> <translation type="unfinished"></translation> </message> <message> <source>16th note</source> <translation type="unfinished"></translation> </message> <message> <source>32nd note</source> <translation type="unfinished"></translation> </message> <message> <source>Custom...</source> <translation type="unfinished"></translation> </message> <message> <source>Custom </source> <translation type="unfinished"></translation> </message> <message> <source>Synced to Eight Beats</source> <translation type="unfinished"></translation> </message> <message> <source>Synced to Whole Note</source> <translation type="unfinished"></translation> </message> <message> <source>Synced to Half Note</source> <translation type="unfinished"></translation> </message> <message> <source>Synced to Quarter Note</source> <translation type="unfinished"></translation> </message> <message> <source>Synced to 8th Note</source> <translation type="unfinished"></translation> </message> <message> <source>Synced to 16th Note</source> <translation type="unfinished"></translation> </message> <message> <source>Synced to 32nd Note</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TimeDisplayWidget</name> <message> <source>click to change time units</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TimeLineWidget</name> <message> <source>Enable/disable auto-scrolling</source> <translation type="unfinished"></translation> </message> <message> <source>Enable/disable loop-points</source> <translation type="unfinished"></translation> </message> <message> <source>After stopping go back to begin</source> <translation type="unfinished"></translation> </message> <message> <source>After stopping go back to position at which playing was started</source> <translation type="unfinished"></translation> </message> <message> <source>After stopping keep position</source> <translation type="unfinished"></translation> </message> <message> <source>Hint</source> <translation type="unfinished"></translation> </message> <message> <source>Press &lt;Ctrl&gt; to disable magnetic loop points.</source> <translation type="unfinished"></translation> </message> <message> <source>Hold &lt;Shift&gt; to move the begin loop point; Press &lt;Ctrl&gt; to disable magnetic loop points.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>Track</name> <message> <source>Mute</source> <translation type="unfinished"></translation> </message> <message> <source>Solo</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TrackContainer</name> <message> <source>Couldn&apos;t import file</source> <translation type="unfinished"></translation> </message> <message> <source>Couldn&apos;t find a filter for importing file %1. You should convert this file into a format supported by LMMS using another software.</source> <translation type="unfinished"></translation> </message> <message> <source>Couldn&apos;t open file</source> <translation type="unfinished"></translation> </message> <message> <source>Couldn&apos;t open file %1 for reading. Please make sure you have read-permission to the file and the directory containing the file and try again!</source> <translation type="unfinished"></translation> </message> <message> <source>Loading project...</source> <translation type="unfinished">بارگذاری پروژه...</translation> </message> <message> <source>Cancel</source> <translation type="unfinished">لغو</translation> </message> <message> <source>Please wait...</source> <translation type="unfinished">لطفا صبر کنید...</translation> </message> <message> <source>Importing MIDI-file...</source> <translation type="unfinished">وارد کردن پرونده ی MIDI...</translation> </message> <message> <source>Importing FLP-file...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TrackContentObject</name> <message> <source>Muted</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TrackContentObjectView</name> <message> <source>Current position</source> <translation type="unfinished"></translation> </message> <message> <source>Hint</source> <translation type="unfinished"></translation> </message> <message> <source>Press &lt;Ctrl&gt; and drag to make a copy.</source> <translation type="unfinished"></translation> </message> <message> <source>Current length</source> <translation type="unfinished"></translation> </message> <message> <source>Press &lt;Ctrl&gt; for free resizing.</source> <translation type="unfinished"></translation> </message> <message> <source>%1:%2 (%3:%4 to %5:%6)</source> <translation type="unfinished"></translation> </message> <message> <source>Delete (middle mousebutton)</source> <translation type="unfinished"></translation> </message> <message> <source>Cut</source> <translation type="unfinished">برش</translation> </message> <message> <source>Copy</source> <translation type="unfinished">کپی</translation> </message> <message> <source>Paste</source> <translation type="unfinished">چسباندن</translation> </message> <message> <source>Mute/unmute (&lt;Ctrl&gt; + middle click)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TrackOperationsWidget</name> <message> <source>Press &lt;Ctrl&gt; while clicking on move-grip to begin a new drag&apos;n&apos;drop-action.</source> <translation type="unfinished"></translation> </message> <message> <source>Actions for this track</source> <translation type="unfinished"></translation> </message> <message> <source>Mute</source> <translation type="unfinished"></translation> </message> <message> <source>Solo</source> <translation type="unfinished"></translation> </message> <message> <source>Mute this track</source> <translation type="unfinished"></translation> </message> <message> <source>Clone this track</source> <translation type="unfinished">تکثیر این تراک</translation> </message> <message> <source>Remove this track</source> <translation type="unfinished"></translation> </message> <message> <source>Clear this track</source> <translation type="unfinished"></translation> </message> <message> <source>FX %1: %2</source> <translation type="unfinished"></translation> </message> <message> <source>Turn all recording on</source> <translation type="unfinished"></translation> </message> <message> <source>Turn all recording off</source> <translation type="unfinished"></translation> </message> </context> <context> <name>TripleOscillatorView</name> <message> <source>Use phase modulation for modulating oscillator 2 with oscillator 1</source> <translation type="unfinished"></translation> </message> <message> <source>Use amplitude modulation for modulating oscillator 2 with oscillator 1</source> <translation type="unfinished"></translation> </message> <message> <source>Mix output of oscillator 1 &amp; 2</source> <translation type="unfinished"></translation> </message> <message> <source>Synchronize oscillator 1 with oscillator 2</source> <translation type="unfinished"></translation> </message> <message> <source>Use frequency modulation for modulating oscillator 2 with oscillator 1</source> <translation type="unfinished"></translation> </message> <message> <source>Use phase modulation for modulating oscillator 3 with oscillator 2</source> <translation type="unfinished"></translation> </message> <message> <source>Use amplitude modulation for modulating oscillator 3 with oscillator 2</source> <translation type="unfinished"></translation> </message> <message> <source>Mix output of oscillator 2 &amp; 3</source> <translation type="unfinished"></translation> </message> <message> <source>Synchronize oscillator 2 with oscillator 3</source> <translation type="unfinished"></translation> </message> <message> <source>Use frequency modulation for modulating oscillator 3 with oscillator 2</source> <translation type="unfinished"></translation> </message> <message> <source>Osc %1 volume:</source> <translation type="unfinished">حجم نوسان ساز %1:</translation> </message> <message> <source>With this knob you can set the volume of oscillator %1. When setting a value of 0 the oscillator is turned off. Otherwise you can hear the oscillator as loud as you set it here.</source> <translation type="unfinished">با این دستگیره می توانید حجم نوسان ساز %1 را تنظیم کنید.هنگام تنظیم به ۰ ,نوسان ساز خاموش است.در غیر این صورت همان قدر که تنظیم کنید صدای نوسان سار را بلند خواهید شنید.</translation> </message> <message> <source>Osc %1 panning:</source> <translation type="unfinished">تراز نوسان ساز %1:</translation> </message> <message> <source>With this knob you can set the panning of the oscillator %1. A value of -100 means 100% left and a value of 100 moves oscillator-output right.</source> <translation type="unfinished">با این دستگیره می توانید تراز نوسان ساز %1 را تنظیم کنید.مقدار ۱۰۰- یعنی ۱۰۰٪ چپ و مقدار ۱۰۰ خروجی نوسان ساز را به راست منتقل می کند.</translation> </message> <message> <source>Osc %1 coarse detuning:</source> <translation type="unfinished">کوک زمختی نوسان ساز %1:</translation> </message> <message> <source>semitones</source> <translation type="unfinished"></translation> </message> <message> <source>With this knob you can set the coarse detuning of oscillator %1. You can detune the oscillator 24 semitones (2 octaves) up and down. This is useful for creating sounds with a chord.</source> <translation type="unfinished">با این دستگیره می توانید کوک زمختی نوسان ساز %1 را تنظیم کنید.شما می توانید کوک نوسان ساز را در ۱۲ نیم صدا (۱ نت) بالا یا پایین کنید. این برای ایجاد صدا به همراه زه (Chord) مفید خواهد بود.</translation> </message> <message> <source>Osc %1 fine detuning left:</source> <translation type="unfinished">کوک دقیق چپ نوسان ساز %1:</translation> </message> <message> <source>cents</source> <translation type="unfinished">درصد</translation> </message> <message> <source>With this knob you can set the fine detuning of oscillator %1 for the left channel. The fine-detuning is ranged between -100 cents and +100 cents. This is useful for creating &quot;fat&quot; sounds.</source> <translation type="unfinished">با این دستگیره می توانید کانال چپ نوسان ساز %1 را کوک دقیق کنید.کوک دقیق بین ۱۰۰- در صد و ۱۰۰ در صد محدود شده است.این برای ایجاد صدا های چاق (fat) مفید است.</translation> </message> <message> <source>Osc %1 fine detuning right:</source> <translation type="unfinished">کوک دقیق راست نوسان ساز %1:</translation> </message> <message> <source>With this knob you can set the fine detuning of oscillator %1 for the right channel. The fine-detuning is ranged between -100 cents and +100 cents. This is useful for creating &quot;fat&quot; sounds.</source> <translation type="unfinished">با این دستگیره می توانید کانال راست نوسان ساز %1 را کوک دقیق کنید.کوک دقیق بین ۱۰۰- در صد و ۱۰۰ در صد محدود شده است.این برای ایجاد صدا های چاق (fat) مفید است.</translation> </message> <message> <source>Osc %1 phase-offset:</source> <translation type="unfinished">انحراف فاز نوسان ساز %1:</translation> </message> <message> <source>degrees</source> <translation type="unfinished">درجه ها</translation> </message> <message> <source>With this knob you can set the phase-offset of oscillator %1. That means you can move the point within an oscillation where the oscillator begins to oscillate. For example if you have a sine-wave and have a phase-offset of 180 degrees the wave will first go down. It&apos;s the same with a square-wave.</source> <translation type="unfinished">با این دستگیره می توانید انحراف فاز نوسان ساز %1 را تنظیم کنید.این یعنی اینکه شما می توانید نقطه ی شروع نوسان نوسان ساز را جابجا کنید.برای مثال اگر یک موج سینوسی و انحراف فاز ۱۸۰ داشته باشید, موج در ابتدا به پایین می رود.برای موج مربعی نیز شبیه همین است.</translation> </message> <message> <source>Osc %1 stereo phase-detuning:</source> <translation type="unfinished">کوک فاز استریوی نوسان ساز %1:</translation> </message> <message> <source>With this knob you can set the stereo phase-detuning of oscillator %1. The stereo phase-detuning specifies the size of the difference between the phase-offset of left and right channel. This is very good for creating wide stereo sounds.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a sine-wave for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a triangle-wave for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a saw-wave for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a square-wave for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a moog-like saw-wave for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use an exponential wave for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use white-noise for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a user-defined waveform for current oscillator.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>VersionedSaveDialog</name> <message> <source>Increment version number</source> <translation type="unfinished"></translation> </message> <message> <source>Decrement version number</source> <translation type="unfinished"></translation> </message> </context> <context> <name>VestigeInstrumentView</name> <message> <source>Open other VST-plugin</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to open another VST-plugin. After clicking on this button, a file-open-dialog appears and you can select your file.</source> <translation type="unfinished"></translation> </message> <message> <source>Show/hide GUI</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to show or hide the graphical user interface (GUI) of your VST-plugin.</source> <translation type="unfinished"></translation> </message> <message> <source>Turn off all notes</source> <translation type="unfinished"></translation> </message> <message> <source>Open VST-plugin</source> <translation type="unfinished"></translation> </message> <message> <source>DLL-files (*.dll)</source> <translation type="unfinished"></translation> </message> <message> <source>EXE-files (*.exe)</source> <translation type="unfinished"></translation> </message> <message> <source>No VST-plugin loaded</source> <translation type="unfinished"></translation> </message> <message> <source>Control VST-plugin from LMMS host</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to control VST-plugin from host.</source> <translation type="unfinished"></translation> </message> <message> <source>Open VST-plugin preset</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to open another *.fxp, *.fxb VST-plugin preset.</source> <translation type="unfinished"></translation> </message> <message> <source>Previous (-)</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to switch to another VST-plugin preset program.</source> <translation type="unfinished"></translation> </message> <message> <source>Save preset</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to save current VST-plugin preset program.</source> <translation type="unfinished"></translation> </message> <message> <source>Next (+)</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to select presets that are currently loaded in VST.</source> <translation type="unfinished"></translation> </message> <message> <source>Preset</source> <translation type="unfinished"></translation> </message> <message> <source>by </source> <translation type="unfinished"></translation> </message> <message> <source> - VST plugin control</source> <translation type="unfinished"></translation> </message> </context> <context> <name>VisualizationWidget</name> <message> <source>click to enable/disable visualization of master-output</source> <translation type="unfinished">برای فعال / غیرفعال کردن تصور خروجی اصلی کلیک کنید</translation> </message> <message> <source>Click to enable</source> <translation type="unfinished"></translation> </message> </context> <context> <name>VstEffectControlDialog</name> <message> <source>Show/hide</source> <translation type="unfinished"></translation> </message> <message> <source>Control VST-plugin from LMMS host</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to control VST-plugin from host.</source> <translation type="unfinished"></translation> </message> <message> <source>Open VST-plugin preset</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to open another *.fxp, *.fxb VST-plugin preset.</source> <translation type="unfinished"></translation> </message> <message> <source>Previous (-)</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to switch to another VST-plugin preset program.</source> <translation type="unfinished"></translation> </message> <message> <source>Next (+)</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to select presets that are currently loaded in VST.</source> <translation type="unfinished"></translation> </message> <message> <source>Save preset</source> <translation type="unfinished"></translation> </message> <message> <source>Click here, if you want to save current VST-plugin preset program.</source> <translation type="unfinished"></translation> </message> <message> <source>Effect by: </source> <translation type="unfinished"></translation> </message> <message> <source>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&lt;br /&gt;</source> <translation type="unfinished"></translation> </message> </context> <context> <name>VstPlugin</name> <message> <source>Loading plugin</source> <translation type="unfinished"></translation> </message> <message> <source>Open Preset</source> <translation type="unfinished"></translation> </message> <message> <source>Vst Plugin Preset (*.fxp *.fxb)</source> <translation type="unfinished"></translation> </message> <message> <source>: default</source> <translation type="unfinished"></translation> </message> <message> <source>&quot;</source> <translation type="unfinished"></translation> </message> <message> <source>&apos;</source> <translation type="unfinished"></translation> </message> <message> <source>Save Preset</source> <translation type="unfinished"></translation> </message> <message> <source>.fxp</source> <translation type="unfinished"></translation> </message> <message> <source>.FXP</source> <translation type="unfinished"></translation> </message> <message> <source>.FXB</source> <translation type="unfinished"></translation> </message> <message> <source>.fxb</source> <translation type="unfinished"></translation> </message> <message> <source>Please wait while loading VST plugin...</source> <translation type="unfinished"></translation> </message> <message> <source>The VST plugin %1 could not be loaded.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WatsynInstrument</name> <message> <source>Volume A1</source> <translation type="unfinished"></translation> </message> <message> <source>Volume A2</source> <translation type="unfinished"></translation> </message> <message> <source>Volume B1</source> <translation type="unfinished"></translation> </message> <message> <source>Volume B2</source> <translation type="unfinished"></translation> </message> <message> <source>Panning A1</source> <translation type="unfinished"></translation> </message> <message> <source>Panning A2</source> <translation type="unfinished"></translation> </message> <message> <source>Panning B1</source> <translation type="unfinished"></translation> </message> <message> <source>Panning B2</source> <translation type="unfinished"></translation> </message> <message> <source>Freq. multiplier A1</source> <translation type="unfinished"></translation> </message> <message> <source>Freq. multiplier A2</source> <translation type="unfinished"></translation> </message> <message> <source>Freq. multiplier B1</source> <translation type="unfinished"></translation> </message> <message> <source>Freq. multiplier B2</source> <translation type="unfinished"></translation> </message> <message> <source>Left detune A1</source> <translation type="unfinished"></translation> </message> <message> <source>Left detune A2</source> <translation type="unfinished"></translation> </message> <message> <source>Left detune B1</source> <translation type="unfinished"></translation> </message> <message> <source>Left detune B2</source> <translation type="unfinished"></translation> </message> <message> <source>Right detune A1</source> <translation type="unfinished"></translation> </message> <message> <source>Right detune A2</source> <translation type="unfinished"></translation> </message> <message> <source>Right detune B1</source> <translation type="unfinished"></translation> </message> <message> <source>Right detune B2</source> <translation type="unfinished"></translation> </message> <message> <source>A-B Mix</source> <translation type="unfinished"></translation> </message> <message> <source>A-B Mix envelope amount</source> <translation type="unfinished"></translation> </message> <message> <source>A-B Mix envelope attack</source> <translation type="unfinished"></translation> </message> <message> <source>A-B Mix envelope hold</source> <translation type="unfinished"></translation> </message> <message> <source>A-B Mix envelope decay</source> <translation type="unfinished"></translation> </message> <message> <source>A1-B2 Crosstalk</source> <translation type="unfinished"></translation> </message> <message> <source>A2-A1 modulation</source> <translation type="unfinished"></translation> </message> <message> <source>B2-B1 modulation</source> <translation type="unfinished"></translation> </message> <message> <source>Selected graph</source> <translation type="unfinished"></translation> </message> </context> <context> <name>WatsynView</name> <message> <source>Select oscillator A1</source> <translation type="unfinished"></translation> </message> <message> <source>Select oscillator A2</source> <translation type="unfinished"></translation> </message> <message> <source>Select oscillator B1</source> <translation type="unfinished"></translation> </message> <message> <source>Select oscillator B2</source> <translation type="unfinished"></translation> </message> <message> <source>Mix output of A2 to A1</source> <translation type="unfinished"></translation> </message> <message> <source>Modulate amplitude of A1 with output of A2</source> <translation type="unfinished"></translation> </message> <message> <source>Ring-modulate A1 and A2</source> <translation type="unfinished"></translation> </message> <message> <source>Modulate phase of A1 with output of A2</source> <translation type="unfinished"></translation> </message> <message> <source>Mix output of B2 to B1</source> <translation type="unfinished"></translation> </message> <message> <source>Modulate amplitude of B1 with output of B2</source> <translation type="unfinished"></translation> </message> <message> <source>Ring-modulate B1 and B2</source> <translation type="unfinished"></translation> </message> <message> <source>Modulate phase of B1 with output of B2</source> <translation type="unfinished"></translation> </message> <message> <source>Draw your own waveform here by dragging your mouse on this graph.</source> <translation type="unfinished"></translation> </message> <message> <source>Load waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Click to load a waveform from a sample file</source> <translation type="unfinished"></translation> </message> <message> <source>Phase left</source> <translation type="unfinished"></translation> </message> <message> <source>Click to shift phase by -15 degrees</source> <translation type="unfinished"></translation> </message> <message> <source>Phase right</source> <translation type="unfinished"></translation> </message> <message> <source>Click to shift phase by +15 degrees</source> <translation type="unfinished"></translation> </message> <message> <source>Normalize</source> <translation type="unfinished"></translation> </message> <message> <source>Click to normalize</source> <translation type="unfinished"></translation> </message> <message> <source>Invert</source> <translation type="unfinished"></translation> </message> <message> <source>Click to invert</source> <translation type="unfinished"></translation> </message> <message> <source>Smooth</source> <translation type="unfinished"></translation> </message> <message> <source>Click to smooth</source> <translation type="unfinished"></translation> </message> <message> <source>Sine wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click for sine wave</source> <translation type="unfinished"></translation> </message> <message> <source>Triangle wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click for triangle wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click for saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Square wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click for square wave</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ZynAddSubFxInstrument</name> <message> <source>Portamento</source> <translation type="unfinished"></translation> </message> <message> <source>Filter Frequency</source> <translation type="unfinished"></translation> </message> <message> <source>Filter Resonance</source> <translation type="unfinished"></translation> </message> <message> <source>Bandwidth</source> <translation type="unfinished"></translation> </message> <message> <source>FM Gain</source> <translation type="unfinished"></translation> </message> <message> <source>Resonance Center Frequency</source> <translation type="unfinished"></translation> </message> <message> <source>Resonance Bandwidth</source> <translation type="unfinished"></translation> </message> <message> <source>Forward MIDI Control Change Events</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ZynAddSubFxView</name> <message> <source>Show GUI</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to show or hide the graphical user interface (GUI) of ZynAddSubFX.</source> <translation type="unfinished"></translation> </message> <message> <source>Portamento:</source> <translation type="unfinished"></translation> </message> <message> <source>PORT</source> <translation type="unfinished"></translation> </message> <message> <source>Filter Frequency:</source> <translation type="unfinished"></translation> </message> <message> <source>FREQ</source> <translation type="unfinished"></translation> </message> <message> <source>Filter Resonance:</source> <translation type="unfinished"></translation> </message> <message> <source>RES</source> <translation type="unfinished"></translation> </message> <message> <source>Bandwidth:</source> <translation type="unfinished"></translation> </message> <message> <source>BW</source> <translation type="unfinished"></translation> </message> <message> <source>FM Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>FM GAIN</source> <translation type="unfinished"></translation> </message> <message> <source>Resonance center frequency:</source> <translation type="unfinished"></translation> </message> <message> <source>RES CF</source> <translation type="unfinished"></translation> </message> <message> <source>Resonance bandwidth:</source> <translation type="unfinished"></translation> </message> <message> <source>RES BW</source> <translation type="unfinished"></translation> </message> <message> <source>Forward MIDI Control Changes</source> <translation type="unfinished"></translation> </message> </context> <context> <name>audioFileProcessor</name> <message> <source>Amplify</source> <translation>تقویت</translation> </message> <message> <source>Start of sample</source> <translation>شروع نمونه</translation> </message> <message> <source>End of sample</source> <translation>پایان نمونه</translation> </message> <message> <source>Reverse sample</source> <translation type="unfinished"></translation> </message> <message> <source>Stutter</source> <translation type="unfinished"></translation> </message> <message> <source>Loopback point</source> <translation type="unfinished"></translation> </message> <message> <source>Loop mode</source> <translation type="unfinished"></translation> </message> <message> <source>Interpolation mode</source> <translation type="unfinished"></translation> </message> <message> <source>None</source> <translation type="unfinished"></translation> </message> <message> <source>Linear</source> <translation type="unfinished"></translation> </message> <message> <source>Sinc</source> <translation type="unfinished"></translation> </message> <message> <source>Sample not found: %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>bitInvader</name> <message> <source>Samplelength</source> <translation type="unfinished"></translation> </message> </context> <context> <name>bitInvaderView</name> <message> <source>Sample Length</source> <translation type="unfinished"></translation> </message> <message> <source>Sine wave</source> <translation type="unfinished"></translation> </message> <message> <source>Triangle wave</source> <translation type="unfinished"></translation> </message> <message> <source>Saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Square wave</source> <translation type="unfinished"></translation> </message> <message> <source>White noise wave</source> <translation type="unfinished"></translation> </message> <message> <source>User defined wave</source> <translation type="unfinished"></translation> </message> <message> <source>Smooth</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to smooth waveform.</source> <translation type="unfinished"></translation> </message> <message> <source>Interpolation</source> <translation type="unfinished"></translation> </message> <message> <source>Normalize</source> <translation type="unfinished"></translation> </message> <message> <source>Draw your own waveform here by dragging your mouse on this graph.</source> <translation type="unfinished"></translation> </message> <message> <source>Click for a sine-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a triangle-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a saw-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a square-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for white-noise.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a user-defined shape.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>dynProcControlDialog</name> <message> <source>INPUT</source> <translation type="unfinished"></translation> </message> <message> <source>Input gain:</source> <translation type="unfinished"></translation> </message> <message> <source>OUTPUT</source> <translation type="unfinished"></translation> </message> <message> <source>Output gain:</source> <translation type="unfinished"></translation> </message> <message> <source>ATTACK</source> <translation type="unfinished"></translation> </message> <message> <source>Peak attack time:</source> <translation type="unfinished"></translation> </message> <message> <source>RELEASE</source> <translation type="unfinished"></translation> </message> <message> <source>Peak release time:</source> <translation type="unfinished"></translation> </message> <message> <source>Reset waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to reset the wavegraph back to default</source> <translation type="unfinished"></translation> </message> <message> <source>Smooth waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to apply smoothing to wavegraph</source> <translation type="unfinished"></translation> </message> <message> <source>Increase wavegraph amplitude by 1dB</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to increase wavegraph amplitude by 1dB</source> <translation type="unfinished"></translation> </message> <message> <source>Decrease wavegraph amplitude by 1dB</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to decrease wavegraph amplitude by 1dB</source> <translation type="unfinished"></translation> </message> <message> <source>Stereomode Maximum</source> <translation type="unfinished"></translation> </message> <message> <source>Process based on the maximum of both stereo channels</source> <translation type="unfinished"></translation> </message> <message> <source>Stereomode Average</source> <translation type="unfinished"></translation> </message> <message> <source>Process based on the average of both stereo channels</source> <translation type="unfinished"></translation> </message> <message> <source>Stereomode Unlinked</source> <translation type="unfinished"></translation> </message> <message> <source>Process each stereo channel independently</source> <translation type="unfinished"></translation> </message> </context> <context> <name>dynProcControls</name> <message> <source>Input gain</source> <translation type="unfinished"></translation> </message> <message> <source>Output gain</source> <translation type="unfinished"></translation> </message> <message> <source>Attack time</source> <translation type="unfinished"></translation> </message> <message> <source>Release time</source> <translation type="unfinished"></translation> </message> <message> <source>Stereo mode</source> <translation type="unfinished"></translation> </message> </context> <context> <name>graphModel</name> <message> <source>Graph</source> <translation type="unfinished"></translation> </message> </context> <context> <name>kickerInstrument</name> <message> <source>Start frequency</source> <translation type="unfinished"></translation> </message> <message> <source>End frequency</source> <translation type="unfinished"></translation> </message> <message> <source>Gain</source> <translation type="unfinished"></translation> </message> <message> <source>Length</source> <translation type="unfinished"></translation> </message> <message> <source>Distortion Start</source> <translation type="unfinished"></translation> </message> <message> <source>Distortion End</source> <translation type="unfinished"></translation> </message> <message> <source>Envelope Slope</source> <translation type="unfinished"></translation> </message> <message> <source>Noise</source> <translation type="unfinished"></translation> </message> <message> <source>Click</source> <translation type="unfinished"></translation> </message> <message> <source>Frequency Slope</source> <translation type="unfinished"></translation> </message> <message> <source>Start from note</source> <translation type="unfinished"></translation> </message> <message> <source>End to note</source> <translation type="unfinished"></translation> </message> </context> <context> <name>kickerInstrumentView</name> <message> <source>Start frequency:</source> <translation type="unfinished"></translation> </message> <message> <source>End frequency:</source> <translation type="unfinished"></translation> </message> <message> <source>Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>Frequency Slope:</source> <translation type="unfinished"></translation> </message> <message> <source>Envelope Length:</source> <translation type="unfinished"></translation> </message> <message> <source>Envelope Slope:</source> <translation type="unfinished"></translation> </message> <message> <source>Click:</source> <translation type="unfinished"></translation> </message> <message> <source>Noise:</source> <translation type="unfinished"></translation> </message> <message> <source>Distortion Start:</source> <translation type="unfinished"></translation> </message> <message> <source>Distortion End:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ladspaBrowserView</name> <message> <source>Available Effects</source> <translation type="unfinished"></translation> </message> <message> <source>Unavailable Effects</source> <translation type="unfinished"></translation> </message> <message> <source>Instruments</source> <translation type="unfinished"></translation> </message> <message> <source>Analysis Tools</source> <translation type="unfinished"></translation> </message> <message> <source>Don&apos;t know</source> <translation type="unfinished"></translation> </message> <message> <source>This dialog displays information on all of the LADSPA plugins LMMS was able to locate. The plugins are divided into five categories based upon an interpretation of the port types and names. Available Effects are those that can be used by LMMS. In order for LMMS to be able to use an effect, it must, first and foremost, be an effect, which is to say, it has to have both input channels and output channels. LMMS identifies an input channel as an audio rate port containing &apos;in&apos; in the name. Output channels are identified by the letters &apos;out&apos;. Furthermore, the effect must have the same number of inputs and outputs and be real time capable. Unavailable Effects are those that were identified as effects, but either didn&apos;t have the same number of input and output channels or weren&apos;t real time capable. Instruments are plugins for which only output channels were identified. Analysis Tools are plugins for which only input channels were identified. Don&apos;t Knows are plugins for which no input or output channels were identified. Double clicking any of the plugins will bring up information on the ports.</source> <translation type="unfinished"></translation> </message> <message> <source>Type:</source> <translation type="unfinished">نوع:</translation> </message> </context> <context> <name>ladspaDescription</name> <message> <source>Plugins</source> <translation type="unfinished"></translation> </message> <message> <source>Description</source> <translation type="unfinished"></translation> </message> </context> <context> <name>ladspaPortDialog</name> <message> <source>Ports</source> <translation type="unfinished"></translation> </message> <message> <source>Name</source> <translation type="unfinished"></translation> </message> <message> <source>Rate</source> <translation type="unfinished"></translation> </message> <message> <source>Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Type</source> <translation type="unfinished"></translation> </message> <message> <source>Min &lt; Default &lt; Max</source> <translation type="unfinished"></translation> </message> <message> <source>Logarithmic</source> <translation type="unfinished"></translation> </message> <message> <source>SR Dependent</source> <translation type="unfinished"></translation> </message> <message> <source>Audio</source> <translation type="unfinished"></translation> </message> <message> <source>Control</source> <translation type="unfinished"></translation> </message> <message> <source>Input</source> <translation type="unfinished"></translation> </message> <message> <source>Output</source> <translation type="unfinished"></translation> </message> <message> <source>Toggled</source> <translation type="unfinished"></translation> </message> <message> <source>Integer</source> <translation type="unfinished"></translation> </message> <message> <source>Float</source> <translation type="unfinished"></translation> </message> <message> <source>Yes</source> <translation type="unfinished"></translation> </message> </context> <context> <name>lb302Synth</name> <message> <source>VCF Cutoff Frequency</source> <translation type="unfinished"></translation> </message> <message> <source>VCF Resonance</source> <translation type="unfinished"></translation> </message> <message> <source>VCF Envelope Mod</source> <translation type="unfinished"></translation> </message> <message> <source>VCF Envelope Decay</source> <translation type="unfinished"></translation> </message> <message> <source>Distortion</source> <translation type="unfinished"></translation> </message> <message> <source>Waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Slide Decay</source> <translation type="unfinished"></translation> </message> <message> <source>Slide</source> <translation type="unfinished"></translation> </message> <message> <source>Accent</source> <translation type="unfinished"></translation> </message> <message> <source>Dead</source> <translation type="unfinished"></translation> </message> <message> <source>24dB/oct Filter</source> <translation type="unfinished"></translation> </message> </context> <context> <name>lb302SynthView</name> <message> <source>Cutoff Freq:</source> <translation type="unfinished"></translation> </message> <message> <source>Resonance:</source> <translation type="unfinished"></translation> </message> <message> <source>Env Mod:</source> <translation type="unfinished"></translation> </message> <message> <source>Decay:</source> <translation type="unfinished">محو شدن(Decay):</translation> </message> <message> <source>303-es-que, 24dB/octave, 3 pole filter</source> <translation type="unfinished"></translation> </message> <message> <source>Slide Decay:</source> <translation type="unfinished"></translation> </message> <message> <source>DIST:</source> <translation type="unfinished"></translation> </message> <message> <source>Saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a saw-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Triangle wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a triangle-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Square wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a square-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Rounded square wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a square-wave with a rounded end.</source> <translation type="unfinished"></translation> </message> <message> <source>Moog wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for a moog-like wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Sine wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click for a sine-wave.</source> <translation type="unfinished"></translation> </message> <message> <source>White noise wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for an exponential wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for white-noise.</source> <translation type="unfinished"></translation> </message> <message> <source>Bandlimited saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for bandlimited saw wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Bandlimited square wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for bandlimited square wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Bandlimited triangle wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for bandlimited triangle wave.</source> <translation type="unfinished"></translation> </message> <message> <source>Bandlimited moog saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Click here for bandlimited moog saw wave.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>lb303Synth</name> <message> <source>VCF Cutoff Frequency</source> <translation type="unfinished"></translation> </message> <message> <source>VCF Resonance</source> <translation type="unfinished"></translation> </message> <message> <source>VCF Envelope Mod</source> <translation type="unfinished"></translation> </message> <message> <source>VCF Envelope Decay</source> <translation type="unfinished"></translation> </message> <message> <source>Distortion</source> <translation type="unfinished"></translation> </message> <message> <source>Waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Slide Decay</source> <translation type="unfinished"></translation> </message> <message> <source>Slide</source> <translation type="unfinished"></translation> </message> <message> <source>Accent</source> <translation type="unfinished"></translation> </message> <message> <source>Dead</source> <translation type="unfinished"></translation> </message> <message> <source>24dB/oct Filter</source> <translation type="unfinished"></translation> </message> </context> <context> <name>lb303SynthView</name> <message> <source>Cutoff Freq:</source> <translation type="unfinished"></translation> </message> <message> <source>CUT</source> <translation type="unfinished"></translation> </message> <message> <source>Resonance:</source> <translation type="unfinished"></translation> </message> <message> <source>RES</source> <translation type="unfinished"></translation> </message> <message> <source>Env Mod:</source> <translation type="unfinished"></translation> </message> <message> <source>ENV MOD</source> <translation type="unfinished"></translation> </message> <message> <source>Decay:</source> <translation type="unfinished">محو شدن(Decay):</translation> </message> <message> <source>DEC</source> <translation type="unfinished"></translation> </message> <message> <source>303-es-que, 24dB/octave, 3 pole filter</source> <translation type="unfinished"></translation> </message> <message> <source>Slide Decay:</source> <translation type="unfinished"></translation> </message> <message> <source>SLIDE</source> <translation type="unfinished"></translation> </message> <message> <source>DIST:</source> <translation type="unfinished"></translation> </message> <message> <source>DIST</source> <translation type="unfinished"></translation> </message> <message> <source>WAVE:</source> <translation type="unfinished"></translation> </message> <message> <source>WAVE</source> <translation type="unfinished"></translation> </message> </context> <context> <name>malletsInstrument</name> <message> <source>Hardness</source> <translation type="unfinished"></translation> </message> <message> <source>Position</source> <translation type="unfinished"></translation> </message> <message> <source>Vibrato Gain</source> <translation type="unfinished"></translation> </message> <message> <source>Vibrato Freq</source> <translation type="unfinished"></translation> </message> <message> <source>Stick Mix</source> <translation type="unfinished"></translation> </message> <message> <source>Modulator</source> <translation type="unfinished"></translation> </message> <message> <source>Crossfade</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Speed</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Depth</source> <translation type="unfinished"></translation> </message> <message> <source>ADSR</source> <translation type="unfinished"></translation> </message> <message> <source>Pressure</source> <translation type="unfinished"></translation> </message> <message> <source>Motion</source> <translation type="unfinished"></translation> </message> <message> <source>Speed</source> <translation type="unfinished"></translation> </message> <message> <source>Bowed</source> <translation type="unfinished"></translation> </message> <message> <source>Spread</source> <translation type="unfinished"></translation> </message> <message> <source>Marimba</source> <translation type="unfinished"></translation> </message> <message> <source>Vibraphone</source> <translation type="unfinished"></translation> </message> <message> <source>Agogo</source> <translation type="unfinished"></translation> </message> <message> <source>Wood1</source> <translation type="unfinished"></translation> </message> <message> <source>Reso</source> <translation type="unfinished"></translation> </message> <message> <source>Wood2</source> <translation type="unfinished"></translation> </message> <message> <source>Beats</source> <translation type="unfinished"></translation> </message> <message> <source>Two Fixed</source> <translation type="unfinished"></translation> </message> <message> <source>Clump</source> <translation type="unfinished"></translation> </message> <message> <source>Tubular Bells</source> <translation type="unfinished"></translation> </message> <message> <source>Uniform Bar</source> <translation type="unfinished"></translation> </message> <message> <source>Tuned Bar</source> <translation type="unfinished"></translation> </message> <message> <source>Glass</source> <translation type="unfinished"></translation> </message> <message> <source>Tibetan Bowl</source> <translation type="unfinished"></translation> </message> <message> <source>Missing files</source> <translation type="unfinished"></translation> </message> <message> <source>Your Stk-installation seems to be incomplete. Please make sure the full Stk-package is installed!</source> <translation type="unfinished"></translation> </message> </context> <context> <name>malletsInstrumentView</name> <message> <source>Instrument</source> <translation type="unfinished"></translation> </message> <message> <source>Spread</source> <translation type="unfinished"></translation> </message> <message> <source>Spread:</source> <translation type="unfinished"></translation> </message> <message> <source>Hardness</source> <translation type="unfinished"></translation> </message> <message> <source>Hardness:</source> <translation type="unfinished"></translation> </message> <message> <source>Position</source> <translation type="unfinished"></translation> </message> <message> <source>Position:</source> <translation type="unfinished"></translation> </message> <message> <source>Vib Gain</source> <translation type="unfinished"></translation> </message> <message> <source>Vib Gain:</source> <translation type="unfinished"></translation> </message> <message> <source>Vib Freq</source> <translation type="unfinished"></translation> </message> <message> <source>Vib Freq:</source> <translation type="unfinished"></translation> </message> <message> <source>Stick Mix</source> <translation type="unfinished"></translation> </message> <message> <source>Stick Mix:</source> <translation type="unfinished"></translation> </message> <message> <source>Modulator</source> <translation type="unfinished"></translation> </message> <message> <source>Modulator:</source> <translation type="unfinished"></translation> </message> <message> <source>Crossfade</source> <translation type="unfinished"></translation> </message> <message> <source>Crossfade:</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Speed</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Speed:</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Depth</source> <translation type="unfinished"></translation> </message> <message> <source>LFO Depth:</source> <translation type="unfinished"></translation> </message> <message> <source>ADSR</source> <translation type="unfinished"></translation> </message> <message> <source>ADSR:</source> <translation type="unfinished"></translation> </message> <message> <source>Bowed</source> <translation type="unfinished"></translation> </message> <message> <source>Pressure</source> <translation type="unfinished"></translation> </message> <message> <source>Pressure:</source> <translation type="unfinished"></translation> </message> <message> <source>Motion</source> <translation type="unfinished"></translation> </message> <message> <source>Motion:</source> <translation type="unfinished"></translation> </message> <message> <source>Speed</source> <translation type="unfinished"></translation> </message> <message> <source>Speed:</source> <translation type="unfinished"></translation> </message> <message> <source>Vibrato</source> <translation type="unfinished"></translation> </message> <message> <source>Vibrato:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>manageVSTEffectView</name> <message> <source> - VST parameter control</source> <translation type="unfinished"></translation> </message> <message> <source>VST Sync</source> <translation type="unfinished"></translation> </message> <message> <source>Click here if you want to synchronize all parameters with VST plugin.</source> <translation type="unfinished"></translation> </message> <message> <source>Automated</source> <translation type="unfinished"></translation> </message> <message> <source>Click here if you want to display automated parameters only.</source> <translation type="unfinished"></translation> </message> <message> <source> Close </source> <translation type="unfinished"></translation> </message> <message> <source>Close VST effect knob-controller window.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>manageVestigeInstrumentView</name> <message> <source> - VST plugin control</source> <translation type="unfinished"></translation> </message> <message> <source>VST Sync</source> <translation type="unfinished"></translation> </message> <message> <source>Click here if you want to synchronize all parameters with VST plugin.</source> <translation type="unfinished"></translation> </message> <message> <source>Automated</source> <translation type="unfinished"></translation> </message> <message> <source>Click here if you want to display automated parameters only.</source> <translation type="unfinished"></translation> </message> <message> <source> Close </source> <translation type="unfinished"></translation> </message> <message> <source>Close VST plugin knob-controller window.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>opl2instrument</name> <message> <source>Patch</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Attack</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Decay</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Sustain</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Release</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Level</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Level Scaling</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Frequency Multiple</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Feedback</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Key Scaling Rate</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Percussive Envelope</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Tremolo</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Vibrato</source> <translation type="unfinished"></translation> </message> <message> <source>Op 1 Waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Attack</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Decay</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Sustain</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Release</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Level</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Level Scaling</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Frequency Multiple</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Key Scaling Rate</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Percussive Envelope</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Tremolo</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Vibrato</source> <translation type="unfinished"></translation> </message> <message> <source>Op 2 Waveform</source> <translation type="unfinished"></translation> </message> <message> <source>FM</source> <translation type="unfinished"></translation> </message> <message> <source>Vibrato Depth</source> <translation type="unfinished"></translation> </message> <message> <source>Tremolo Depth</source> <translation type="unfinished"></translation> </message> </context> <context> <name>organicInstrument</name> <message> <source>Distortion</source> <translation type="unfinished"></translation> </message> <message> <source>Volume</source> <translation type="unfinished"></translation> </message> </context> <context> <name>organicInstrumentView</name> <message> <source>Distortion:</source> <translation type="unfinished"></translation> </message> <message> <source>Volume:</source> <translation type="unfinished"></translation> </message> <message> <source>Randomise</source> <translation type="unfinished"></translation> </message> <message> <source>Osc %1 waveform:</source> <translation type="unfinished"></translation> </message> <message> <source>Osc %1 volume:</source> <translation type="unfinished">حجم نوسان ساز %1:</translation> </message> <message> <source>Osc %1 panning:</source> <translation type="unfinished">تراز نوسان ساز %1:</translation> </message> <message> <source>cents</source> <translation type="unfinished">درصد</translation> </message> <message> <source>The distortion knob adds distortion to the output of the instrument. </source> <translation type="unfinished"></translation> </message> <message> <source>The volume knob controls the volume of the output of the instrument. It is cumulative with the instrument window&apos;s volume control. </source> <translation type="unfinished"></translation> </message> <message> <source>The randomize button randomizes all knobs except the harmonics,main volume and distortion knobs. </source> <translation type="unfinished"></translation> </message> <message> <source>Osc %1 stereo detuning</source> <translation type="unfinished"></translation> </message> <message> <source>Osc %1 harmonic:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>papuInstrument</name> <message> <source>Sweep time</source> <translation type="unfinished"></translation> </message> <message> <source>Sweep direction</source> <translation type="unfinished"></translation> </message> <message> <source>Sweep RtShift amount</source> <translation type="unfinished"></translation> </message> <message> <source>Wave Pattern Duty</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 1 volume</source> <translation type="unfinished"></translation> </message> <message> <source>Volume sweep direction</source> <translation type="unfinished"></translation> </message> <message> <source>Length of each step in sweep</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 2 volume</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 3 volume</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 4 volume</source> <translation type="unfinished"></translation> </message> <message> <source>Right Output level</source> <translation type="unfinished"></translation> </message> <message> <source>Left Output level</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 1 to SO2 (Left)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 2 to SO2 (Left)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 3 to SO2 (Left)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 4 to SO2 (Left)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 1 to SO1 (Right)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 2 to SO1 (Right)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 3 to SO1 (Right)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel 4 to SO1 (Right)</source> <translation type="unfinished"></translation> </message> <message> <source>Treble</source> <translation type="unfinished"></translation> </message> <message> <source>Bass</source> <translation type="unfinished"></translation> </message> <message> <source>Shift Register width</source> <translation type="unfinished"></translation> </message> </context> <context> <name>papuInstrumentView</name> <message> <source>Sweep Time:</source> <translation type="unfinished"></translation> </message> <message> <source>Sweep Time</source> <translation type="unfinished"></translation> </message> <message> <source>Sweep RtShift amount:</source> <translation type="unfinished"></translation> </message> <message> <source>Sweep RtShift amount</source> <translation type="unfinished"></translation> </message> <message> <source>Wave pattern duty:</source> <translation type="unfinished"></translation> </message> <message> <source>Wave Pattern Duty</source> <translation type="unfinished"></translation> </message> <message> <source>Square Channel 1 Volume:</source> <translation type="unfinished"></translation> </message> <message> <source>Length of each step in sweep:</source> <translation type="unfinished"></translation> </message> <message> <source>Length of each step in sweep</source> <translation type="unfinished"></translation> </message> <message> <source>Wave pattern duty</source> <translation type="unfinished"></translation> </message> <message> <source>Square Channel 2 Volume:</source> <translation type="unfinished"></translation> </message> <message> <source>Square Channel 2 Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Wave Channel Volume:</source> <translation type="unfinished"></translation> </message> <message> <source>Wave Channel Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Noise Channel Volume:</source> <translation type="unfinished"></translation> </message> <message> <source>Noise Channel Volume</source> <translation type="unfinished"></translation> </message> <message> <source>SO1 Volume (Right):</source> <translation type="unfinished"></translation> </message> <message> <source>SO1 Volume (Right)</source> <translation type="unfinished"></translation> </message> <message> <source>SO2 Volume (Left):</source> <translation type="unfinished"></translation> </message> <message> <source>SO2 Volume (Left)</source> <translation type="unfinished"></translation> </message> <message> <source>Treble:</source> <translation type="unfinished"></translation> </message> <message> <source>Treble</source> <translation type="unfinished"></translation> </message> <message> <source>Bass:</source> <translation type="unfinished"></translation> </message> <message> <source>Bass</source> <translation type="unfinished"></translation> </message> <message> <source>Sweep Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Volume Sweep Direction</source> <translation type="unfinished"></translation> </message> <message> <source>Shift Register Width</source> <translation type="unfinished"></translation> </message> <message> <source>Channel1 to SO1 (Right)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel2 to SO1 (Right)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel3 to SO1 (Right)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel4 to SO1 (Right)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel1 to SO2 (Left)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel2 to SO2 (Left)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel3 to SO2 (Left)</source> <translation type="unfinished"></translation> </message> <message> <source>Channel4 to SO2 (Left)</source> <translation type="unfinished"></translation> </message> <message> <source>Wave Pattern</source> <translation type="unfinished"></translation> </message> <message> <source>The amount of increase or decrease in frequency</source> <translation type="unfinished"></translation> </message> <message> <source>The rate at which increase or decrease in frequency occurs</source> <translation type="unfinished"></translation> </message> <message> <source>The duty cycle is the ratio of the duration (time) that a signal is ON versus the total period of the signal.</source> <translation type="unfinished"></translation> </message> <message> <source>Square Channel 1 Volume</source> <translation type="unfinished"></translation> </message> <message> <source>The delay between step change</source> <translation type="unfinished"></translation> </message> <message> <source>Draw the wave here</source> <translation type="unfinished"></translation> </message> </context> <context> <name>pluginBrowser</name> <message> <source>no description</source> <translation type="unfinished"></translation> </message> <message> <source>Incomplete monophonic imitation tb303</source> <translation type="unfinished"></translation> </message> <message> <source>Plugin for freely manipulating stereo output</source> <translation type="unfinished"></translation> </message> <message> <source>Plugin for controlling knobs with sound peaks</source> <translation type="unfinished"></translation> </message> <message> <source>Plugin for enhancing stereo separation of a stereo input file</source> <translation type="unfinished"></translation> </message> <message> <source>List installed LADSPA plugins</source> <translation type="unfinished"></translation> </message> <message> <source>Filter for importing FL Studio projects into LMMS</source> <translation type="unfinished"></translation> </message> <message> <source>GUS-compatible patch instrument</source> <translation type="unfinished"></translation> </message> <message> <source>Additive Synthesizer for organ-like sounds</source> <translation type="unfinished"></translation> </message> <message> <source>Tuneful things to bang on</source> <translation type="unfinished"></translation> </message> <message> <source>VST-host for using VST(i)-plugins within LMMS</source> <translation type="unfinished"></translation> </message> <message> <source>Vibrating string modeler</source> <translation type="unfinished"></translation> </message> <message> <source>plugin for using arbitrary LADSPA-effects inside LMMS.</source> <translation type="unfinished"></translation> </message> <message> <source>Filter for importing MIDI-files into LMMS</source> <translation type="unfinished"></translation> </message> <message> <source>Emulation of the MOS6581 and MOS8580 SID. This chip was used in the Commodore 64 computer.</source> <translation type="unfinished"></translation> </message> <message> <source>Player for SoundFont files</source> <translation type="unfinished"></translation> </message> <message> <source>Emulation of GameBoy (TM) APU</source> <translation type="unfinished"></translation> </message> <message> <source>Customizable wavetable synthesizer</source> <translation type="unfinished"></translation> </message> <message> <source>Embedded ZynAddSubFX</source> <translation type="unfinished"></translation> </message> <message> <source>2-operator FM Synth</source> <translation type="unfinished"></translation> </message> <message> <source>Filter for importing Hydrogen files into LMMS</source> <translation type="unfinished"></translation> </message> <message> <source>LMMS port of sfxr</source> <translation type="unfinished"></translation> </message> <message> <source>Monstrous 3-oscillator synth with modulation matrix</source> <translation type="unfinished"></translation> </message> <message> <source>Three powerful oscillators you can modulate in several ways</source> <translation type="unfinished"></translation> </message> <message> <source>A native amplifier plugin</source> <translation type="unfinished"></translation> </message> <message> <source>Carla Rack Instrument</source> <translation type="unfinished"></translation> </message> <message> <source>4-oscillator modulatable wavetable synth</source> <translation type="unfinished"></translation> </message> <message> <source>plugin for waveshaping</source> <translation type="unfinished"></translation> </message> <message> <source>Boost your bass the fast and simple way</source> <translation type="unfinished"></translation> </message> <message> <source>Versatile drum synthesizer</source> <translation type="unfinished"></translation> </message> <message> <source>Simple sampler with various settings for using samples (e.g. drums) in an instrument-track</source> <translation type="unfinished"></translation> </message> <message> <source>plugin for processing dynamics in a flexible way</source> <translation type="unfinished"></translation> </message> <message> <source>Carla Patchbay Instrument</source> <translation type="unfinished"></translation> </message> <message> <source>plugin for using arbitrary VST effects inside LMMS.</source> <translation type="unfinished"></translation> </message> <message> <source>Graphical spectrum analyzer plugin</source> <translation type="unfinished"></translation> </message> <message> <source>A NES-like synthesizer</source> <translation type="unfinished"></translation> </message> <message> <source>Player for GIG files</source> <translation type="unfinished"></translation> </message> <message> <source>A multitap echo delay plugin</source> <translation type="unfinished"></translation> </message> <message> <source>A native flanger plugin</source> <translation type="unfinished"></translation> </message> <message> <source>A native delay plugin</source> <translation type="unfinished"></translation> </message> <message> <source>An oversampling bitcrusher</source> <translation type="unfinished"></translation> </message> <message> <source>A native eq plugin</source> <translation type="unfinished"></translation> </message> <message> <source>A 4-band Crossover Equalizer</source> <translation type="unfinished"></translation> </message> </context> <context> <name>setupWidget</name> <message> <source>JACK (JACK Audio Connection Kit)</source> <translation type="unfinished"></translation> </message> <message> <source>OSS Raw-MIDI (Open Sound System)</source> <translation type="unfinished"></translation> </message> <message> <source>SDL (Simple DirectMedia Layer)</source> <translation type="unfinished"></translation> </message> <message> <source>PulseAudio</source> <translation type="unfinished"></translation> </message> <message> <source>Dummy (no MIDI support)</source> <translation type="unfinished"></translation> </message> <message> <source>ALSA Raw-MIDI (Advanced Linux Sound Architecture)</source> <translation type="unfinished"></translation> </message> <message> <source>PortAudio</source> <translation type="unfinished"></translation> </message> <message> <source>Dummy (no sound output)</source> <translation type="unfinished"></translation> </message> <message> <source>ALSA (Advanced Linux Sound Architecture)</source> <translation type="unfinished"></translation> </message> <message> <source>OSS (Open Sound System)</source> <translation type="unfinished"></translation> </message> <message> <source>WinMM MIDI</source> <translation type="unfinished"></translation> </message> <message> <source>ALSA-Sequencer (Advanced Linux Sound Architecture)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>sf2Instrument</name> <message> <source>Bank</source> <translation type="unfinished"></translation> </message> <message> <source>Patch</source> <translation type="unfinished"></translation> </message> <message> <source>Gain</source> <translation type="unfinished"></translation> </message> <message> <source>Reverb</source> <translation type="unfinished"></translation> </message> <message> <source>Reverb Roomsize</source> <translation type="unfinished"></translation> </message> <message> <source>Reverb Damping</source> <translation type="unfinished"></translation> </message> <message> <source>Reverb Width</source> <translation type="unfinished"></translation> </message> <message> <source>Reverb Level</source> <translation type="unfinished"></translation> </message> <message> <source>Chorus</source> <translation type="unfinished"></translation> </message> <message> <source>Chorus Lines</source> <translation type="unfinished"></translation> </message> <message> <source>Chorus Level</source> <translation type="unfinished"></translation> </message> <message> <source>Chorus Speed</source> <translation type="unfinished"></translation> </message> <message> <source>Chorus Depth</source> <translation type="unfinished"></translation> </message> <message> <source>A soundfont %1 could not be loaded.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>sf2InstrumentView</name> <message> <source>Open other SoundFont file</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to open another SF2 file</source> <translation type="unfinished"></translation> </message> <message> <source>Choose the patch</source> <translation type="unfinished"></translation> </message> <message> <source>Gain</source> <translation type="unfinished"></translation> </message> <message> <source>Apply reverb (if supported)</source> <translation type="unfinished"></translation> </message> <message> <source>This button enables the reverb effect. This is useful for cool effects, but only works on files that support it.</source> <translation type="unfinished"></translation> </message> <message> <source>Reverb Roomsize:</source> <translation type="unfinished"></translation> </message> <message> <source>Reverb Damping:</source> <translation type="unfinished"></translation> </message> <message> <source>Reverb Width:</source> <translation type="unfinished"></translation> </message> <message> <source>Reverb Level:</source> <translation type="unfinished"></translation> </message> <message> <source>Apply chorus (if supported)</source> <translation type="unfinished"></translation> </message> <message> <source>This button enables the chorus effect. This is useful for cool echo effects, but only works on files that support it.</source> <translation type="unfinished"></translation> </message> <message> <source>Chorus Lines:</source> <translation type="unfinished"></translation> </message> <message> <source>Chorus Level:</source> <translation type="unfinished"></translation> </message> <message> <source>Chorus Speed:</source> <translation type="unfinished"></translation> </message> <message> <source>Chorus Depth:</source> <translation type="unfinished"></translation> </message> <message> <source>Open SoundFont file</source> <translation type="unfinished"></translation> </message> <message> <source>SoundFont2 Files (*.sf2)</source> <translation type="unfinished"></translation> </message> </context> <context> <name>sfxrInstrument</name> <message> <source>Wave Form</source> <translation type="unfinished"></translation> </message> </context> <context> <name>sidInstrument</name> <message> <source>Cutoff</source> <translation type="unfinished"></translation> </message> <message> <source>Resonance</source> <translation type="unfinished"></translation> </message> <message> <source>Filter type</source> <translation type="unfinished"></translation> </message> <message> <source>Voice 3 off</source> <translation type="unfinished"></translation> </message> <message> <source>Volume</source> <translation type="unfinished"></translation> </message> <message> <source>Chip model</source> <translation type="unfinished"></translation> </message> </context> <context> <name>sidInstrumentView</name> <message> <source>Volume:</source> <translation type="unfinished"></translation> </message> <message> <source>Resonance:</source> <translation type="unfinished"></translation> </message> <message> <source>Cutoff frequency:</source> <translation type="unfinished"></translation> </message> <message> <source>High-Pass filter </source> <translation type="unfinished"></translation> </message> <message> <source>Band-Pass filter </source> <translation type="unfinished"></translation> </message> <message> <source>Low-Pass filter </source> <translation type="unfinished"></translation> </message> <message> <source>Voice3 Off </source> <translation type="unfinished"></translation> </message> <message> <source>MOS6581 SID </source> <translation type="unfinished"></translation> </message> <message> <source>MOS8580 SID </source> <translation type="unfinished"></translation> </message> <message> <source>Attack:</source> <translation type="unfinished">تهاجم(Attack):</translation> </message> <message> <source>Attack rate determines how rapidly the output of Voice %1 rises from zero to peak amplitude.</source> <translation type="unfinished"></translation> </message> <message> <source>Decay:</source> <translation type="unfinished">محو شدن(Decay):</translation> </message> <message> <source>Decay rate determines how rapidly the output falls from the peak amplitude to the selected Sustain level.</source> <translation type="unfinished"></translation> </message> <message> <source>Sustain:</source> <translation type="unfinished">تقویت(Sustain):</translation> </message> <message> <source>Output of Voice %1 will remain at the selected Sustain amplitude as long as the note is held.</source> <translation type="unfinished"></translation> </message> <message> <source>Release:</source> <translation type="unfinished">رهایی(Release):</translation> </message> <message> <source>The output of of Voice %1 will fall from Sustain amplitude to zero amplitude at the selected Release rate.</source> <translation type="unfinished"></translation> </message> <message> <source>Pulse Width:</source> <translation type="unfinished"></translation> </message> <message> <source>The Pulse Width resolution allows the width to be smoothly swept with no discernable stepping. The Pulse waveform on Oscillator %1 must be selected to have any audible effect.</source> <translation type="unfinished"></translation> </message> <message> <source>Coarse:</source> <translation type="unfinished"></translation> </message> <message> <source>The Coarse detuning allows to detune Voice %1 one octave up or down.</source> <translation type="unfinished"></translation> </message> <message> <source>Pulse Wave</source> <translation type="unfinished"></translation> </message> <message> <source>Triangle Wave</source> <translation type="unfinished"></translation> </message> <message> <source>SawTooth</source> <translation type="unfinished"></translation> </message> <message> <source>Noise</source> <translation type="unfinished"></translation> </message> <message> <source>Sync</source> <translation type="unfinished"></translation> </message> <message> <source>Sync synchronizes the fundamental frequency of Oscillator %1 with the fundamental frequency of Oscillator %2 producing &quot;Hard Sync&quot; effects.</source> <translation type="unfinished"></translation> </message> <message> <source>Ring-Mod</source> <translation type="unfinished"></translation> </message> <message> <source>Ring-mod replaces the Triangle Waveform output of Oscillator %1 with a &quot;Ring Modulated&quot; combination of Oscillators %1 and %2.</source> <translation type="unfinished"></translation> </message> <message> <source>Filtered</source> <translation type="unfinished"></translation> </message> <message> <source>When Filtered is on, Voice %1 will be processed through the Filter. When Filtered is off, Voice %1 appears directly at the output, and the Filter has no effect on it.</source> <translation type="unfinished"></translation> </message> <message> <source>Test</source> <translation type="unfinished"></translation> </message> <message> <source>Test, when set, resets and locks Oscillator %1 at zero until Test is turned off.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>stereoEnhancerControlDialog</name> <message> <source>WIDE</source> <translation type="unfinished"></translation> </message> <message> <source>Width:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>stereoEnhancerControls</name> <message> <source>Width</source> <translation type="unfinished"></translation> </message> </context> <context> <name>stereoMatrixControlDialog</name> <message> <source>Left to Left Vol:</source> <translation type="unfinished"></translation> </message> <message> <source>Left to Right Vol:</source> <translation type="unfinished"></translation> </message> <message> <source>Right to Left Vol:</source> <translation type="unfinished"></translation> </message> <message> <source>Right to Right Vol:</source> <translation type="unfinished"></translation> </message> </context> <context> <name>stereoMatrixControls</name> <message> <source>Left to Left</source> <translation type="unfinished"></translation> </message> <message> <source>Left to Right</source> <translation type="unfinished"></translation> </message> <message> <source>Right to Left</source> <translation type="unfinished"></translation> </message> <message> <source>Right to Right</source> <translation type="unfinished"></translation> </message> </context> <context> <name>vestigeInstrument</name> <message> <source>Loading plugin</source> <translation type="unfinished"></translation> </message> <message> <source>Please wait while loading VST-plugin...</source> <translation type="unfinished"></translation> </message> </context> <context> <name>vibed</name> <message> <source>String %1 volume</source> <translation type="unfinished"></translation> </message> <message> <source>String %1 stiffness</source> <translation type="unfinished"></translation> </message> <message> <source>Pick %1 position</source> <translation type="unfinished"></translation> </message> <message> <source>Pickup %1 position</source> <translation type="unfinished"></translation> </message> <message> <source>Pan %1</source> <translation type="unfinished"></translation> </message> <message> <source>Detune %1</source> <translation type="unfinished"></translation> </message> <message> <source>Fuzziness %1 </source> <translation type="unfinished"></translation> </message> <message> <source>Length %1</source> <translation type="unfinished"></translation> </message> <message> <source>Impulse %1</source> <translation type="unfinished"></translation> </message> <message> <source>Octave %1</source> <translation type="unfinished"></translation> </message> </context> <context> <name>vibedView</name> <message> <source>Volume:</source> <translation type="unfinished"></translation> </message> <message> <source>The &apos;V&apos; knob sets the volume of the selected string.</source> <translation type="unfinished"></translation> </message> <message> <source>String stiffness:</source> <translation type="unfinished"></translation> </message> <message> <source>The &apos;S&apos; knob sets the stiffness of the selected string. The stiffness of the string affects how long the string will ring out. The lower the setting, the longer the string will ring.</source> <translation type="unfinished"></translation> </message> <message> <source>Pick position:</source> <translation type="unfinished">برگزیدن موقعیت:</translation> </message> <message> <source>The &apos;P&apos; knob sets the position where the selected string will be &apos;picked&apos;. The lower the setting the closer the pick is to the bridge.</source> <translation type="unfinished"></translation> </message> <message> <source>Pickup position:</source> <translation type="unfinished">برداشتن موقعیت:</translation> </message> <message> <source>The &apos;PU&apos; knob sets the position where the vibrations will be monitored for the selected string. The lower the setting, the closer the pickup is to the bridge.</source> <translation type="unfinished"></translation> </message> <message> <source>Pan:</source> <translation type="unfinished"></translation> </message> <message> <source>The Pan knob determines the location of the selected string in the stereo field.</source> <translation type="unfinished"></translation> </message> <message> <source>Detune:</source> <translation type="unfinished"></translation> </message> <message> <source>The Detune knob modifies the pitch of the selected string. Settings less than zero will cause the string to sound flat. Settings greater than zero will cause the string to sound sharp.</source> <translation type="unfinished"></translation> </message> <message> <source>Fuzziness:</source> <translation type="unfinished"></translation> </message> <message> <source>The Slap knob adds a bit of fuzz to the selected string which is most apparent during the attack, though it can also be used to make the string sound more &apos;metallic&apos;.</source> <translation type="unfinished"></translation> </message> <message> <source>Length:</source> <translation type="unfinished"></translation> </message> <message> <source>The Length knob sets the length of the selected string. Longer strings will both ring longer and sound brighter, however, they will also eat up more CPU cycles.</source> <translation type="unfinished"></translation> </message> <message> <source>Impulse or initial state</source> <translation type="unfinished"></translation> </message> <message> <source>The &apos;Imp&apos; selector determines whether the waveform in the graph is to be treated as an impulse imparted to the string by the pick or the initial state of the string.</source> <translation type="unfinished"></translation> </message> <message> <source>Octave</source> <translation type="unfinished"></translation> </message> <message> <source>The Octave selector is used to choose which harmonic of the note the string will ring at. For example, &apos;-2&apos; means the string will ring two octaves below the fundamental, &apos;F&apos; means the string will ring at the fundamental, and &apos;6&apos; means the string will ring six octaves above the fundamental.</source> <translation type="unfinished"></translation> </message> <message> <source>Impulse Editor</source> <translation type="unfinished"></translation> </message> <message> <source>The waveform editor provides control over the initial state or impulse that is used to start the string vibrating. The buttons to the right of the graph will initialize the waveform to the selected type. The &apos;?&apos; button will load a waveform from a file--only the first 128 samples will be loaded. The waveform can also be drawn in the graph. The &apos;S&apos; button will smooth the waveform. The &apos;N&apos; button will normalize the waveform.</source> <translation type="unfinished"></translation> </message> <message> <source>Vibed models up to nine independently vibrating strings. The &apos;String&apos; selector allows you to choose which string is being edited. The &apos;Imp&apos; selector chooses whether the graph represents an impulse or the initial state of the string. The &apos;Octave&apos; selector chooses which harmonic the string should vibrate at. The graph allows you to control the initial state or impulse used to set the string in motion. The &apos;V&apos; knob controls the volume. The &apos;S&apos; knob controls the string&apos;s stiffness. The &apos;P&apos; knob controls the pick position. The &apos;PU&apos; knob controls the pickup position. &apos;Pan&apos; and &apos;Detune&apos; hopefully don&apos;t need explanation. The &apos;Slap&apos; knob adds a bit of fuzz to the sound of the string. The &apos;Length&apos; knob controls the length of the string. The LED in the lower right corner of the waveform editor determines whether the string is active in the current instrument.</source> <translation type="unfinished"></translation> </message> <message> <source>Enable waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to enable/disable waveform.</source> <translation type="unfinished"></translation> </message> <message> <source>String</source> <translation type="unfinished"></translation> </message> <message> <source>The String selector is used to choose which string the controls are editing. A Vibed instrument can contain up to nine independently vibrating strings. The LED in the lower right corner of the waveform editor indicates whether the selected string is active.</source> <translation type="unfinished"></translation> </message> <message> <source>Sine wave</source> <translation type="unfinished"></translation> </message> <message> <source>Triangle wave</source> <translation type="unfinished"></translation> </message> <message> <source>Saw wave</source> <translation type="unfinished"></translation> </message> <message> <source>Square wave</source> <translation type="unfinished"></translation> </message> <message> <source>White noise wave</source> <translation type="unfinished"></translation> </message> <message> <source>User defined wave</source> <translation type="unfinished"></translation> </message> <message> <source>Smooth</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to smooth waveform.</source> <translation type="unfinished"></translation> </message> <message> <source>Normalize</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to normalize waveform.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a sine-wave for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a triangle-wave for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a saw-wave for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a square-wave for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use white-noise for current oscillator.</source> <translation type="unfinished"></translation> </message> <message> <source>Use a user-defined waveform for current oscillator.</source> <translation type="unfinished"></translation> </message> </context> <context> <name>voiceObject</name> <message> <source>Voice %1 pulse width</source> <translation type="unfinished"></translation> </message> <message> <source>Voice %1 attack</source> <translation type="unfinished"></translation> </message> <message> <source>Voice %1 decay</source> <translation type="unfinished"></translation> </message> <message> <source>Voice %1 sustain</source> <translation type="unfinished"></translation> </message> <message> <source>Voice %1 release</source> <translation type="unfinished"></translation> </message> <message> <source>Voice %1 coarse detuning</source> <translation type="unfinished"></translation> </message> <message> <source>Voice %1 wave shape</source> <translation type="unfinished"></translation> </message> <message> <source>Voice %1 sync</source> <translation type="unfinished"></translation> </message> <message> <source>Voice %1 ring modulate</source> <translation type="unfinished"></translation> </message> <message> <source>Voice %1 filtered</source> <translation type="unfinished"></translation> </message> <message> <source>Voice %1 test</source> <translation type="unfinished"></translation> </message> </context> <context> <name>waveShaperControlDialog</name> <message> <source>INPUT</source> <translation type="unfinished"></translation> </message> <message> <source>Input gain:</source> <translation type="unfinished"></translation> </message> <message> <source>OUTPUT</source> <translation type="unfinished"></translation> </message> <message> <source>Output gain:</source> <translation type="unfinished"></translation> </message> <message> <source>Reset waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to reset the wavegraph back to default</source> <translation type="unfinished"></translation> </message> <message> <source>Smooth waveform</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to apply smoothing to wavegraph</source> <translation type="unfinished"></translation> </message> <message> <source>Increase graph amplitude by 1dB</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to increase wavegraph amplitude by 1dB</source> <translation type="unfinished"></translation> </message> <message> <source>Decrease graph amplitude by 1dB</source> <translation type="unfinished"></translation> </message> <message> <source>Click here to decrease wavegraph amplitude by 1dB</source> <translation type="unfinished"></translation> </message> <message> <source>Clip input</source> <translation type="unfinished"></translation> </message> <message> <source>Clip input signal to 0dB</source> <translation type="unfinished"></translation> </message> </context> <context> <name>waveShaperControls</name> <message> <source>Input gain</source> <translation type="unfinished"></translation> </message> <message> <source>Output gain</source> <translation type="unfinished"></translation> </message> </context> </TS>
DanielAeolusLaude/lmms
data/locale/fa.ts
TypeScript
gpl-2.0
324,101
showWord(["","pratikan nan relijyon Vodou.<br>"])
georgejhunt/HaitiDictionary.activity
data/words/vodouyizan.js
JavaScript
gpl-2.0
49
package tutorial; /** * Main class that shows how to create your first working application. * * @author Maciej Spiechowicz */ public class Main { public static void main(String[] args) { // This line is responsible for printing a message System.out.println("Hello World!"); } }
MSpiechowicz/Programming
Java/Lesson01_HelloWorld/src/main/java/tutorial/Main.java
Java
gpl-2.0
310