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
require "docusign_transaction_rooms/version" require 'docusign_transaction_rooms/configuration' require 'active_support/all' require 'resource_kit' require 'kartograph' module DocusignTransactionRooms autoload :Client, 'docusign_transaction_rooms/client' # Models autoload :BaseModel, 'docusign_transaction_rooms/models/base_model' autoload :Office, 'docusign_transaction_rooms/models/office' autoload :Address, 'docusign_transaction_rooms/models/address' autoload :Integration, 'docusign_transaction_rooms/models/integration' autoload :RoomField, 'docusign_transaction_rooms/models/room_field' autoload :RoomFieldDetail, 'docusign_transaction_rooms/models/room_field_detail' autoload :Member, 'docusign_transaction_rooms/models/member' autoload :Profile, 'docusign_transaction_rooms/models/profile' autoload :Agent, 'docusign_transaction_rooms/models/agent' autoload :Profile, 'docusign_transaction_rooms/models/profile' autoload :Manager, 'docusign_transaction_rooms/models/manager' autoload :Access, 'docusign_transaction_rooms/models/access' autoload :Permissions, 'docusign_transaction_rooms/models/permissions' autoload :DefaultOffice, 'docusign_transaction_rooms/models/default_office' autoload :ContactInfo, 'docusign_transaction_rooms/models/contact_info' autoload :Room, 'docusign_transaction_rooms/models/room' autoload :Owner, 'docusign_transaction_rooms/models/owner' autoload :Details, 'docusign_transaction_rooms/models/details' autoload :TransactionParty, 'docusign_transaction_rooms/models/transaction_party' autoload :RoomContact, 'docusign_transaction_rooms/models/room_contact' autoload :RoomContactType, 'docusign_transaction_rooms/models/room_contact_type' autoload :RoomContactIntegration, 'docusign_transaction_rooms/models/room_contact_integration' autoload :AuctionDetails, 'docusign_transaction_rooms/models/auction_details' autoload :CreationDetails, 'docusign_transaction_rooms/models/creation_details' autoload :LoneWolfDetails, 'docusign_transaction_rooms/models/lone_wolf_details' autoload :AgentCommission, 'docusign_transaction_rooms/models/agent_commission' autoload :ExternalAgentCommission, 'docusign_transaction_rooms/models/external_agent_commission' autoload :ClientContact, 'docusign_transaction_rooms/models/client_contact' autoload :BusinessContact, 'docusign_transaction_rooms/models/business_contact' autoload :ProfitPowerDetails, 'docusign_transaction_rooms/models/profit_power_details' autoload :RoomActivity, 'docusign_transaction_rooms/models/room_activity' autoload :RoomApproval, 'docusign_transaction_rooms/models/room_approval' autoload :RoomDocument, 'docusign_transaction_rooms/models/room_document' autoload :RoomRejection, 'docusign_transaction_rooms/models/room_rejection' autoload :RoomSubmission, 'docusign_transaction_rooms/models/room_submission' autoload :RoomTaskList, 'docusign_transaction_rooms/models/room_task_list' autoload :User, 'docusign_transaction_rooms/models/user' autoload :Folder, 'docusign_transaction_rooms/models/room' autoload :Meta, 'docusign_transaction_rooms/models/meta' autoload :MetaInformation, 'docusign_transaction_rooms/models/meta_information' autoload :Title, 'docusign_transaction_rooms/models/title' autoload :Template, 'docusign_transaction_rooms/models/template' autoload :TemplateOffice, 'docusign_transaction_rooms/models/template_office' autoload :TemplateRegion, 'docusign_transaction_rooms/models/template_region' autoload :Inbox, 'docusign_transaction_rooms/models/inbox' autoload :Document, 'docusign_transaction_rooms/models/document' autoload :Region, 'docusign_transaction_rooms/models/region' autoload :TaskList, 'docusign_transaction_rooms/models/task_list' autoload :Task, 'docusign_transaction_rooms/models/task' autoload :TaskDocument, 'docusign_transaction_rooms/models/task_document' autoload :TaskReminder, 'docusign_transaction_rooms/models/task_reminder' autoload :TaskAssignment, 'docusign_transaction_rooms/models/task_assignment' # Resources autoload :CompanyResource, 'docusign_transaction_rooms/resources/company_resource' autoload :MemberResource, 'docusign_transaction_rooms/resources/member_resource' autoload :OfficeResource, 'docusign_transaction_rooms/resources/office_resource' autoload :RoomResource, 'docusign_transaction_rooms/resources/room_resource' autoload :MetaResource, 'docusign_transaction_rooms/resources/meta_resource' autoload :UserResource, 'docusign_transaction_rooms/resources/user_resource' autoload :TitleResource, 'docusign_transaction_rooms/resources/title_resource' autoload :TemplateResource, 'docusign_transaction_rooms/resources/template_resource' autoload :InboxResource, 'docusign_transaction_rooms/resources/inbox_resource' autoload :DocumentResource, 'docusign_transaction_rooms/resources/document_resource' autoload :LoneWolfMetaResource, 'docusign_transaction_rooms/resources/lone_wolf_meta_resource' autoload :RegionResource, 'docusign_transaction_rooms/resources/region_resource' autoload :TaskListResource, 'docusign_transaction_rooms/resources/task_list_resource' autoload :TaskResource, 'docusign_transaction_rooms/resources/task_resource' # JSON Maps autoload :OfficeMapping, 'docusign_transaction_rooms/mappings/office_mapping' autoload :IntegrationMapping, 'docusign_transaction_rooms/mappings/integration_mapping' autoload :RoomFieldMapping, 'docusign_transaction_rooms/mappings/room_field_mapping' autoload :MemberMapping, 'docusign_transaction_rooms/mappings/member_mapping' autoload :AgentMapping, 'docusign_transaction_rooms/mappings/agent_mapping' autoload :ProfileMapping, 'docusign_transaction_rooms/mappings/profile_mapping' autoload :AccessMapping, 'docusign_transaction_rooms/mappings/access_mapping' autoload :PermissionsMapping, 'docusign_transaction_rooms/mappings/permissions_mapping' autoload :ManagerMapping, 'docusign_transaction_rooms/mappings/manager_mapping' autoload :ContactInfoMapping, 'docusign_transaction_rooms/mappings/contact_info_mapping' autoload :RoomMapping, 'docusign_transaction_rooms/mappings/room_mapping' autoload :AddressMapping, 'docusign_transaction_rooms/mappings/address_mapping' autoload :DetailsMapping, 'docusign_transaction_rooms/mappings/details_mapping' autoload :TransactionPartyMapping, 'docusign_transaction_rooms/mappings/transaction_party_mapping' autoload :RoomContactMapping, 'docusign_transaction_rooms/mappings/room_contact_mapping' autoload :RoomContactTypeMapping, 'docusign_transaction_rooms/mappings/room_contact_type_mapping' autoload :RoomContactIntegrationMapping, 'docusign_transaction_rooms/mappings/room_contact_integration_mapping' autoload :LoneWolfDetailsMapping, 'docusign_transaction_rooms/mappings/lone_wolf_details_mapping' autoload :AgentCommissionMapping, 'docusign_transaction_rooms/mappings/agent_commission_mapping' autoload :ExternalAgentCommissionMapping, 'docusign_transaction_rooms/mappings/external_agent_commission_mapping' autoload :ClientContactMapping, 'docusign_transaction_rooms/mappings/client_contact_mapping' autoload :BusinessContactMapping, 'docusign_transaction_rooms/mappings/business_contact_mapping' autoload :AuctionDetailsMapping, 'docusign_transaction_rooms/mappings/auction_details_mapping' autoload :ProfitPowerDetailsMapping, 'docusign_transaction_rooms/mappings/profit_power_details_mapping' autoload :RoomActivityMapping, 'docusign_transaction_rooms/mappings/room_activity_mapping' autoload :RoomApprovalMapping, 'docusign_transaction_rooms/mappings/room_approval_mapping' autoload :RoomDocumentMapping, 'docusign_transaction_rooms/mappings/room_document_mapping' autoload :RoomRejectionMapping, 'docusign_transaction_rooms/mappings/room_rejection_mapping' autoload :RoomSubmissionMapping, 'docusign_transaction_rooms/mappings/room_submission_mapping' autoload :RoomTaskListMapping, 'docusign_transaction_rooms/mappings/room_task_list_mapping' autoload :FolderMapping, 'docusign_transaction_rooms/mappings/folder_mapping' autoload :MetaMapping, 'docusign_transaction_rooms/mappings/meta_mapping' autoload :TitleMapping, 'docusign_transaction_rooms/mappings/title_mapping' autoload :TemplateMapping, 'docusign_transaction_rooms/mappings/template_mapping' autoload :InboxMapping, 'docusign_transaction_rooms/mappings/inbox_mapping' autoload :DocumentMapping, 'docusign_transaction_rooms/mappings/document_mapping' autoload :RegionMapping, 'docusign_transaction_rooms/mappings/region_mapping' autoload :TaskListMapping, 'docusign_transaction_rooms/mappings/task_list_mapping' autoload :TaskMapping, 'docusign_transaction_rooms/mappings/task_mapping' # Utils autoload :ErrorHandlingResourcable, 'docusign_transaction_rooms/error_handling_resourcable' autoload :PaginatedResource, 'docusign_transaction_rooms/paginated_resource' # Errors autoload :ErrorMapping, 'droplet_kit/mappings/error_mapping' Error = Class.new(StandardError) end
omundu/docusign_transaction_rooms
lib/docusign_transaction_rooms.rb
Ruby
mit
9,078
require 'spec_helper' describe "README features" do describe "Custom actions" do let(:custom_path) { 'accounts/:account_id/item_lists.json' } around do |example| begin ExampleCom::ItemList.define_action :index, method: :get, path: custom_path example.run ensure ExampleCom::ItemList.define_action :index, method: :get, path: ':route_key.json' end end before do stub_request(:get, expected_item_lists_path) end specify "will change the URL for the request" do ExampleCom::ItemList.all(account_id: '123') expect_request(:get, path: expected_item_lists_path) end specify "are isolated to class" do expect(ExampleCom::Item._defined_actions[:index][:path]).to eq(':route_key.json') end def expected_item_lists_path example_com_build_url('accounts/123/item_lists.json') end end end
neerfri/signaling
spec/integration/readme_features/custom_action_path_spec.rb
Ruby
mit
904
<?xml version="1.0" ?><!DOCTYPE TS><TS language="ky" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;VPSCoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The VPSCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Жаң даректи жасоо</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-46"/> <source>These are your VPSCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a VPSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Verify a message to ensure it was signed with a specified VPSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>Ө&amp;чүрүү</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+65"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+250"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation>Дарек</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(аты жок)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+35"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-58"/> <source>VPSCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+282"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>Synchronizing with network...</source> <translation type="unfinished"/> </message> <message> <location line="-319"/> <source>&amp;Overview</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation>&amp;Транзакциялар</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>&amp;Receive coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="-7"/> <source>&amp;Send coins</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show information about VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+259"/> <source>~%n block(s) remaining</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Downloaded %1 of %2 blocks of transaction history (%3% done).</source> <translation type="unfinished"/> </message> <message> <location line="-256"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Send coins to a VPSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Modify configuration options for VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-14"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation>Билдирүүнү &amp;текшерүү...</translation> </message> <message> <location line="-202"/> <source>VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet</source> <translation>Капчык</translation> </message> <message> <location line="+180"/> <source>&amp;About VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>&amp;File</source> <translation>&amp;Файл</translation> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation>&amp;Жардам</translation> </message> <message> <location line="+12"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Actions toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+9"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+60"/> <source>VPSCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+75"/> <source>%n active connection(s) to VPSCoin network</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+40"/> <source>Downloaded %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+413"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-403"/> <source>%n second(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="-312"/> <source>About VPSCoin card</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about VPSCoin card</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+297"/> <source>%n minute(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s) ago</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Up to date</source> <translation>Жаңыланган</translation> </message> <message> <location line="+7"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Last received block was generated %1.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid VPSCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+76"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+18"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+109"/> <source>A fatal error occurred. VPSCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+90"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+551"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation>Дарек</translation> </message> <message> <location line="+5"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-515"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+155"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+66"/> <source>(no label)</source> <translation>(аты жок)</translation> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Дарек</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+20"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid VPSCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+420"/> <location line="+12"/> <source>VPSCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start VPSCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start VPSCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Detach databases at shutdown</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation>&amp;Тармак</translation> </message> <message> <location line="+6"/> <source>Automatically open the VPSCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Connect to the VPSCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Порт:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Терезе</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting VPSCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show VPSCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Жарайт</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Жокко чыгаруу</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+55"/> <source>default</source> <translation>жарыяланбаган</translation> </message> <message> <location line="+149"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting VPSCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <location line="+231"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the VPSCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-160"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-107"/> <source>Wallet</source> <translation>Капчык</translation> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-108"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+113"/> <location line="+1"/> <source>out of sync</source> <translation>синхрондоштурулган эмес</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+348"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-217"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Ачуу</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the VPSCoin-Qt help message to get a list with possible VPSCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Консоль</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>VPSCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>VPSCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the VPSCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Консолду тазалоо</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-33"/> <source>Welcome to the VPSCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+86"/> <location line="+86"/> <location line="+32"/> <source>0.00 VPS</source> <translation type="unfinished"/> </message> <message> <location line="-191"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>&amp;Бардыгын тазалоо</translation> </message> <message> <location line="+28"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>123.456 VPS</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Жөнөтүү</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-173"/> <source>Enter a VPSCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+86"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+251"/> <source>WARNING: Invalid VPSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation>(аты жок)</translation> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <location filename="../sendcoinsentry.cpp" line="+25"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to send the payment to (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Даректи алмашуу буферинен коюу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a VPSCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation>Даректи алмашуу буферинен коюу</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this VPSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>&amp;Бардыгын тазалоо</translation> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified VPSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a VPSCoin address (e.g. Sjz75uKHzUQJnSdzvpiigEGxseKkDhQToX)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter VPSCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+19"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-2"/> <source>Open for %n block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+8"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation>%1/тармакта эмес</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation>Билдирүү</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-211"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+226"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation>Дарек</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+190"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+55"/> <location line="+16"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Today</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+144"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation>Дата</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation>Дарек</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+206"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+33"/> <source>VPSCoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to -server or VPSCoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify configuration file (default: VPSCoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: VPSCoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Listen for connections on &lt;port&gt; (default: 15714 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Stake your coins to support network and gain reward (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Detach block and address databases. Increases shutdown time (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds </source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 15715 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-11"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>Error: Transaction creation failed </source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>Error: Wallet locked, unable to create transaction </source> <translation type="unfinished"/> </message> <message> <location line="-8"/> <source>Importing blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Importing bootstrap blockchain data file.</source> <translation type="unfinished"/> </message> <message> <location line="-88"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+117"/> <source>Error initializing database environment %s! To recover, BACKUP THAT DIRECTORY, then remove everything from it except for wallet.dat.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+61"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong VPSCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="-31"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-30"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-62"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+94"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-90"/> <source>Find peers using DNS lookup (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync checkpoints policy (default: strict)</source> <translation type="unfinished"/> </message> <message> <location line="+83"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-82"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-29"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-42"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+109"/> <source>Unable to sign checkpoint, wrong checkpointkey? </source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+57"/> <source>WARNING: syncronized checkpoint violation detected, but skipped!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-48"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-54"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-84"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=VPSCoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;VPSCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Find peers using internet relay chat (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enforce transaction scripts to use canonical PUSH operators (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 2500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>WARNING: Invalid checkpoint found! Displayed transactions may not be correct! You may need to upgrade, or notify developers.</source> <translation type="unfinished"/> </message> <message> <location line="-158"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+95"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot obtain a lock on data directory %s. VPSCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-98"/> <source>VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <source>Connect through socks proxy</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Error loading blkindex.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of VPSCoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart VPSCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-24"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Error: could not start node</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="-34"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-103"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="+122"/> <source>Unable to bind to %s on this computer. VPSCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-97"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+55"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot initialize keypool</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="-167"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Error</source> <translation>Ката</translation> </message> <message> <location line="+6"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
vpscoin/VPSCoin
src/qt/locale/bitcoin_ky.ts
TypeScript
mit
107,742
# frozen_string_literal: true class Projects::TriggersController < Projects::ApplicationController before_action :authorize_admin_build! before_action :authorize_manage_trigger!, except: [:index, :create] before_action :authorize_admin_trigger!, only: [:edit, :update] before_action :trigger, only: [:take_ownership, :edit, :update, :destroy] layout 'project_settings' def index redirect_to project_settings_ci_cd_path(@project, anchor: 'js-pipeline-triggers') end def create @trigger = project.triggers.create(trigger_params.merge(owner: current_user)) if @trigger.valid? flash[:notice] = _('Trigger was created successfully.') else flash[:alert] = _('You could not create a new trigger.') end redirect_to project_settings_ci_cd_path(@project, anchor: 'js-pipeline-triggers') end def take_ownership if trigger.update(owner: current_user) flash[:notice] = _('Trigger was re-assigned.') else flash[:alert] = _('You could not take ownership of trigger.') end redirect_to project_settings_ci_cd_path(@project, anchor: 'js-pipeline-triggers') end def edit end def update if trigger.update(trigger_params) redirect_to project_settings_ci_cd_path(@project, anchor: 'js-pipeline-triggers'), notice: _('Trigger was successfully updated.') else render action: "edit" end end def destroy if trigger.destroy flash[:notice] = _("Trigger removed.") else flash[:alert] = _("Could not remove the trigger.") end redirect_to project_settings_ci_cd_path(@project, anchor: 'js-pipeline-triggers'), status: :found end private def authorize_manage_trigger! access_denied! unless can?(current_user, :manage_trigger, trigger) end def authorize_admin_trigger! access_denied! unless can?(current_user, :admin_trigger, trigger) end def trigger @trigger ||= project.triggers.find(params[:id]) .present(current_user: current_user) end def trigger_params params.require(:trigger).permit(:description) end end
iiet/iiet-git
app/controllers/projects/triggers_controller.rb
Ruby
mit
2,087
package org.diorite.material.blocks.stony; import java.util.Map; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.diorite.BlockFace; import org.diorite.cfg.magic.MagicNumbers; import org.diorite.material.BlockMaterialData; import org.diorite.material.blocks.StairsMat; import org.diorite.utils.collections.maps.CaseInsensitiveMap; import gnu.trove.map.TByteObjectMap; import gnu.trove.map.hash.TByteObjectHashMap; /** * Class representing block "RedSandstoneStairs" and all its subtypes. */ public class RedSandstoneStairsMat extends BlockMaterialData implements StairsMat { /** * Sub-ids used by diorite/minecraft by default */ public static final byte USED_DATA_VALUES = 8; /** * Blast resistance of block, can be changed only before server start. * Final copy of blast resistance from {@link MagicNumbers} class. */ public static final float BLAST_RESISTANCE = MagicNumbers.MATERIAL__RED_SANDSTONE_STAIRS__BLAST_RESISTANCE; /** * Hardness of block, can be changed only before server start. * Final copy of hardness from {@link MagicNumbers} class. */ public static final float HARDNESS = MagicNumbers.MATERIAL__RED_SANDSTONE_STAIRS__HARDNESS; public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_EAST = new RedSandstoneStairsMat(); public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_WEST = new RedSandstoneStairsMat(BlockFace.WEST, false); public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_SOUTH = new RedSandstoneStairsMat(BlockFace.SOUTH, false); public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_NORTH = new RedSandstoneStairsMat(BlockFace.NORTH, false); public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_EAST_UPSIDE_DOWN = new RedSandstoneStairsMat(BlockFace.EAST, true); public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_WEST_UPSIDE_DOWN = new RedSandstoneStairsMat(BlockFace.WEST, true); public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_SOUTH_UPSIDE_DOWN = new RedSandstoneStairsMat(BlockFace.SOUTH, true); public static final RedSandstoneStairsMat RED_SANDSTONE_STAIRS_NORTH_UPSIDE_DOWN = new RedSandstoneStairsMat(BlockFace.NORTH, true); private static final Map<String, RedSandstoneStairsMat> byName = new CaseInsensitiveMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR); private static final TByteObjectMap<RedSandstoneStairsMat> byID = new TByteObjectHashMap<>(USED_DATA_VALUES, SMALL_LOAD_FACTOR); protected final BlockFace face; protected final boolean upsideDown; @SuppressWarnings("MagicNumber") protected RedSandstoneStairsMat() { super("RED_SANDSTONE_STAIRS", 180, "minecraft:red_sandstone_stairs", "EAST", (byte) 0x00); this.face = BlockFace.EAST; this.upsideDown = false; } protected RedSandstoneStairsMat(final BlockFace face, final boolean upsideDown) { super(RED_SANDSTONE_STAIRS_EAST.name(), RED_SANDSTONE_STAIRS_EAST.ordinal(), RED_SANDSTONE_STAIRS_EAST.getMinecraftId(), face.name() + (upsideDown ? "_UPSIDE_DOWN" : ""), StairsMat.combine(face, upsideDown)); this.face = face; this.upsideDown = upsideDown; } protected RedSandstoneStairsMat(final String enumName, final int id, final String minecraftId, final int maxStack, final String typeName, final byte type, final BlockFace face, final boolean upsideDown) { super(enumName, id, minecraftId, maxStack, typeName, type); this.face = face; this.upsideDown = upsideDown; } @Override public float getBlastResistance() { return BLAST_RESISTANCE; } @Override public float getHardness() { return HARDNESS; } @Override public boolean isUpsideDown() { return this.upsideDown; } @Override public RedSandstoneStairsMat getUpsideDown(final boolean upsideDown) { return getByID(StairsMat.combine(this.face, upsideDown)); } @Override public RedSandstoneStairsMat getType(final BlockFace face, final boolean upsideDown) { return getByID(StairsMat.combine(face, upsideDown)); } @Override public BlockFace getBlockFacing() { return this.face; } @Override public RedSandstoneStairsMat getBlockFacing(final BlockFace face) { return getByID(StairsMat.combine(face, this.upsideDown)); } @Override public RedSandstoneStairsMat getType(final String name) { return getByEnumName(name); } @Override public RedSandstoneStairsMat getType(final int id) { return getByID(id); } @Override public String toString() { return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("face", this.face).append("upsideDown", this.upsideDown).toString(); } /** * Returns one of RedSandstoneStairs sub-type based on sub-id, may return null * * @param id sub-type id * * @return sub-type of RedSandstoneStairs or null */ public static RedSandstoneStairsMat getByID(final int id) { return byID.get((byte) id); } /** * Returns one of RedSandstoneStairs sub-type based on name (selected by diorite team), may return null * If block contains only one type, sub-name of it will be this same as name of material. * * @param name name of sub-type * * @return sub-type of RedSandstoneStairs or null */ public static RedSandstoneStairsMat getByEnumName(final String name) { return byName.get(name); } /** * Returns one of RedSandstoneStairs sub-type based on facing direction and upside-down state. * It will never return null. * * @param blockFace facing direction of stairs. * @param upsideDown if stairs should be upside-down. * * @return sub-type of RedSandstoneStairs */ public static RedSandstoneStairsMat getRedSandstoneStairs(final BlockFace blockFace, final boolean upsideDown) { return getByID(StairsMat.combine(blockFace, upsideDown)); } /** * Register new sub-type, may replace existing sub-types. * Should be used only if you know what are you doing, it will not create fully usable material. * * @param element sub-type to register */ public static void register(final RedSandstoneStairsMat element) { byID.put((byte) element.getType(), element); byName.put(element.name(), element); } @Override public RedSandstoneStairsMat[] types() { return RedSandstoneStairsMat.redSandstoneStairsTypes(); } /** * @return array that contains all sub-types of this block. */ public static RedSandstoneStairsMat[] redSandstoneStairsTypes() { return byID.values(new RedSandstoneStairsMat[byID.size()]); } static { RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_EAST); RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_WEST); RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_SOUTH); RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_NORTH); RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_EAST_UPSIDE_DOWN); RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_WEST_UPSIDE_DOWN); RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_SOUTH_UPSIDE_DOWN); RedSandstoneStairsMat.register(RED_SANDSTONE_STAIRS_NORTH_UPSIDE_DOWN); } }
joda17/Diorite-API
src/main/java/org/diorite/material/blocks/stony/RedSandstoneStairsMat.java
Java
mit
7,654
<?php require(__DIR__ . '/vendor/autoload.php'); Httpful\Bootstrap::init(); RESTful\Bootstrap::init(); Balanced\Bootstrap::init(); Balanced\Settings::$api_key = "ak-test-25ZY8HQwZPuQtDecrxb671LilUya5t5G0"; $order = Balanced\Order::get("/orders/OR5sl2RJVnbwEf45nq5eATdz"); $order->description = 'New description for order'; $order->meta = array( "anykey" => "valuegoeshere", "product.id" => "1234567890", ); $order->save(); ?>
joelgarciajr84/balanced-php
scenarios/order_update/executable.php
PHP
mit
438
package cn.ezandroid.ezfilter.render; import android.content.Context; import android.opengl.GLES20; import cn.ezandroid.lib.ezfilter.core.util.Path; import cn.ezandroid.lib.ezfilter.extra.IAdjustable; import cn.ezandroid.lib.ezfilter.extra.MultiBitmapInputRender; /** * 黑白滤镜 * * @author like * @date 2017-09-17 */ public class BWRender extends MultiBitmapInputRender implements IAdjustable { private static final String[] BITMAP_PATHS = new String[]{ Path.ASSETS.wrap("filter/bw.png"), // Path.DRAWABLE.wrap("" + R.drawable.bw) }; private static final String UNIFORM_MIX = "u_mix"; private int mMixHandle; private float mMix = 1f; // 滤镜强度 public BWRender(Context context) { super(context, BITMAP_PATHS); setFragmentShader("precision lowp float;\n" + " uniform lowp float u_mix;\n" + " \n" + " varying highp vec2 textureCoordinate;\n" + " \n" + " uniform sampler2D inputImageTexture;\n" + " uniform sampler2D inputImageTexture2;\n" + " \n" + " \n" + " void main()\n" + "{\n" + " lowp vec4 sourceImageColor = texture2D(inputImageTexture, textureCoordinate)" + ";\n" + " \n" + " vec3 texel = texture2D(inputImageTexture, textureCoordinate).rgb;\n" + " texel = vec3(dot(vec3(0.3, 0.6, 0.1), texel));\n" + " texel = vec3(texture2D(inputImageTexture2, vec2(texel.r, .16666)).r);\n" + " mediump vec4 fragColor = vec4(texel, 1.0);\n" + " gl_FragColor = mix(sourceImageColor, fragColor, u_mix);\n" + "}"); } @Override protected void initShaderHandles() { super.initShaderHandles(); mMixHandle = GLES20.glGetUniformLocation(mProgramHandle, UNIFORM_MIX); } @Override protected void bindShaderValues() { super.bindShaderValues(); GLES20.glUniform1f(mMixHandle, mMix); } @Override public void adjust(float progress) { mMix = progress; } }
uestccokey/EZFilter
app/src/main/java/cn/ezandroid/ezfilter/render/BWRender.java
Java
mit
2,224
@extends ('site.layouts.home.master') @section ('conteudo') <div class="w3-row"> <div class="w3-padding-64 w3-container login"> <div class="w3-content"> <div class="w3-container"> <h2>Resetar Senha</h2> <hr> <form role="form" method="POST" action="{{ route('empresa.reseta-senha.request') }}"> {{ csrf_field() }} <input type="hidden" name="token" value="{{ $token }}"> <div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}"> <label for="email">E-Mail</label> <input id="email" type="email" class="w3-input" name="email" value="{{ $email or old('email') }}" required autofocus> @if ($errors->has('email')) <span class="help-block"> <strong>{{ $errors->first('email') }}</strong> </span> @endif </div> <div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}"> <label for="password">Senha</label> <input id="password" type="password" class="w3-input" name="password" required> @if ($errors->has('password')) <span class="help-block"> <strong>{{ $errors->first('password') }}</strong> </span> @endif </div> <div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}"> <label for="password-confirm">Confirmação de senha</label> <input id="password-confirm" type="password" class="w3-input" name="password_confirmation" required> @if ($errors->has('password_confirmation')) <span class="help-block"> <strong>{{ $errors->first('password_confirmation') }}</strong> </span> @endif </div> <div class="form-group"> <button type="submit" class="btn btn-primary"> Resetar senha </button> </div> </form> </div> </div> </div> </div> @endsection <script src='https://www.google.com/recaptcha/api.js'></script> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script> <script> $(document).ready(function(){ $( "#home, .ajuste" ).removeClass( "w3-white" ); $( ".ajuste" ).addClass( "w3-white" ); }); </script>
jthanlopes/SysGAP
resources/views/site/reset-empresa.blade.php
PHP
mit
2,346
<TS language="sq" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Right-click to edit address or label</source> <translation>Kliko me të djathtën për të ndryshuar adresën ose etiketen.</translation> </message> <message> <source>Create a new address</source> <translation>Krijo një adresë të re</translation> </message> <message> <source>&amp;New</source> <translation>&amp;E re</translation> </message> <message> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopjo adresën e zgjedhur në memorjen e sistemit </translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Kopjo</translation> </message> <message> <source>Delete the currently selected address from the list</source> <translation>Fshi adresen e selektuar nga lista</translation> </message> <message> <source>Export the data in the current tab to a file</source> <translation>Eksporto të dhënat e skedës korrente në një skedar</translation> </message> <message> <source>&amp;Delete</source> <translation>&amp;Fshi</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <source>Enter passphrase</source> <translation>Futni frazkalimin</translation> </message> <message> <source>New passphrase</source> <translation>Frazkalim i ri</translation> </message> <message> <source>Repeat new passphrase</source> <translation>Përsërisni frazkalimin e ri</translation> </message> </context> <context> <name>BanTableModel</name> </context> <context> <name>InfinitumGUI</name> <message> <source>Synchronizing with network...</source> <translation>Duke u sinkronizuar me rrjetin...</translation> </message> <message> <source>&amp;Overview</source> <translation>&amp;Përmbledhje</translation> </message> <message> <source>Show general overview of wallet</source> <translation>Trego një përmbledhje te përgjithshme të portofolit</translation> </message> <message> <source>&amp;Transactions</source> <translation>&amp;Transaksionet</translation> </message> <message> <source>Browse transaction history</source> <translation>Shfleto historinë e transaksioneve</translation> </message> <message> <source>Quit application</source> <translation>Mbyllni aplikacionin</translation> </message> <message> <source>&amp;Options...</source> <translation>&amp;Opsione</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>Duke marr adresen</translation> </message> <message> <source>Change the passphrase used for wallet encryption</source> <translation>Ndrysho frazkalimin e përdorur per enkriptimin e portofolit</translation> </message> <message> <source>Infinitum</source> <translation>Infinitum</translation> </message> <message> <source>Wallet</source> <translation>Portofol</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Dergo</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Merr</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Shfaq / Fsheh</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Skedar</translation> </message> <message> <source>&amp;Settings</source> <translation>&amp;Konfigurimet</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Ndihmë</translation> </message> <message> <source>Tabs toolbar</source> <translation>Shiriti i mjeteve</translation> </message> <message> <source>%1 and %2</source> <translation>%1 dhe %2</translation> </message> <message> <source>%1 behind</source> <translation>%1 Pas</translation> </message> <message> <source>Error</source> <translation>Problem</translation> </message> <message> <source>Information</source> <translation>Informacion</translation> </message> <message> <source>Up to date</source> <translation>I azhornuar</translation> </message> <message> <source>Catching up...</source> <translation>Duke u azhornuar...</translation> </message> <message> <source>Sent transaction</source> <translation>Dërgo transaksionin</translation> </message> <message> <source>Incoming transaction</source> <translation>Transaksion në ardhje</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Portofoli po &lt;b&gt; enkriptohet&lt;/b&gt; dhe është &lt;b&gt; i ç'kyçur&lt;/b&gt;</translation> </message> <message> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Portofoli po &lt;b&gt; enkriptohet&lt;/b&gt; dhe është &lt;b&gt; i kyçur&lt;/b&gt;</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Coin Selection</source> <translation>Zgjedhja e monedhes</translation> </message> <message> <source>Amount:</source> <translation>Shuma:</translation> </message> <message> <source>Amount</source> <translation>Sasia</translation> </message> <message> <source>Date</source> <translation>Data</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <source>Edit Address</source> <translation>Ndrysho Adresën</translation> </message> <message> <source>&amp;Label</source> <translation>&amp;Etiketë</translation> </message> <message> <source>&amp;Address</source> <translation>&amp;Adresa</translation> </message> </context> <context> <name>FreespaceChecker</name> <message> <source>name</source> <translation>emri</translation> </message> </context> <context> <name>HelpMessageDialog</name> <message> <source>version</source> <translation>versioni</translation> </message> </context> <context> <name>Intro</name> <message> <source>Welcome</source> <translation>Miresevini</translation> </message> <message> <source>Error</source> <translation>Problem</translation> </message> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> <message> <source>Options</source> <translation>Opsionet</translation> </message> <message> <source>W&amp;allet</source> <translation>Portofol</translation> </message> </context> <context> <name>OverviewPage</name> <message> <source>Form</source> <translation>Formilarë</translation> </message> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Sasia</translation> </message> </context> <context> <name>RPCConsole</name> <message> <source>&amp;Information</source> <translation>Informacion</translation> </message> <message> <source>&amp;Open</source> <translation>&amp;Hap</translation> </message> <message> <source>&amp;Clear</source> <translation>&amp;Pastro</translation> </message> <message> <source>never</source> <translation>asnjehere</translation> </message> <message> <source>Unknown</source> <translation>i/e panjohur</translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> <message> <source>&amp;Amount:</source> <translation>Shuma:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiketë:</translation> </message> <message> <source>Clear</source> <translation>Pastro</translation> </message> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>Copy &amp;Address</source> <translation>&amp;Kopjo adresen</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>Send Coins</source> <translation>Dërgo Monedha</translation> </message> <message> <source>Insufficient funds!</source> <translation>Fonde te pamjaftueshme</translation> </message> <message> <source>Amount:</source> <translation>Shuma:</translation> </message> <message> <source>Send to multiple recipients at once</source> <translation>Dërgo marrësve të ndryshëm njëkohësisht</translation> </message> <message> <source>Balance:</source> <translation>Balanca:</translation> </message> <message> <source>Confirm the send action</source> <translation>Konfirmo veprimin e dërgimit</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <source>A&amp;mount:</source> <translation>Sh&amp;uma:</translation> </message> <message> <source>Pay &amp;To:</source> <translation>Paguaj &amp;drejt:</translation> </message> <message> <source>&amp;Label:</source> <translation>&amp;Etiketë:</translation> </message> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Ngjit nga memorja e sistemit</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <source>Pay To:</source> <translation>Paguaj drejt:</translation> </message> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> <message> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <source>Paste address from clipboard</source> <translation>Ngjit nga memorja e sistemit</translation> </message> <message> <source>Alt+P</source> <translation>Alt+P</translation> </message> </context> <context> <name>SplashScreen</name> <message> <source>[testnet]</source> <translation>[testo rrjetin]</translation> </message> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDescDialog</name> <message> <source>This pane shows a detailed description of the transaction</source> <translation>Ky panel tregon një përshkrim të detajuar të transaksionit</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>infinitum-core</name> <message> <source>Options:</source> <translation>Opsionet:</translation> </message> <message> <source>Infinitum Core</source> <translation>Berthama Infinitum</translation> </message> <message> <source>Information</source> <translation>Informacion</translation> </message> <message> <source>Insufficient funds</source> <translation>Fonde te pamjaftueshme</translation> </message> <message> <source>Rescanning...</source> <translation>Rikerkim</translation> </message> <message> <source>Error</source> <translation>Problem</translation> </message> </context> </TS>
fcecin/infinitum
src/qt/locale/infinitum_sq.ts
TypeScript
mit
12,467
/* eslint-env jest */ import fs from 'fs-extra' import { join } from 'path' import { killApp, findPort, launchApp, nextStart, nextBuild, fetchViaHTTP, } from 'next-test-utils' import webdriver from 'next-webdriver' import cheerio from 'cheerio' jest.setTimeout(1000 * 60 * 2) const appDir = join(__dirname, '../') const gip404Err = /`pages\/404` can not have getInitialProps\/getServerSideProps/ let appPort let app describe('404 Page Support with _app', () => { describe('production mode', () => { afterAll(() => killApp(app)) it('should build successfully', async () => { const { code, stderr, stdout } = await nextBuild(appDir, [], { stderr: true, stdout: true, }) expect(code).toBe(0) expect(stderr).not.toMatch(gip404Err) expect(stdout).not.toMatch(gip404Err) appPort = await findPort() app = await nextStart(appDir, appPort) }) it('should not output static 404 if _app has getInitialProps', async () => { const browser = await webdriver(appPort, '/404') const isAutoExported = await browser.eval('__NEXT_DATA__.autoExport') expect(isAutoExported).toBe(null) }) it('specify to use the 404 page still in the routes-manifest', async () => { const manifest = await fs.readJSON( join(appDir, '.next/routes-manifest.json') ) expect(manifest.pages404).toBe(true) }) it('should still use 404 page', async () => { const res = await fetchViaHTTP(appPort, '/abc') expect(res.status).toBe(404) const $ = cheerio.load(await res.text()) expect($('#404-title').text()).toBe('Hi There') }) }) describe('dev mode', () => { let stderr = '' let stdout = '' beforeAll(async () => { appPort = await findPort() app = await launchApp(appDir, appPort, { onStderr(msg) { stderr += msg }, onStdout(msg) { stdout += msg }, }) }) afterAll(() => killApp(app)) it('should not show pages/404 GIP error if _app has GIP', async () => { const res = await fetchViaHTTP(appPort, '/abc') expect(res.status).toBe(404) const $ = cheerio.load(await res.text()) expect($('#404-title').text()).toBe('Hi There') expect(stderr).not.toMatch(gip404Err) expect(stdout).not.toMatch(gip404Err) }) }) })
flybayer/next.js
test/integration/404-page-app/test/index.test.js
JavaScript
mit
2,390
/** * Calculates the complex number raised to some power * * @param {numeric} c The power to which the complex number should be raised * @return {Complex} */ pow(c) : Complex { var re, im, abs, arg; if (MathLib.type(c) === 'complex') { re = c.re; im = c.im; abs = this.abs(); arg = this.arg(); // Fixes inf^(2+5i) = inf and 0^(2+5i) = 0 if ((this.isZero() || this.re === Infinity) && !(c.isZero() || c.re === Infinity || MathLib.isNaN(c.re))) { return new MathLib.Complex(this.re, this.im); } return MathLib.Complex.polar( MathLib.times( MathLib.pow(abs, re), MathLib.exp( MathLib.negative( MathLib.times(im, arg) ) ) ), MathLib.plus(MathLib.times(re, arg), MathLib.times(im, MathLib.ln(abs))) ); } else { // The naive pow method has some rounding errrors. For example // (2+5i)^3 = -142.00000000000006-64.99999999999999i // instead of -142-65i which are errors of magnitude around 1e-14. // This error increases quickly for increasing exponents. // (2+5i)^21 has an error of 5.8 in the real part // return MathLib.Complex.polar(MathLib.pow(abs, c), MathLib.times(arg, c)); // The following algorithm uses a different approach for integer exponents, // where it yields exact results. // Non integer exponents are evaluated using the naive approach. // TODO: Improve the algorithm. var i, int = MathLib.floor(Math.abs(c)), res = new MathLib.Complex(1), power = this, bin = int.toString(2); // If the exponent is not an integer we use the naive approach if (c % 1) { abs = this.abs(); arg = this.arg(); return MathLib.Complex.polar(MathLib.pow(abs, c), MathLib.times(arg, c)); } // The imaginary part of (2+5i)^-0 should be -0 not +0. if (MathLib.isZero(c)) { return new MathLib.Complex(1, c); } for (i = bin.length - 1; i >= 0; i--) { if (bin[i] === '1') { res = MathLib.times(res, power); } power = MathLib.times(power, power); } if (c < 0) { res = res.inverse(); } return res; } }
alawatthe/MathLib
src/Complex/prototype/pow.ts
TypeScript
mit
2,048
'use strict'; const sinon = require('sinon'), q = require('q'), mockery = require('mockery'), _ = require('lodash'), should = require('chai').should(); describe('Create episode', () => { const idsGeneratorStub = () => '123'; it('Should call the next callback', done => { let deferred = q.defer(); let promise = deferred.promise; let persistEpisodeInStorage = sinon.stub(); persistEpisodeInStorage.returns(promise); const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage); createEpisode(mockRequest('book-id-123'), mockResponse(), done); deferred.resolve(); }); it('Should return 201 created', done => { const responseMock = mockResponse(); const responseSpy = sinon.spy(responseMock, 'json'); let deferred = q.defer(); let promise = deferred.promise; let persistEpisodeInStorage = sinon.stub(); persistEpisodeInStorage.returns(promise); const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage); createEpisode(mockRequest('book-id-123'), responseMock, checkResponse); function checkResponse() { responseSpy.args[0][0].should.equal(201); done(); } deferred.resolve(); }); it('Should return an id property with the scenario id', done => { const responseMock = mockResponse(); const responseSpy = sinon.spy(responseMock, 'json'); let deferred = q.defer(); let promise = deferred.promise; let persistEpisodeInStorage = sinon.stub(); persistEpisodeInStorage.returns(promise); const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage); createEpisode(mockRequest('book-id-123'), responseMock, checkResponse); function checkResponse() { const body = responseSpy.args[0][1]; body.should.deep.equal({id: idsGeneratorStub()}); done(); } deferred.resolve(); }); it('Should store the scenario data and id', done => { let deferred = q.defer(); let promise = deferred.promise; let persistEpisodeInStorage = sinon.stub(); persistEpisodeInStorage.returns(promise); const bookId = 'abc1234'; const mockedRequest = mockRequest(bookId); const createEpisode = getCreateEpisodeMiddleware(idsGeneratorStub, persistEpisodeInStorage); createEpisode(mockedRequest, mockResponse(), checkResponse); deferred.resolve(); function checkResponse() { persistEpisodeInStorage.calledOnce.should.equal(true); persistEpisodeInStorage.args[0][0].should.equal(bookId); persistEpisodeInStorage.args[0][1].should.deep.equal(_.assign({id: idsGeneratorStub()}, mockedRequest.body)); done(); } }); afterEach(() => { mockery.deregisterAll(); mockery.disable(); }); }); function getCreateEpisodeMiddleware(idsMock, persistEpisodeInStorage) { mockery.registerMock('../idsGenerator/generateId.js', idsMock); mockery.registerMock('./persistEpisodeInStorage.js', persistEpisodeInStorage); mockery.enable({ useCleanCache: true, warnOnReplace: false, warnOnUnregistered: false }); return require('../../src/episodes/createEpisode.js'); } function mockResponse() { return { json: () => {} }; } function mockRequest(bookId) { return { context: { bookId: bookId }, body: { a: 1, b: 2 } }; }
thegameofcode/cucumberly
test/episodes/createEpisodeTest.js
JavaScript
mit
3,231
RSpec.describe Magick::Image, '#find_similar_region' do it 'works' do image = described_class.new(20, 20) girl = described_class.read(IMAGES_DIR + '/Flower_Hat.jpg').first region = girl.crop(10, 10, 50, 50) x, y = girl.find_similar_region(region) expect(x).not_to be(nil) expect(y).not_to be(nil) expect(x).to eq(10) expect(y).to eq(10) x, y = girl.find_similar_region(region, 0) expect(x).to eq(10) expect(y).to eq(10) x, y = girl.find_similar_region(region, 0, 0) expect(x).to eq(10) expect(y).to eq(10) image_list = Magick::ImageList.new image_list << region x, y = girl.find_similar_region(image_list, 0, 0) expect(x).to eq(10) expect(y).to eq(10) x = girl.find_similar_region(image) expect(x).to be(nil) expect { girl.find_similar_region(region, 10, 10, 10) }.to raise_error(ArgumentError) expect { girl.find_similar_region(region, 10, 'x') }.to raise_error(TypeError) expect { girl.find_similar_region(region, 'x') }.to raise_error(TypeError) region.destroy! expect { girl.find_similar_region(region) }.to raise_error(Magick::DestroyedImageError) end it 'accepts an ImageList argument' do image = described_class.new(20, 20) image_list = Magick::ImageList.new image_list.new_image(10, 10) expect { image.find_similar_region(image_list) }.not_to raise_error expect { image.find_similar_region(image_list, 0) }.not_to raise_error expect { image.find_similar_region(image_list, 0, 0) }.not_to raise_error end end
rmagick/rmagick
spec/rmagick/image/find_similar_region_spec.rb
Ruby
mit
1,562
// Description: C# Extension Methods | Enhance the .NET Framework and .NET Core with over 1000 extension methods. // Website & Documentation: https://csharp-extension.com/ // Issues: https://github.com/zzzprojects/Z.ExtensionMethods/issues // License (MIT): https://github.com/zzzprojects/Z.ExtensionMethods/blob/master/LICENSE // More projects: https://zzzprojects.com/ // Copyright © ZZZ Projects Inc. All rights reserved. using System; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Z.Reflection.Test { [TestClass] public class Field_GetSignature_InternalField { [TestMethod] public void GetSignature() { // Type var @this = typeof(FieldModel<int>).GetField("InternalField", BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); // Exemples string result = @this.GetSignature(); // Unit Test Assert.AreEqual("InternalField", result); } } }
zzzprojects/Z.ExtensionMethods
test/Z.Reflection.Test/GetSignature/Field/InternalField.cs
C#
mit
1,044
<?php namespace Igorw\Trashbin; use Silex\Application; use Silex\ServiceProviderInterface; use Symfony\Component\Finder\Finder; class Provider implements ServiceProviderInterface { public function register(Application $app) { $app['app.languages'] = $app->share(function () { $languages = array(); $finder = new Finder(); foreach ($finder->name('*.min.js')->in(__DIR__.'/../../../web/shjs/lang') as $file) { if (preg_match('#sh_(.+).min.js#', basename($file), $matches)) { $languages[] = $matches[1]; } } return $languages; }); $app['app.storage'] = $app->share(function ($app) { return new RedisStorage($app['predis']); }); $app['app.validator'] = $app->share(function () { return new Validator(); }); $app['app.parser'] = $app->share(function ($app) { return new Parser($app['app.languages']); }); } public function boot(Application $app) { } }
igorw/trashbin
src/Igorw/Trashbin/Provider.php
PHP
mit
1,091
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M4 17h6v2H4zm13-6H4v2h13.25c1.1 0 2 .9 2 2s-.9 2-2 2H15v-2l-3 3 3 3v-2h2c2.21 0 4-1.79 4-4s-1.79-4-4-4zM4 5h16v2H4z" /> , 'WrapTextTwoTone');
kybarg/material-ui
packages/material-ui-icons/src/WrapTextTwoTone.js
JavaScript
mit
262
# -*- coding:utf-8 -*- import abc import platform from UserList import UserList class Monitor(object): @abc.abstractmethod def current(self): pass @abc.abstractmethod def percent(self, range): pass @abc.abstractmethod def reset(self): pass @abc.abstractmethod def max(self): pass @abc.abstractmethod def min(self): pass class Monitors(UserList): @abc.abstractmethod def percent(self, range): pass @abc.abstractmethod def reset(self): pass @abc.abstractmethod def max(self): pass @abc.abstractmethod def min(self): pass def get_monitors(): if platform.system() == "Windows": from .driver_win_wmi import WinWMIMonitors return WinWMIMonitors() elif platform.system() == "Darwin": from .driver_mac import MacMonitors return MacMonitors() elif platform.system() == "Linux": from .driver_linux import LinuxMonitors return LinuxMonitors() else: raise OSError()
x007007007/pyScreenBrightness
src/pyScreenBrightness/base.py
Python
mit
1,127
/* * The MIT License * * Copyright 2014 Sebastian Russ <citeaux at https://github.com/citeaux/JAHAP>. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jahap.business.base; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.apache.log4j.Logger; import org.jahap.business.acc.revaccountsbean; import org.jahap.entities.JahapDatabaseConnector; import org.jahap.entities.acc.AccountPosition; import org.jahap.entities.acc.Csc; import org.jahap.entities.acc.Revaccounts; import org.jahap.entities.base.Rates; import org.jahap.entities.base.Vattype; /** * * @author russ */ public class ratesbean extends DatabaseOperations implements rates_i{ static Logger log = Logger.getLogger(ratesbean.class.getName()); JahapDatabaseConnector dbhook; private static List<Rates> allrecordlist; private revaccountsbean revAccBean; public ratesbean(){ long testg; dbhook = JahapDatabaseConnector.getConnector(); revAccBean= new revaccountsbean(); try { query_AllDbRecords = dbhook.getEntity().createQuery("select t from Rates t ORDER BY t.id"); List<Rates>allroomslist= query_AllDbRecords.getResultList(); numberOfLastRecord= allroomslist.size()-1; } catch (Exception e) { numberOfLastRecord=-1; } query_AllDbRecords = dbhook.getEntity().createQuery("select t from Rates t ORDER BY t.id"); allrecordlist= query_AllDbRecords.getResultList(); try { testg=allrecordlist.get(currentRecordNumber).getId(); tabelIsEmpty=false; tabelIsInit=true; } catch (Exception e) { tabelIsEmpty=true; } log.trace("DB connected"); // If the table is yet empty, init List } public List<Rates>getCurrentRate(){ List<Rates>hh=new ArrayList<Rates>(); hh.add(allrecordlist.get(currentRecordNumber)); return hh; } public void createNewEmptyRecord() { log.debug("Function entry createNewEmptyRecord"); if(numberOfLastRecord==-1){ allrecordlist = new ArrayList(); numberOfLastRecord++; } if(numberOfLastRecord>-1){ numberOfLastRecord++; } Rates emptyroom = new Rates(); allrecordlist.add(emptyroom); currentRecordNumber=numberOfLastRecord; setNewEmptyRecordCreadted(); tabelIsInit=true; // Set Tabel iniated - List is connected } public void nextRecordBackward() { if (currentRecordNumber>0) { currentRecordNumber--; } } public void nextRecordForeward() { if (currentRecordNumber<numberOfLastRecord) { currentRecordNumber++; } } public void saveRecord() { log.debug("Function entry save Record"); if (newEmptyRecordCreated==false){ saveOldRecord(); } if (newEmptyRecordCreated==true){ saveNewRecord(); setNewEmptyRecordSaved(); } } private void saveOldRecord(){ log.debug("Function entry saveOldRecord"); if(newEmptyRecordCreated==false){ dbhook.getEntity().getTransaction().begin(); dbhook.getEntity().find(Rates.class,allrecordlist.get(currentRecordNumber).getId() ); dbhook.getEntity().merge(allrecordlist.get(currentRecordNumber)); dbhook.getEntity().getTransaction().commit(); } } private void saveNewRecord(){ log.debug("Function entry saveNewRecord"); if ( newEmptyRecordCreated==true){ try{ dbhook.getEntity().getTransaction().begin(); dbhook.getEntity().persist(allrecordlist.get(currentRecordNumber)); dbhook.getEntity().getTransaction().commit(); newEmptyRecordCreated=false; } catch (Exception e){ e.printStackTrace(); } } } public void setDataRecordId(Long id){ int inl=-1; try { do { inl++; } while (allrecordlist.get(inl).getId() != id && allrecordlist.size() - 1 > inl); currentRecordNumber=inl; } catch (Exception e) { e.printStackTrace(); } } public List<Rates>SearchForRate(String searchstring){ return allrecordlist; } /* Depricated - not used public Rates SearchForRatewithId(long id){ for(Rates kj:allrecordlist){ if(kj.getId()==id){ return kj; } } return null; } */ public Rates getDataRecord(Long id){ int inl=-1; try { do { inl++; } while (allrecordlist.get(inl).getId() != id && allrecordlist.size() - 1 > inl); currentRecordNumber = inl; System.out.println(currentRecordNumber); } catch (Exception e) { e.printStackTrace(); } return allrecordlist.get(currentRecordNumber); } public void quitDBaccess() { dbhook.getEntity().close(); } // ---------------------- Getters & Setters ------------------ public Collection<AccountPosition> getAccountPositionCollection() { if( tabelIsEmpty!=true){ return allrecordlist.get(currentRecordNumber).getAccountPositionCollection(); } return null; } public String getCode() { if( tabelIsEmpty!=true) return allrecordlist.get(currentRecordNumber).getCode(); return ""; } public Long getId() { if( tabelIsEmpty!=true) return allrecordlist.get(currentRecordNumber).getId(); return null; } public String getName() { if( tabelIsEmpty!=true) return allrecordlist.get(currentRecordNumber).getName(); return null; } public double getPrice() { if( tabelIsEmpty!=true) return allrecordlist.get(currentRecordNumber).getPrice(); return 0; } public void setAccountPositionCollection(Collection<AccountPosition> accountPositionCollection) { if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord(); } public void setCode(String code) { if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord(); allrecordlist.get(currentRecordNumber).setCode(code); } public void setName(String name) { if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord(); allrecordlist.get(currentRecordNumber).setName(name); } public void setPrice(double price) { if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord(); allrecordlist.get(currentRecordNumber).setPrice(price); } public void setId(Long id) { throw new UnsupportedOperationException("Not supported yet."); } // public long getRevaccount() { // if( tabelIsEmpty!=true) // return allrecordlist.get(currentRecordNumber).getRevaccount().getId(); // return 0; // } public Collection<Csc> getCscCollection() { if( tabelIsEmpty!=true){ return allrecordlist.get(currentRecordNumber).getCscCollection(); } return null; } public boolean getOvernight() { if( tabelIsEmpty!=true){ return allrecordlist.get(currentRecordNumber).getOvernight(); } return false; } public void setCscCollection(Collection<Csc> cscCollection) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } public void setOvernight(boolean overnight) { if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord(); allrecordlist.get(currentRecordNumber).setOvernight(overnight); } public void setRevaccount(long revaccount) { if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord(); allrecordlist.get(currentRecordNumber).setRevaccount(revAccBean.SearchForRevAccount(revaccount)); } @Override public Vattype getVattype() { if( tabelIsEmpty!=true){ return allrecordlist.get(currentRecordNumber).getVattype(); } return null; } public void setVattype(long vattype) { if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord(); vattypesbean vatb= new vattypesbean(); allrecordlist.get(currentRecordNumber).setVattype(vatb.getDataRecord(vattype)); } @Override public void setVattype(Vattype vattype) { if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord(); allrecordlist.get(currentRecordNumber).setVattype(vattype); } @Override public Revaccounts getRevaccount() { if( tabelIsEmpty!=true) return allrecordlist.get(currentRecordNumber).getRevaccount(); return null; } @Override public void setRevaccount(Revaccounts revaccount) { if (tabelIsInit==false|| tabelIsEmpty==true) createNewEmptyRecord(); allrecordlist.get(currentRecordNumber).setRevaccount(revaccount); } }
citeaux/JAHAP
src/main/java/org/jahap/business/base/ratesbean.java
Java
mit
11,151
require_relative 'location_splitter' require_relative 'elevation_checker' require_relative 'terrain_checker' class DetailsChecker attr_reader :locations, :services_response def initialize(locations) @locations = locations end def call! split_locations! unless locations.is_a?(Array) check_elevation! check_terrain! services_response end private def split_locations! @locations = LocationSplitter.new(locations).call! end def check_elevation! elevation_checker = ElevationChecker.new(locations) @services_response ||= elevation_checker.call!.body end def check_terrain! services_response.each do |location| lat = location['location']['latitude'] long = location['location']['longitude'] location['statistics']['terrain'] = TerrainChecker.new(latitude: lat, longitude: long).call! end end end
tolhaje/coords2details
details_checker.rb
Ruby
mit
880
# -*- coding: utf-8 -*- """ Forms for day forms """ from django.conf import settings from django import forms from django.utils.translation import ugettext as _ from arrow import Arrow from datebook.models import DayEntry from datebook.forms import CrispyFormMixin from datebook.utils.imports import safe_import_module DATETIME_FORMATS = { 'input_date_formats': ['%d/%m/%Y'], 'input_time_formats': ['%H:%M'], 'widget': forms.SplitDateTimeWidget(date_format='%d/%m/%Y', time_format='%H:%M'), } class DayBaseFormMixin(object): """ DayBase form mixin """ crispy_form_helper_path = 'datebook.forms.crispies.day_helper' crispy_form_helper_kwargs = {} def fill_initial_data(self, *args, **kwargs): # Pass initial data for start and stop to their SplitDateTimeField clones if 'start' in kwargs['initial']: kwargs['initial']['start_datetime'] = kwargs['initial']['start'] if 'stop' in kwargs['initial']: kwargs['initial']['stop_datetime'] = kwargs['initial']['stop'] # For existing instance (in edit mode) pass the start and stop values to their # clone with SplitDateTimeField via initial datas if kwargs.get('instance'): kwargs['initial']['start_datetime'] = kwargs['instance'].start kwargs['initial']['stop_datetime'] = kwargs['instance'].stop return kwargs def init_fields(self, *args, **kwargs): self.fields['start_datetime'] = forms.SplitDateTimeField(label=_('start'), **DATETIME_FORMATS) self.fields['stop_datetime'] = forms.SplitDateTimeField(label=_('stop'), **DATETIME_FORMATS) # Set the form field for DayEntry.content field_helper = safe_import_module(settings.DATEBOOK_TEXT_FIELD_HELPER_PATH) if field_helper is not None: self.fields['content'] = field_helper(self, **{'label':_('content'), 'required': False}) def clean_content(self): """ Text content validation """ content = self.cleaned_data.get("content") validation_helper = safe_import_module(settings.DATEBOOK_TEXT_VALIDATOR_HELPER_PATH) if validation_helper is not None: return validation_helper(self, content) else: return content def clean_start_datetime(self): start = self.cleaned_data['start_datetime'] # Day entry can't start before the targeted day date if start and start.date() < self.daydate: raise forms.ValidationError(_("You can't start a day before itself")) # Day entry can't start after the targeted day date if start and start.date() > self.daydate: raise forms.ValidationError(_("You can't start a day after itself")) return start def clean_stop_datetime(self): start = self.cleaned_data.get('start_datetime') stop = self.cleaned_data['stop_datetime'] # Day entry can't stop before the start if start and stop and stop <= start: raise forms.ValidationError(_("Stop time can't be less or equal to start time")) # Day entry can't stop in more than one futur day from the targeted day date if stop and stop.date() > Arrow.fromdate(self.daydate).replace(days=1).date(): raise forms.ValidationError(_("Stop time can't be more than the next day")) return stop # TODO: overtime must not be more than effective worked time #def clean_overtime(self): #overtime = self.cleaned_data.get('overtime') #return overtime # TODO #def clean_pause(self): #start = self.cleaned_data.get('start_datetime') #stop = self.cleaned_data.get('stop_datetime') #pause = self.cleaned_data['pause'] ## Pause time can't be more than elapsed time between start and stop #if start and stop and pause and False: #raise forms.ValidationError("Pause time is more than the elapsed time") #return pause class DayEntryForm(DayBaseFormMixin, CrispyFormMixin, forms.ModelForm): """ DayEntry form """ def __init__(self, datebook, day, *args, **kwargs): self.datebook = datebook self.daydate = datebook.period.replace(day=day) # Args to give to the form layout method self.crispy_form_helper_kwargs.update({ 'next_day': kwargs.pop('next_day', None), 'day_to_model_url': kwargs.pop('day_to_model_url', None), 'form_action': kwargs.pop('form_action'), 'remove_url': kwargs.pop('remove_url', None), }) # Fill initial datas kwargs = self.fill_initial_data(*args, **kwargs) super(DayEntryForm, self).__init__(*args, **kwargs) super(forms.ModelForm, self).__init__(*args, **kwargs) # Init some special fields kwargs = self.init_fields(*args, **kwargs) def clean(self): cleaned_data = super(DayBaseFormMixin, self).clean() content = cleaned_data.get("content") vacation = cleaned_data.get("vacation") # Content text is only required when vacation is not checked if not vacation and not content: raise forms.ValidationError(_("Worked days require a content text")) return cleaned_data def save(self, *args, **kwargs): instance = super(DayEntryForm, self).save(commit=False, *args, **kwargs) instance.start = self.cleaned_data['start_datetime'] instance.stop = self.cleaned_data['stop_datetime'] instance.datebook = self.datebook instance.activity_date = self.daydate instance.save() return instance class Meta: model = DayEntry exclude = ('datebook', 'activity_date', 'start', 'stop') widgets = { 'pause': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]), 'overtime': forms.TimeInput(format=DATETIME_FORMATS['input_time_formats'][0]), } class DayEntryCreateForm(DayEntryForm): def clean(self): cleaned_data = super(DayEntryCreateForm, self).clean() # Validate that there is not allready a day entry for the same day try: obj = DayEntry.objects.get(datebook=self.datebook, activity_date=self.daydate) except DayEntry.DoesNotExist: pass else: raise forms.ValidationError(_("This day entry has allready been created")) return cleaned_data
sveetch/django-datebook
datebook/forms/day.py
Python
mit
6,638
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ## \package pts.core.tools.special Special functions. # ----------------------------------------------------------------- # Ensure Python 3 compatibility from __future__ import absolute_import, division, print_function # Import standard modules import numpy as np # Import the relevant PTS classes and modules from ...magic.core.frame import Frame from ..basics.remote import Remote, connected_remotes from . import time from . import filesystem as fs from .logging import log # ----------------------------------------------------------------- def remote_convolution(image, kernel, host_id): """ This function ... :param image: :param kernel: :param host_id: """ # Check whether we are already connected to the specified remote host if host_id in connected_remotes and connected_remotes[host_id] is not None: remote = connected_remotes[host_id] else: # Debugging log.debug("Logging in to remote host ...") # Create a remote instance for the specified host ID remote = Remote() remote.setup(host_id) # Debugging log.debug("Creating temporary directory remotely ...") # Create a temporary directory to do the convolution remote_home_directory = remote.home_directory remote_temp_path = fs.join(remote_home_directory, time.unique_name("convolution")) remote.create_directory(remote_temp_path) # Debugging #log.debug("Uploading the kernel to the remote directory ...") # Upload the kernel FITS file to the remote directory #remote_kernel_path = fs.join(remote_temp_path, "kernel.fits") #remote.upload(kernel_path, remote_temp_path, new_name="kernel.fits", compress=True, show_output=True) # Debugging log.debug("Creating a local temporary directory ...") # Create a temporary directory locally to contain the frames local_temp_path = fs.join(fs.home(), time.unique_name("convolution")) fs.create_directory(local_temp_path) # Debugging log.debug("Saving the image frames to the temporary directory ...") # Save the frames local_frame_paths = [] constant_frames = [] for frame_name in image.frames: frame_path = fs.join(local_temp_path, frame_name + ".fits") # Only upload and convolve non-constant frames if not image.frames[frame_name].is_constant(): image.frames[frame_name].save(frame_path) local_frame_paths.append(frame_path) else: log.debug("The " + frame_name + " frame is constant, so this won't be uploaded and convolved") constant_frames.append(frame_name) # Debugging log.debug("Saving the kernel to the temporary directory ...") local_kernel_path = fs.join(local_temp_path, "kernel.fits") kernel.save(local_kernel_path) # Debugging log.debug("Uploading the image frames to the remote directory ...") # Upload the frames remote_frame_paths = [] for local_frame_path in local_frame_paths: # Determine the name of the local frame file frame_file_name = fs.name(local_frame_path) # Debugging log.debug("Uploading the " + fs.strip_extension(frame_file_name) + " frame ...") # Upload the frame file remote_frame_path = fs.join(remote_temp_path, frame_file_name) remote.upload(local_frame_path, remote_temp_path, new_name=frame_file_name, compress=True, show_output=True) remote_frame_paths.append(remote_frame_path) # Debugging log.debug("Uploading the kernel to the remote directory ...") # Upload the kernel remote_kernel_path = fs.join(remote_temp_path, "kernel.fits") remote.upload(local_kernel_path, remote_temp_path, new_name="kernel.fits", compress=True, show_output=True) # Debugging log.debug("Creating a python script to perform the convolution remotely ...") # Create a python script that does the convolution #script_file = tempfile.NamedTemporaryFile() #local_script_path = script_file.name local_script_path = fs.join(local_temp_path, "convolve.py") script_file = open(local_script_path, 'w') script_file.write("#!/usr/bin/env python\n") script_file.write("# -*- coding: utf8 -*-\n") script_file.write("\n") script_file.write("# Import astronomical modules\n") script_file.write("from astropy.units import Unit\n") script_file.write("\n") script_file.write("# Import the relevant PTS classes and modules\n") script_file.write("from pts.magic.core.frame import Frame\n") script_file.write("from pts.magic.core.image import Image\n") script_file.write("from pts.magic.core.kernel import ConvolutionKernel\n") script_file.write("from pts.core.tools.logging import log\n") script_file.write("\n") script_file.write("# Inform the user\n") script_file.write("log.info('Opening the kernel frame ...')\n") script_file.write("\n") script_file.write("# Open the kernel\n") script_file.write("kernel = ConvolutionKernel.from_file('" + remote_kernel_path + "')\n") script_file.write("\n") for remote_frame_path in remote_frame_paths: frame_name = fs.strip_extension(fs.name(remote_frame_path)) script_file.write("# Inform the user\n") script_file.write("log.info('Opening the " + frame_name + " frame ...')\n") script_file.write("\n") script_file.write("# Open the frame\n") script_file.write("frame = Frame.from_file('" + remote_frame_path + "')\n") script_file.write("\n") script_file.write("# Inform the user\n") script_file.write("log.info('Convolving the " + frame_name + " frame ...')\n") script_file.write("\n") script_file.write("# Do the convolution and save the result\n") script_file.write("frame.convolve(kernel, allow_huge=True)\n") script_file.write("frame.save('" + remote_frame_path + "')\n") # overwrite the frame script_file.write("\n") #script_file.write("# Save the image\n") #script_file.write("image.save(" + remote_image_path + ")\n") # Write to disk #script_file.flush() script_file.close() # Debugging log.debug("Uploading the python script ...") # Upload the script file remote_script_path = fs.join(remote_temp_path, "convolve.py") remote.upload(local_script_path, remote_temp_path, new_name="convolve.py", show_output=True) # Close the local script (it is automatically removed) #script_file.close() # Debugging log.debug("Executing the script remotely ...") # Execute the script file remotely remote.execute("python " + remote_script_path, output=False, show_output=True) # Debugging log.debug("Downloading the results ...") # Download the resulting FITS file (the convolved image) #local_result_path = self.full_output_path("convolved.fits") #remote.download(remote_image_path, fs.directory_of(local_result_path), new_name="convolved.fits", compress=True) for remote_frame_path in remote_frame_paths: # Determine the name of the local frame file frame_file_name = fs.name(remote_frame_path) # Debugging log.debug("Downloading the " + fs.strip_extension(frame_file_name) + " frame ...") # Download remote.download(remote_frame_path, local_temp_path, new_name=frame_file_name, compress=True, show_output=True) # Remove the temporary directory on the remote's filesystem remote.remove_directory(remote_temp_path) # Load the result #self.image = Image.from_file(local_result_path) for frame_name in image.frames.keys(): if frame_name in constant_frames: continue # Skip constant frames, these are not convolved local_frame_path = fs.join(local_temp_path, frame_name + ".fits") image.frames[frame_name] = Frame.from_file(local_frame_path) # Remove the local temporary directory fs.remove_directory(local_temp_path) # ----------------------------------------------------------------- def remote_convolution_frame(frame, kernel_path, host_id): """ This function ... :param frame: :param kernel_path: :param host_id: :return: """ # Check whether the frame is constant. If it is, we don't have to convolve! if frame.is_constant(): return frame.copy() # Check whether we are already connected to the specified remote host if host_id in connected_remotes and connected_remotes[host_id] is not None: remote = connected_remotes[host_id] else: # Debugging log.debug("Logging in to remote host ...") # Create a remote instance for the specified host ID remote = Remote() remote.setup(host_id) # Debugging log.debug("Creating temporary directory remotely ...") # Create a temporary directory to do the convolution remote_home_directory = remote.home_directory remote_temp_path = fs.join(remote_home_directory, time.unique_name("convolution")) remote.create_directory(remote_temp_path) # Debugging log.debug("Creating local temporary directory ...") # Create a temporary directory locally to contain the frames local_temp_path = fs.join(fs.home(), time.unique_name("convolution")) fs.create_directory(local_temp_path) # Debugging log.debug("Writing the frame to the temporary directory ...") # Write the frame local_frame_path = fs.join(local_temp_path, frame.name + ".fits") frame.save(local_frame_path) # Debugging #log.debug("Writing the kernel to the temporary directory ...") # Write the kernel #local_kernel_path = fs.join(local_temp_path, "kernel.fits") #kernel.save(local_kernel_path) # Debugging log.debug("Uploading the frame to the remote directory ...") # Upload the frame file remote_frame_path = fs.join(remote_temp_path, frame.name) remote.upload(local_frame_path, remote_temp_path, new_name=frame.name, compress=True, show_output=True) # Debugging #log.debug("Uploading the kernel to the remote directory ...") # Upload the kernel FITS file to the remote directory #remote_kernel_path = fs.join(remote_temp_path, "kernel.fits") #remote.upload(local_kernel_path, remote_temp_path, new_name="kernel.fits", compress=True, show_output=True) # Debugging log.debug("Uploading the kernel to the remote directory ...") # Upload the kernel FITS file to the remote directory remote_kernel_path = fs.join(remote_temp_path, "kernel.fits") remote.upload(kernel_path, remote_temp_path, new_name="kernel.fits", compress=True, show_output=True) # Debugging log.debug("Creating a python script to perform the convolution remotely ...") # Create the script local_script_path = fs.join(local_temp_path, "convolve.py") script_file = open(local_script_path, 'w') script_file.write("#!/usr/bin/env python\n") script_file.write("# -*- coding: utf8 -*-\n") script_file.write("\n") script_file.write("# Import the relevant PTS classes and modules\n") script_file.write("from pts.magic.core.frame import Frame\n") script_file.write("from pts.core.tools.logging import log\n") script_file.write("\n") script_file.write("# Inform the user\n") script_file.write("log.info('Opening the kernel frame ...')\n") script_file.write("\n") script_file.write("# Open the kernel frame\n") script_file.write("kernel = Frame.from_file('" + remote_kernel_path + "')\n") script_file.write("\n") script_file.write("# Inform the user\n") script_file.write("log.info('Opening the frame ...')\n") script_file.write("\n") script_file.write("# Open the frame\n") script_file.write("frame = Frame.from_file('" + remote_frame_path + "')\n") script_file.write("\n") script_file.write("# Inform the user\n") script_file.write("log.info('Convolving the frame ...')\n") script_file.write("\n") script_file.write("# Do the convolution and save the result\n") script_file.write("convolved = frame.convolved(kernel, allow_huge=True)\n") script_file.write("convolved.save('" + remote_frame_path + "')\n") # overwrite the frame # Write to disk script_file.close() # Debugging log.debug("Uploading the python script ...") # Upload the script file remote_script_path = fs.join(remote_temp_path, "convolve.py") remote.upload(local_script_path, remote_temp_path, new_name="convolve.py", show_output=True) # Debugging log.debug("Executing the script remotely ...") # Execute the script file remotely remote.execute("python " + remote_script_path, output=False, show_output=True) # Debugging log.debug("Downloading the result ...") # Determine the name of the local frame file frame_file_name = fs.name(remote_frame_path) # Debugging log.debug("Downloading the " + fs.strip_extension(frame_file_name) + " frame ...") # Download remote.download(remote_frame_path, local_temp_path, new_name=frame_file_name, compress=True, show_output=True) # Remove the temporary directory on the remote's filesystem remote.remove_directory(remote_temp_path) # Load the convolved frame convolved = Frame.from_file(local_frame_path) # Remove the local temporary directory fs.remove_directory(local_temp_path) # Return the convolved frame return convolved # ----------------------------------------------------------------- def remote_filter_convolution_no_pts(host_id, datacube_path, wavelengths, filters): """ This function ... :param host_id: :param datacube_path: :param wavelengths: :param filters: :return: """ # Check whether we are already connected to the specified remote host if host_id in connected_remotes and connected_remotes[host_id] is not None: remote = connected_remotes[host_id] else: # Debugging log.debug("Logging in to remote host ...") # Create a remote instance for the specified host ID remote = Remote() remote.setup(host_id) # Debugging log.debug("Creating temporary directory remotely ...") # Create a temporary directory to do the convolution remote_home_directory = remote.home_directory remote_temp_path = fs.join(remote_home_directory, time.unique_name("filter-convolution")) remote.create_directory(remote_temp_path) # Debugging log.debug("Creating local temporary directory ...") # Create a temporary directory locally to contain the frames local_temp_path = fs.join(fs.home(), time.unique_name("filter-convolution")) fs.create_directory(local_temp_path) integrated_transmissions = dict() # Loop over the filters for fltr in filters: # Get the transmission data fltr_wavelengths = fltr._Wavelengths fltr_transmission = fltr._Transmission fltr_integrated_transmission = fltr._IntegratedTransmission integrated_transmissions[fltr.name] = fltr_integrated_transmission # Save the transmission data path = fs.join(local_temp_path, "transmission__" + str(fltr) + ".dat") np.savetxt(path, (fltr_wavelengths, fltr_transmission)) #print(integrated_transmissions) #print(local_temp_path) integrated_path = fs.join(local_temp_path, "integrated_transmissions.txt") with open(integrated_path, 'w') as integrated_trans_file: for fltr_name in integrated_transmissions: integrated_trans_file.write(fltr_name + ": " + str(integrated_transmissions[fltr_name]) + "\n") # NOT FINISHED ... # ----------------------------------------------------------------- def remote_filter_convolution(host_id, datacube_path, wavelengths, filters, keep_output=False): """ This function ... :param host_id: :param datacube_path: :param wavelengths: :param filters: :param keep_output: :return: """ # Check whether we are already connected to the specified remote host if host_id in connected_remotes and connected_remotes[host_id] is not None: remote = connected_remotes[host_id] else: # Debugging log.debug("Logging in to remote host ...") # Create a remote instance for the specified host ID remote = Remote() remote.setup(host_id) # Debugging log.debug("Creating temporary directory remotely ...") # Create a temporary directory to do the convolution remote_home_directory = remote.home_directory remote_temp_path = fs.join(remote_home_directory, time.unique_name("filter-convolution")) remote.create_directory(remote_temp_path) # Debugging log.debug("Creating local temporary directory ...") # Create a temporary directory locally to contain the frames local_temp_path = fs.join(fs.home(), time.unique_name("filter-convolution")) fs.create_directory(local_temp_path) # Debugging log.debug("Uploading the datacube to the temporary remote directory ...") # Upload the frame file datacube_name = fs.name(datacube_path) remote_datacube_path = fs.join(remote_temp_path, datacube_name) remote.upload(datacube_path, remote_temp_path, compress=True, show_output=True) # Debugging log.debug("Writing the wavelengths to the temporary local directory ...") local_wavelengths_path = fs.join(local_temp_path, "wavelengths.txt") np.savetxt(local_wavelengths_path, wavelengths) # Debugging log.debug("Uploading the wavelengths file to the remote directory ...") # Upload the kernel FITS file to the remote directory remote_wavelengths_path = fs.join(remote_temp_path, "wavelengths.txt") remote.upload(local_wavelengths_path, remote_temp_path, compress=True, show_output=True) # Debugging log.debug("Creating a python script to perform the filter convolution remotely ...") # Create the script local_script_path = fs.join(local_temp_path, "make_images.py") script_file = open(local_script_path, 'w') script_file.write("#!/usr/bin/env python\n") script_file.write("# -*- coding: utf8 -*-\n") script_file.write("\n") script_file.write("# Import standard modules\n") script_file.write("import numpy as np\n") script_file.write("\n") script_file.write("# Import the relevant PTS classes and modules\n") script_file.write("from pts.magic.core.image import Image\n") script_file.write("from pts.magic.core.frame import Frame\n") script_file.write("from pts.core.basics.filter import Filter\n") script_file.write("from pts.core.tools.logging import log\n") script_file.write("from pts.core.tools import filesystem as fs\n") script_file.write("\n") script_file.write("# Inform the user\n") script_file.write("log.info('Loading the datacube ...')\n") script_file.write("\n") script_file.write("# Open the datacube as an Image\n") script_file.write("datacube = Image.from_file('" + remote_datacube_path + "', always_call_first_primary=False)\n") script_file.write("\n") script_file.write("# Inform the user\n") script_file.write("log.info('Loading the wavelengths ...')\n") script_file.write("\n") script_file.write("# Load the wavelengths from the text file\n") script_file.write("wavelengths = np.loadtxt('" + remote_wavelengths_path + "')\n") script_file.write("\n") script_file.write("# Convert the frames from neutral surface brightness to wavelength surface brightness\n") script_file.write("for l in range(len(wavelengths)):\n") script_file.write("\n") script_file.write(" # Get the wavelength\n") script_file.write(" wavelength = wavelengths[l]\n") script_file.write("\n") script_file.write(" # Determine the name of the frame in the datacube\n") script_file.write(" frame_name = 'frame' + str(l)\n") script_file.write("\n") script_file.write(" # Divide this frame by the wavelength in micron\n") script_file.write(" datacube.frames[frame_name] /= wavelength\n") script_file.write("\n") script_file.write(" # Set the new unit\n") script_file.write(" datacube.frames[frame_name].unit = 'W / (m2 * arcsec2 * micron)'\n") script_file.write("\n") script_file.write("# Convert the datacube to a numpy array where wavelength is the third dimension\n") script_file.write("fluxdensities = datacube.asarray()\n") script_file.write("\n") script_file.write("# Inform the user\n") script_file.write("log.info('Creating the filters ...')\n") script_file.write("\n") script_file.write("filters = dict()\n") script_file.write("\n") for filter_name in filters: fltr = filters[filter_name] script_file.write("# Inform the user\n") script_file.write("log.info('Creating the " + str(fltr) + " filter')\n") script_file.write("\n") script_file.write("fltr = Filter.from_string('" + str(fltr) + "')\n") script_file.write("filters['" + filter_name + "'] = fltr\n") script_file.write("\n") script_file.write("# Inform the user\n") script_file.write("log.info('Performing the filter convolutions ...')\n") script_file.write("\n") script_file.write("# Loop over the filters, perform the convolution\n") script_file.write("for filter_name in filters:\n") script_file.write("\n") script_file.write(" log.info('Making the observed image for the ' + str(fltr) + ' filter ...')\n") script_file.write(" fltr = filters[filter_name]\n") script_file.write(" data = fltr.convolve(wavelengths, fluxdensities)\n") script_file.write(" frame = Frame(data)\n") script_file.write(" frame.unit = 'W/(m2 * arcsec2 * micron)'\n") script_file.write(" path = fs.join('" + remote_temp_path + "', filter_name + '.fits')\n") script_file.write(" frame.save(path)\n") # Write to disk script_file.close() # Debugging log.debug("Uploading the python script ...") # Upload the script file remote_script_path = fs.join(remote_temp_path, "make_images.py") remote.upload(local_script_path, remote_temp_path, new_name="make_images.py", show_output=True) # Debugging log.debug("Executing the script remotely ...") # Execute the script file remotely remote.execute("python " + remote_script_path, output=False, show_output=True) # Remove the datacube in the remote directory remote.remove_file(remote_datacube_path) # Debugging log.debug("Downloading the convolved frames ...") # Download local_downloaded_temp_path = fs.join(fs.home(), fs.name(remote_temp_path)) fs.create_directory(local_downloaded_temp_path) remote.download(remote_temp_path, local_downloaded_temp_path, compress=True, show_output=True) # Remove the temporary directory on the remote's filesystem remote.remove_directory(remote_temp_path) # Remove the local temporary directory fs.remove_directory(local_temp_path) # Create a dictionary to contain the frames frames = dict() # Loop over the filters, load the frame for filter_name in filters: # Determine the path to the resulting FITS file path = fs.join(local_downloaded_temp_path, filter_name + ".fits") # Check whether the frame exists if not fs.is_file(path): raise RuntimeError("The image for filter " + str(filters[filter_name]) + " is missing") # Load the FITS file frame = Frame.from_file(path) # Add the frame to the dictionary frames[filter_name] = frame # Remove the downloaded temporary directory if not keep_output: fs.remove_directory(local_downloaded_temp_path) # Return the dictionary of frames return frames # -----------------------------------------------------------------
Stargrazer82301/CAAPR
CAAPR/CAAPR_AstroMagic/PTS/pts/core/tools/special.py
Python
mit
24,211
import React from 'react'; import {shallow} from 'enzyme'; import {BareCheckSuiteView} from '../../lib/views/check-suite-view'; import CheckRunView from '../../lib/views/check-run-view'; import checkSuiteQuery from '../../lib/views/__generated__/checkSuiteView_checkSuite.graphql'; import {checkSuiteBuilder} from '../builder/graphql/timeline'; describe('CheckSuiteView', function() { function buildApp(override = {}) { const props = { checkSuite: checkSuiteBuilder(checkSuiteQuery).build(), checkRuns: [], switchToIssueish: () => {}, ...override, }; return <BareCheckSuiteView {...props} />; } it('renders the summarized suite information', function() { const checkSuite = checkSuiteBuilder(checkSuiteQuery) .app(a => a.name('app')) .status('COMPLETED') .conclusion('SUCCESS') .build(); const wrapper = shallow(buildApp({checkSuite})); const icon = wrapper.find('Octicon'); assert.strictEqual(icon.prop('icon'), 'check'); assert.isTrue(icon.hasClass('github-PrStatuses--success')); assert.strictEqual(wrapper.find('.github-PrStatuses-list-item-context strong').text(), 'app'); }); it('omits app information when the app is no longer present', function() { const checkSuite = checkSuiteBuilder(checkSuiteQuery) .nullApp() .build(); const wrapper = shallow(buildApp({checkSuite})); assert.isTrue(wrapper.exists('Octicon')); assert.isFalse(wrapper.exists('.github-PrStatuses-list-item-context')); }); it('renders a CheckRun for each run within the suite', function() { const checkRuns = [{id: 0}, {id: 1}, {id: 2}]; const wrapper = shallow(buildApp({checkRuns})); assert.deepEqual(wrapper.find(CheckRunView).map(v => v.prop('checkRun')), checkRuns); }); });
atom/github
test/views/check-suite-view.test.js
JavaScript
mit
1,809
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var minus = exports.minus = { "viewBox": "0 0 20 20", "children": [{ "name": "path", "attribs": { "d": "M16,10c0,0.553-0.048,1-0.601,1H4.601C4.049,11,4,10.553,4,10c0-0.553,0.049-1,0.601-1h10.799C15.952,9,16,9.447,16,10z" } }] };
xuan6/admin_dashboard_local_dev
node_modules/react-icons-kit/entypo/minus.js
JavaScript
mit
308
/*! * jQuery JavaScript Library v1.11.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-17T15:27Z */ (function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper window is present, // execute the factory and get jQuery // For environments that do not inherently posses a window with a document // (such as Node.js), expose a jQuery-making factory as module.exports // This accentuates the need for the creation of a real window // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ // var deletedIds = []; var slice = deletedIds.slice; var concat = deletedIds.concat; var push = deletedIds.push; var indexOf = deletedIds.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var support = {}; var version = "1.11.2", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, // Support: Android<4.1, IE<9 // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num != null ? // Return just the one element from the set ( num < 0 ? this[ num + this.length ] : this[ num ] ) : // Return all the elements in a clean array slice.call( this ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: deletedIds.sort, splice: deletedIds.splice }; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { /* jshint eqeqeq: false */ return obj != null && obj == obj.window; }, isNumeric: function( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN // adding 1 corrects loss of precision from parseFloat (#15100) return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, isPlainObject: function( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. if ( support.ownLast ) { for ( key in obj ) { return hasOwn.call( obj, key ); } } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); }, type: function( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; }, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Support: Android<4.1, IE<9 trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( indexOf ) { return indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; while ( j < len ) { first[ i++ ] = second[ j++ ]; } // Support: IE<9 // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) if ( len !== len ) { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, now: function() { return +( new Date() ); }, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support }); // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.2.0-pre * http://sizzlejs.com/ * * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-16 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // http://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + characterEncoding + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; nodeType = context.nodeType; if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } if ( !seed && documentIsHTML ) { // Try to shortcut find operations when possible (e.g., not under DocumentFragment) if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document (jQuery #6963) if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType !== 1 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key + " " ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, parent, doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; parent = doc.defaultView; // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent !== parent.top ) { // IE11 does not have attachEvent, so all must suffer if ( parent.addEventListener ) { parent.addEventListener( "unload", unloadHandler, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", unloadHandler ); } } /* Support tests ---------------------------------------------------------------------- */ documentIsHTML = !isXML( doc ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Support: IE<9 support.getElementsByClassName = rnative.test( doc.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [ m ] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\f]' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); assert(function( div ) { // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( div.querySelectorAll("[name=d]").length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch (e) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( (node = elem[i++]) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[6] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] ) { match[2] = match[4] || match[5] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( (tokens = []) ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (oldCache = outerCache[ dir ]) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return (newCache[ 2 ] = oldCache[ 2 ]); } else { // Reuse newcache so results back-propagate to previous elements outerCache[ dir ] = newCache; // A match means we're done; a fail means we have to keep checking if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), len = elems.length; if ( outermost ) { outermostContext = context !== document && context; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( (selector = compiled.selector || selector) ); results = results || []; // Try to minimize operations if there is no seed and only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : (val = elem.getAttributeNode( name )) && val.specified ? val.value : null; } }); } return Sizzle; })( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; var rneedsContext = jQuery.expr.match.needsContext; var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; }); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } }); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // Use the correct document accordingly with window argument (sandbox) document = window.document, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, init = jQuery.fn.init = function( selector, context ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return typeof rootjQuery.ready !== "undefined" ? rootjQuery.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.extend({ dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); jQuery.fn.extend({ has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { return this.pushStack( jQuery.unique( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { ret = jQuery.unique( ret ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { ret = ret.reverse(); } } return this.pushStack( ret ); }; }); var rnotwhite = (/\S+/g); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !(--remaining) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); // The deferred used on DOM ready var readyList; jQuery.fn.ready = function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }; jQuery.extend({ // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).off( "ready" ); } } }); /** * Clean-up method for dom ready events */ function detach() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } } /** * The ready event handler and self cleanup method */ function completed() { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } } jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; var strundefined = typeof undefined; // Support: IE<9 // Iteration over object's inherited properties before its own var i; for ( i in jQuery( support ) ) { break; } support.ownLast = i !== "0"; // Note: most support tests are defined in their respective modules. // false until the test is run support.inlineBlockNeedsLayout = false; // Execute ASAP in case we need to set body.style.zoom jQuery(function() { // Minified: var a,b,c,d var val, div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Return for frameset docs that don't have a body return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); if ( typeof div.style.zoom !== strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; if ( val ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); }); (function() { var div = document.createElement( "div" ); // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } // Null elements to avoid leaks in IE. div = null; })(); /** * Determines whether an object can have data */ jQuery.acceptData = function( elem ) { var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], nodeType = +elem.nodeType || 1; // Do not set data on non-element DOM nodes because it will not be cleared (#8335). return nodeType !== 1 && nodeType !== 9 ? false : // Nodes accept data unless otherwise specified; rejection can be conditional !noData || noData !== true && elem.getAttribute("classid") === noData; }; var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /([A-Z])/g; function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } function internalData( elem, name, data, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var ret, thisCache, internalKey = jQuery.expando, // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { // Avoid exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( typeof name === "string" ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } i = name.length; while ( i-- ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) /* jshint eqeqeq: false */ } else if ( support.deleteExpando || cache != cache.window ) { /* jshint eqeqeq: true */ delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // The following elements (space-suffixed to avoid Object.prototype collisions) // throw uncatchable exceptions if you attempt to set expando properties noData: { "applet ": true, "embed ": true, // ...but Flash objects (which have this classid) *can* handle expandos "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); } }); jQuery.fn.extend({ data: function( key, value ) { var i, name, data, elem = this[0], attrs = elem && elem.attributes; // Special expections of .data basically thwart jQuery.access, // so implement the relevant behavior ourselves // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE11+ // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return arguments.length > 1 ? // Sets one value this.each(function() { jQuery.data( this, key, value ); }) : // Gets one value // Try to fetch any internally stored data first elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var isHidden = function( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); }; // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }; var rcheckableType = (/^(?:checkbox|radio)$/i); (function() { // Minified: var a,b,c var input = document.createElement( "input" ), div = document.createElement( "div" ), fragment = document.createDocumentFragment(); // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // IE strips leading whitespace when .innerHTML is used support.leadingWhitespace = div.firstChild.nodeType === 3; // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables support.tbody = !div.getElementsByTagName( "tbody" ).length; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works support.html5Clone = document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>"; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) input.type = "checkbox"; input.checked = true; fragment.appendChild( input ); support.appendChecked = input.checked; // Make sure textarea (and checkbox) defaultValue is properly cloned // Support: IE6-IE11+ div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // #11217 - WebKit loses check when the name is after the checked attribute fragment.appendChild( div ); div.innerHTML = "<input type='radio' checked='checked' name='t'/>"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() support.noCloneEvent = true; if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Execute the test only if not already executed in another module. if (support.deleteExpando == null) { // Support: IE<9 support.deleteExpando = true; try { delete div.test; } catch( e ) { support.deleteExpando = false; } } })(); (function() { var i, eventName, div = document.createElement( "div" ); // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; if ( !(support[ i + "Bubbles" ] = eventName in window) ) { // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) div.setAttribute( eventName, "t" ); support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; } } // Null elements to avoid leaks in IE. div = null; })(); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnotwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && jQuery.acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { /* jshint eqeqeq: false */ for ( ; cur != this; cur = cur.parentNode || this ) { /* jshint eqeqeq: true */ // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: IE < 9, Android < 4.0 src.returnValue === false ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && e.stopImmediatePropagation ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this, attaches = jQuery._data( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); jQuery._removeData( doc, fix ); } else { jQuery._data( doc, fix, attaches ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } // Support: IE<8 // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!support.noCloneEvent || !support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } deletedIds.push( id ); } } } } } }); jQuery.fn.extend({ text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, remove: function( selector, keepData /* Internal Use Only */ ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map(function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( support.htmlSerialize || !rnoshimcache.test( value ) ) && ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var arg = arguments[ 0 ]; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { arg = this.parentNode; jQuery.cleanData( getAll( this ) ); if ( arg ) { arg.replaceChild( elem, this ); } }); // Force removal if there was no new content (e.g., from empty arguments) return arg && (arg.length || arg.nodeType) ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback ) { // Flatten any nested arrays args = concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, self.html() ); } self.domManip( args, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); var iframe, elemdisplay = {}; /** * Retrieve the actual display of a element * @param {String} name nodeName of the element * @param {Object} doc Document object */ // Called only from within defaultDisplay function actualDisplay( name, doc ) { var style, elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), // getDefaultComputedStyle might be reliably used only on attached element display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? // Use of this method is a temporary fix (more like optmization) until something better comes along, // since it was removed from specification and supported only in FF style.display : jQuery.css( elem[ 0 ], "display" ); // We don't have any data stored on the element, // so use "detach" method as fast way to get rid of the element elem.detach(); return display; } /** * Try to determine the default display value of an element * @param {String} nodeName */ function defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document; // Support: IE doc.write(); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } (function() { var shrinkWrapBlocksVal; support.shrinkWrapBlocks = function() { if ( shrinkWrapBlocksVal != null ) { return shrinkWrapBlocksVal; } // Will be changed later if needed. shrinkWrapBlocksVal = false; // Minified: var b,c,d var div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); // Support: IE6 // Check if elements with layout shrink-wrap their children if ( typeof div.style.zoom !== strundefined ) { // Reset CSS: box-sizing; display; margin; border div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;" + "padding:1px;width:1px;zoom:1"; div.appendChild( document.createElement( "div" ) ).style.width = "5px"; shrinkWrapBlocksVal = div.offsetWidth !== 3; } body.removeChild( container ); return shrinkWrapBlocksVal; }; })(); var rmargin = (/^margin/); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles, curCSS, rposition = /^(top|right|bottom|left)$/; if ( window.getComputedStyle ) { getStyles = function( elem ) { // Support: IE<=11+, Firefox<=30+ (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" if ( elem.ownerDocument.defaultView.opener ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); } return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + ""; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, computed ) { var left, rs, rsLeft, ret, style = elem.style; computed = computed || getStyles( elem ); ret = computed ? computed[ name ] : undefined; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } // Support: IE // IE returns zIndex value as an integer. return ret === undefined ? ret : ret + "" || "auto"; }; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { var condition = conditionFn(); if ( condition == null ) { // The test was not ready at this point; screw the hook this time // but check again when needed next time. return; } if ( condition ) { // Hook not needed (or it's not possible to use it due to missing dependency), // remove it. // Since there are no other hooks for marginRight, remove the whole object. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return (this.get = hookFn).apply( this, arguments ); } }; } (function() { // Minified: var b,c,d,e,f,g, h,i var div, style, a, pixelPositionVal, boxSizingReliableVal, reliableHiddenOffsetsVal, reliableMarginRightVal; // Setup div = document.createElement( "div" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; style = a && a.style; // Finish early in limited (non-browser) environments if ( !style ) { return; } style.cssText = "float:left;opacity:.5"; // Support: IE<9 // Make sure that element opacity exists (as opposed to filter) support.opacity = style.opacity === "0.5"; // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" || style.WebkitBoxSizing === ""; jQuery.extend(support, { reliableHiddenOffsets: function() { if ( reliableHiddenOffsetsVal == null ) { computeStyleTests(); } return reliableHiddenOffsetsVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelPosition: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelPositionVal; }, // Support: Android 2.3 reliableMarginRight: function() { if ( reliableMarginRightVal == null ) { computeStyleTests(); } return reliableMarginRightVal; } }); function computeStyleTests() { // Minified: var b,c,d,j var div, body, container, contents; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" + "box-sizing:border-box;display:block;margin-top:1%;top:1%;" + "border:1px;padding:1px;width:4px;position:absolute"; // Support: IE<9 // Assume reasonable values in the absence of getComputedStyle pixelPositionVal = boxSizingReliableVal = false; reliableMarginRightVal = true; // Check for getComputedStyle so that this code is not run in IE<9. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right contents = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding contents.style.cssText = div.style.cssText = // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" + "box-sizing:content-box;display:block;margin:0;border:0;padding:0"; contents.style.marginRight = contents.style.width = "0"; div.style.width = "1px"; reliableMarginRightVal = !parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight ); div.removeChild( contents ); } // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; contents = div.getElementsByTagName( "td" ); contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; if ( reliableHiddenOffsetsVal ) { contents[ 0 ].style.display = ""; contents[ 1 ].style.display = "none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; } body.removeChild( container ); } })(); // A method for quickly swapping in/out CSS properties to get correct calculations. jQuery.swap = function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set. See: #7116 if ( value == null || value !== value ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Support: IE // Swallow errors from 'invalid' CSS values (#5509) try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; } }; jQuery.fx = Tween.prototype.init; // Back Compat <1.8 extension point jQuery.fx.step = {}; var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; } ] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = jQuery._data( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated display = jQuery.css( elem, "display" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !support.shrinkWrapBlocks() ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); // Any non-fx value stops us from restoring the original display value } else { display = undefined; } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = jQuery._data( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } // If this is a noop like .hide().hide(), restore an overwritten display value } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) { style.display = display; } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.timers = []; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }; (function() { // Minified: var a,b,c,d,e var input, div, select, a, opt; // Setup div = document.createElement( "div" ); div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName("a")[ 0 ]; // First batch of tests. select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px"; // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) support.getSetAttribute = div.className !== "t"; // Get the style information from getAttribute // (IE uses .cssText instead) support.style = /top/.test( a.getAttribute("style") ); // Make sure that URLs aren't manipulated // (IE normalizes it by default) support.hrefNormalized = a.getAttribute("href") === "/a"; // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) support.checkOn = !!input.value; // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) support.optSelected = opt.selected; // Tests for enctype support on a form (#6743) support.enctype = !!document.createElement("form").enctype; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE8 only // Check if we can trust getAttribute("value") input = document.createElement( "input" ); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; })(); var rreturn = /\r/g; jQuery.fn.extend({ val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE10-11+ // option.text throws exceptions (#14686, #14858) jQuery.trim( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) { // Support: IE6 // When new option element is added to select box we need to // force reflow of newly added node in order to workaround delay // of initialization properties try { option.selected = optionSet = true; } catch ( _ ) { // Will be executed only in IE6 option.scrollHeight; } } else { option.selected = false; } } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return options; } } } }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var nodeHook, boolHook, attrHandle = jQuery.expr.attrHandle, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = support.getSetAttribute, getSetInput = support.input; jQuery.fn.extend({ attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); } }); jQuery.extend({ attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { elem[ propName ] = false; // Support: IE<9 // Also clear defaultChecked/defaultSelected (if appropriate) } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } } }); // Hook for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // Retrieve booleans specially jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ? function( elem, name, isXML ) { var ret, handle; if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ name ]; attrHandle[ name ] = ret; ret = getter( elem, name, isXML ) != null ? name.toLowerCase() : null; attrHandle[ name ] = handle; } return ret; } : function( elem, name, isXML ) { if ( !isXML ) { return elem[ jQuery.camelCase( "default-" + name ) ] ? name.toLowerCase() : null; } }; }); // fix oldIE attroperties if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = { set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) if ( name === "value" || value === elem.getAttribute( name ) ) { return value; } } }; // Some attributes are constructed with empty-string values when not defined attrHandle.id = attrHandle.name = attrHandle.coords = function( elem, name, isXML ) { var ret; if ( !isXML ) { return (ret = elem.getAttributeNode( name )) && ret.value !== "" ? ret.value : null; } }; // Fixing value retrieval on a button requires this module jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); if ( ret && ret.specified ) { return ret.value; } }, set: nodeHook.set }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }; }); } if ( !support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } var rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend({ prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); } }); jQuery.extend({ propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); return tabindex ? parseInt( tabindex, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : -1; } } } }); // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !support.hrefNormalized ) { // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } // Support: Safari, IE9+ // mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // IE6/7 call enctype encoding if ( !support.enctype ) { jQuery.propFix.enctype = "encoding"; } var rclass = /[\t\r\n\f]/g; jQuery.fn.extend({ addClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // only assign if different to avoid unneeded rendering. finalValue = jQuery.trim( cur ); if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, finalValue, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // only assign if different to avoid unneeded rendering. finalValue = value ? jQuery.trim( cur ) : ""; if ( elem.className !== finalValue ) { elem.className = finalValue; } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; } }); // Return jQuery for attributes-only inclusion jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var nonce = jQuery.now(); var rquery = (/\?/); var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g; jQuery.parseJSON = function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { // Support: Android 2.3 // Workaround failure to string-cast null input return window.JSON.parse( data + "" ); } var requireNonComma, depth = null, str = jQuery.trim( data + "" ); // Guard against invalid (and possibly dangerous) input by ensuring that nothing remains // after removing valid tokens return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) { // Force termination if we see a misplaced comma if ( requireNonComma && comma ) { depth = 0; } // Perform no more replacements after returning to outermost depth if ( depth === 0 ) { return token; } // Commas must not follow "[", "{", or "," requireNonComma = open || comma; // Determine new depth // array/object open ("[" or "{"): depth += true - false (increment) // array/object close ("]" or "}"): depth += false - true (decrement) // other cases ("," or primitive): depth += true - true (numeric cast) depth += !close - !open; // Remove this token return ""; }) ) ? ( Function( "return " + str ) )() : jQuery.error( "Invalid JSON: " + data ); }; // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data, "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }; var // Document location ajaxLocParts, ajaxLocation, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType.charAt( 0 ) === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + nonce++ ) : // Otherwise add one to the end cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery._evalUrl = function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); }; jQuery.fn.extend({ wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!support.reliableHiddenOffsets() && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function() { var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); }) .map(function( i, elem ) { var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ? // Support: IE6+ function() { // XHR cannot access local files, always use ActiveX for that case return !this.isLocal && // Support: IE7-8 // oldIE XHR does not support non-RFC2616 methods (#13240) // See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx // and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9 // Although this check for six methods instead of eight // since IE also does not support "trace" and "connect" /^(get|post|head|put|delete|options)$/i.test( this.type ) && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; var xhrId = 0, xhrCallbacks = {}, xhrSupported = jQuery.ajaxSettings.xhr(); // Support: IE<10 // Open requests must be manually aborted on unload (#5280) // See https://support.microsoft.com/kb/2856746 for more info if ( window.attachEvent ) { window.attachEvent( "onunload", function() { for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }); } // Determine support properties support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( options ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !options.crossDomain || support.cors ) { var callback; return { send: function( headers, complete ) { var i, xhr = options.xhr(), id = ++xhrId; // Open the socket xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { // Support: IE<9 // IE's ActiveXObject throws a 'Type Mismatch' exception when setting // request header to a null-value. // // To keep consistent with other XHR implementations, cast the value // to string and ignore `undefined`. if ( headers[ i ] !== undefined ) { xhr.setRequestHeader( i, headers[ i ] + "" ); } } // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( options.hasContent && options.data ) || null ); // Listener callback = function( _, isAbort ) { var status, statusText, responses; // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Clean up delete xhrCallbacks[ id ]; callback = undefined; xhr.onreadystatechange = jQuery.noop; // Abort manually if needed if ( isAbort ) { if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; // Support: IE<10 // Accessing binary-data responseText throws an exception // (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && options.isLocal && !options.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, xhr.getAllResponseHeaders() ); } }; if ( !options.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { // Add to the list of active xhr callbacks xhr.onreadystatechange = xhrCallbacks[ id ] = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject( "Microsoft.XMLHTTP" ); } catch( e ) {} } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; // Keep a copy of the old load method var _load = jQuery.fn.load; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = jQuery.trim( url.slice( off, url.length ) ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; }); jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; var docElem = window.document.documentElement; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ offset: function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); }); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; }); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in // AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === strundefined ) { window.jQuery = window.$ = jQuery; } return jQuery; })); /* ======================================================================== * Bootstrap: affix.js v3.3.2 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$target = $(this.options.target) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = this.pinnedOffset = null this.checkPosition() } Affix.VERSION = '3.3.2' Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0, target: window } Affix.prototype.getState = function (scrollHeight, height, offsetTop, offsetBottom) { var scrollTop = this.$target.scrollTop() var position = this.$element.offset() var targetHeight = this.$target.height() if (offsetTop != null && this.affixed == 'top') return scrollTop < offsetTop ? 'top' : false if (this.affixed == 'bottom') { if (offsetTop != null) return (scrollTop + this.unpin <= position.top) ? false : 'bottom' return (scrollTop + targetHeight <= scrollHeight - offsetBottom) ? false : 'bottom' } var initializing = this.affixed == null var colliderTop = initializing ? scrollTop : position.top var colliderHeight = initializing ? targetHeight : height if (offsetTop != null && scrollTop <= offsetTop) return 'top' if (offsetBottom != null && (colliderTop + colliderHeight >= scrollHeight - offsetBottom)) return 'bottom' return false } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$target.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var height = this.$element.height() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom var scrollHeight = $('body').height() if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.getState(scrollHeight, height, offsetTop, offsetBottom) if (this.affixed != affix) { if (this.unpin != null) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger(affixType.replace('affix', 'affixed') + '.bs.affix') } if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - height - offsetBottom }) } } // AFFIX PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.affix $.fn.affix = Plugin $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom != null) data.offset.bottom = data.offsetBottom if (data.offsetTop != null) data.offset.top = data.offsetTop Plugin.call($spy, data) }) }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.3.2 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.VERSION = '3.3.2' Alert.TRANSITION_DURATION = 150 Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.closest('.alert') } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { // detach from parent, fire event then clean up data $parent.detach().trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one('bsTransitionEnd', removeElement) .emulateTransitionEnd(Alert.TRANSITION_DURATION) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.alert $.fn.alert = Plugin $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.3.2 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.VERSION = '3.3.2' Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (data.resetText == null) $el.data('resetText', $el[val]()) // push to event loop to allow forms to submit setTimeout($.proxy(function () { $el[val](data[state] == null ? this.options[state] : data[state]) if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } else { this.$element.attr('aria-pressed', !this.$element.hasClass('active')) } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } var old = $.fn.button $.fn.button = Plugin $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document) .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') Plugin.call($btn, 'toggle') e.preventDefault() }) .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) { $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type)) }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.3.2 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.2' Carousel.TRANSITION_DURATION = 600 Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } Carousel.prototype.keydown = function (e) { if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } e.preventDefault() } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } Carousel.prototype.getItemForDirection = function (direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= var clickHandler = function (e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.3.2 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.$trigger = $(this.options.trigger).filter('[href="#' + element.id + '"], [data-target="#' + element.id + '"]') this.transitioning = null if (this.options.parent) { this.$parent = this.getParent() } else { this.addAriaAndCollapsedClass(this.$element, this.$trigger) } if (this.options.toggle) this.toggle() } Collapse.VERSION = '3.3.2' Collapse.TRANSITION_DURATION = 350 Collapse.DEFAULTS = { toggle: true, trigger: '[data-toggle="collapse"]' } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var activesData var actives = this.$parent && this.$parent.children('.panel').children('.in, .collapsing') if (actives && actives.length) { activesData = actives.data('bs.collapse') if (activesData && activesData.transitioning) return } var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return if (actives && actives.length) { Plugin.call(actives, 'hide') activesData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing')[dimension](0) .attr('aria-expanded', true) this.$trigger .removeClass('collapsed') .attr('aria-expanded', true) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in')[dimension]('') this.transitioning = 0 this.$element .trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION)[dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element[dimension](this.$element[dimension]())[0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse in') .attr('aria-expanded', false) this.$trigger .addClass('collapsed') .attr('aria-expanded', false) this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .removeClass('collapsing') .addClass('collapse') .trigger('hidden.bs.collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one('bsTransitionEnd', $.proxy(complete, this)) .emulateTransitionEnd(Collapse.TRANSITION_DURATION) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } Collapse.prototype.getParent = function () { return $(this.options.parent) .find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]') .each($.proxy(function (i, element) { var $element = $(element) this.addAriaAndCollapsedClass(getTargetFromTrigger($element), $element) }, this)) .end() } Collapse.prototype.addAriaAndCollapsedClass = function ($element, $trigger) { var isOpen = $element.hasClass('in') $element.attr('aria-expanded', isOpen) $trigger .toggleClass('collapsed', !isOpen) .attr('aria-expanded', isOpen) } function getTargetFromTrigger($trigger) { var href var target = $trigger.attr('data-target') || (href = $trigger.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') // strip for ie7 return $(target) } // COLLAPSE PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && option == 'show') options.toggle = false if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.collapse $.fn.collapse = Plugin $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle="collapse"]', function (e) { var $this = $(this) if (!$this.attr('data-target')) e.preventDefault() var $target = getTargetFromTrigger($this) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $.extend({}, $this.data(), { trigger: this }) Plugin.call($target, option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.3.2 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle="dropdown"]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.VERSION = '3.3.2' Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this .trigger('focus') .attr('aria-expanded', 'true') $parent .toggleClass('open') .trigger('shown.bs.dropdown', relatedTarget) } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if ((!isActive && e.which != 27) || (isActive && e.which == 27)) { if (e.which == 27) $parent.find(toggle).trigger('focus') return $this.trigger('click') } var desc = ' li:not(.divider):visible a' var $items = $parent.find('[role="menu"]' + desc + ', [role="listbox"]' + desc) if (!$items.length) return var index = $items.index(e.target) if (e.which == 38 && index > 0) index-- // up if (e.which == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).trigger('focus') } function clearMenus(e) { if (e && e.which === 3) return $(backdrop).remove() $(toggle).each(function () { var $this = $(this) var $parent = getParent($this) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $this.attr('aria-expanded', 'false') $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget) }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } var old = $.fn.dropdown $.fn.dropdown = Plugin $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle, Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '[role="menu"]', Dropdown.prototype.keydown) .on('keydown.bs.dropdown.data-api', '[role="listbox"]', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.3.2 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.VERSION = '3.3.2' Tab.TRANSITION_DURATION = 150 Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } if ($this.parent('li').hasClass('active')) return var $previous = $ul.find('.active:last a') var hideEvent = $.Event('hide.bs.tab', { relatedTarget: $this[0] }) var showEvent = $.Event('show.bs.tab', { relatedTarget: $previous[0] }) $previous.trigger(hideEvent) $this.trigger(showEvent) if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return var $target = $(selector) this.activate($this.closest('li'), $ul) this.activate($target, $target.parent(), function () { $previous.trigger({ type: 'hidden.bs.tab', relatedTarget: $this[0] }) $this.trigger({ type: 'shown.bs.tab', relatedTarget: $previous[0] }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && (($active.length && $active.hasClass('fade')) || !!container.find('> .fade').length) function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', false) element .addClass('active') .find('[data-toggle="tab"]') .attr('aria-expanded', true) if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element .closest('li.dropdown') .addClass('active') .end() .find('[data-toggle="tab"]') .attr('aria-expanded', true) } callback && callback() } $active.length && transition ? $active .one('bsTransitionEnd', next) .emulateTransitionEnd(Tab.TRANSITION_DURATION) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tab $.fn.tab = Plugin $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ var clickHandler = function (e) { e.preventDefault() Plugin.call($(this), 'show') } $(document) .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler) .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler) }(jQuery); /* ======================================================================== * Bootstrap: transition.js v3.3.2 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { WebkitTransition : 'webkitTransitionEnd', MozTransition : 'transitionend', OTransition : 'oTransitionEnd otransitionend', transition : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false var $el = this $(this).one('bsTransitionEnd', function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() if (!$.support.transition) return $.event.special.bsTransitionEnd = { bindType: $.support.transition.end, delegateType: $.support.transition.end, handle: function (e) { if ($(e.target).is(this)) return e.handleObj.handler.apply(this, arguments) } } }) }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.3.2 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var process = $.proxy(this.process, this) this.$body = $('body') this.$scrollElement = $(element).is('body') ? $(window) : $(element) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || '') + ' .nav li > a' this.offsets = [] this.targets = [] this.activeTarget = null this.scrollHeight = 0 this.$scrollElement.on('scroll.bs.scrollspy', process) this.refresh() this.process() } ScrollSpy.VERSION = '3.3.2' ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) } ScrollSpy.prototype.refresh = function () { var offsetMethod = 'offset' var offsetBase = 0 if (!$.isWindow(this.$scrollElement[0])) { offsetMethod = 'position' offsetBase = this.$scrollElement.scrollTop() } this.offsets = [] this.targets = [] this.scrollHeight = this.getScrollHeight() var self = this this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[$href[offsetMethod]().top + offsetBase, href]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.getScrollHeight() var maxScroll = this.options.offset + scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (this.scrollHeight != scrollHeight) { this.refresh() } if (scrollTop >= maxScroll) { return activeTarget != (i = targets[targets.length - 1]) && this.activate(i) } if (activeTarget && scrollTop < offsets[0]) { this.activeTarget = null return this.clear() } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate(targets[i]) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target this.clear() var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } ScrollSpy.prototype.clear = function () { $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') } // SCROLLSPY PLUGIN DEFINITION // =========================== function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.scrollspy $.fn.scrollspy = Plugin $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load.bs.scrollspy.data-api', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) Plugin.call($spy, $spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.3.2 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$body = $(document.body) this.$element = $(element) this.$backdrop = this.isShown = null this.scrollbarWidth = 0 if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.VERSION = '3.3.2' Modal.TRANSITION_DURATION = 300 Modal.BACKDROP_TRANSITION_DURATION = 150 Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this.isShown ? this.hide() : this.show(_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.checkScrollbar() this.setScrollbar() this.$body.addClass('modal-open') this.escape() this.resize() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(that.$body) // don't move modals dom position } that.$element .show() .scrollTop(0) if (that.options.backdrop) that.adjustBackdrop() that.adjustDialog() if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() this.resize() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one('bsTransitionEnd', $.proxy(this.hideModal, this)) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.trigger('focus') } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keydown.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keydown.dismiss.bs.modal') } } Modal.prototype.resize = function () { if (this.isShown) { $(window).on('resize.bs.modal', $.proxy(this.handleUpdate, this)) } else { $(window).off('resize.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.$body.removeClass('modal-open') that.resetAdjustments() that.resetScrollbar() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var that = this var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .prependTo(this.$element) .on('click.dismiss.bs.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one('bsTransitionEnd', callback) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') var callbackRemove = function () { that.removeBackdrop() callback && callback() } $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one('bsTransitionEnd', callbackRemove) .emulateTransitionEnd(Modal.BACKDROP_TRANSITION_DURATION) : callbackRemove() } else if (callback) { callback() } } // these following methods are used to handle overflowing modals Modal.prototype.handleUpdate = function () { if (this.options.backdrop) this.adjustBackdrop() this.adjustDialog() } Modal.prototype.adjustBackdrop = function () { this.$backdrop .css('height', 0) .css('height', this.$element[0].scrollHeight) } Modal.prototype.adjustDialog = function () { var modalIsOverflowing = this.$element[0].scrollHeight > document.documentElement.clientHeight this.$element.css({ paddingLeft: !this.bodyIsOverflowing && modalIsOverflowing ? this.scrollbarWidth : '', paddingRight: this.bodyIsOverflowing && !modalIsOverflowing ? this.scrollbarWidth : '' }) } Modal.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: '', paddingRight: '' }) } Modal.prototype.checkScrollbar = function () { this.bodyIsOverflowing = document.body.scrollHeight > document.documentElement.clientHeight this.scrollbarWidth = this.measureScrollbar() } Modal.prototype.setScrollbar = function () { var bodyPad = parseInt((this.$body.css('padding-right') || 0), 10) if (this.bodyIsOverflowing) this.$body.css('padding-right', bodyPad + this.scrollbarWidth) } Modal.prototype.resetScrollbar = function () { this.$body.css('padding-right', '') } Modal.prototype.measureScrollbar = function () { // thx walsh var scrollDiv = document.createElement('div') scrollDiv.className = 'modal-scrollbar-measure' this.$body.append(scrollDiv) var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth this.$body[0].removeChild(scrollDiv) return scrollbarWidth } // MODAL PLUGIN DEFINITION // ======================= function Plugin(option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } var old = $.fn.modal $.fn.modal = Plugin $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) // strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target.one('show.bs.modal', function (showEvent) { if (showEvent.isDefaultPrevented()) return // only register focus restorer if modal will actually get shown $target.one('hidden.bs.modal', function () { $this.is(':visible') && $this.trigger('focus') }) }) Plugin.call($target, option, this) }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.3.2 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.VERSION = '3.3.2' Tooltip.TRANSITION_DURATION = 150 Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false, viewport: { selector: 'body', padding: 0 } } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (self && self.$tip && self.$tip.is(':visible')) { self.hoverState = 'in' return } if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(obj.currentTarget, this.getDelegateOptions()) $(obj.currentTarget).data('bs.' + this.type, self) } clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]) if (e.isDefaultPrevented() || !inDom) return var that = this var $tip = this.tip() var tipId = this.getUID(this.type) this.setContent() $tip.attr('id', tipId) this.$element.attr('aria-describedby', tipId) if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) .data('bs.' + this.type, this) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var orgPlacement = placement var $container = this.options.container ? $(this.options.container) : this.$element.parent() var containerDim = this.getPosition($container) placement = placement == 'bottom' && pos.bottom + actualHeight > containerDim.bottom ? 'top' : placement == 'top' && pos.top - actualHeight < containerDim.top ? 'bottom' : placement == 'right' && pos.right + actualWidth > containerDim.width ? 'left' : placement == 'left' && pos.left - actualWidth < containerDim.left ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) var complete = function () { var prevHoverState = that.hoverState that.$element.trigger('shown.bs.' + that.type) that.hoverState = null if (prevHoverState == 'out') that.leave(that) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { offset.top = offset.top + height - actualHeight } var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight) if (delta.left) offset.left += delta.left else offset.top += delta.top var isVertical = /top|bottom/.test(placement) var arrowDelta = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight' $tip.offset(offset) this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function (delta, dimension, isHorizontal) { this.arrow() .css(isHorizontal ? 'left' : 'top', 50 * (1 - delta / dimension) + '%') .css(isHorizontal ? 'top' : 'left', '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function (callback) { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element .removeAttr('aria-describedby') .trigger('hidden.bs.' + that.type) callback && callback() } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one('bsTransitionEnd', complete) .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function ($element) { $element = $element || this.$element var el = $element[0] var isBody = el.tagName == 'BODY' var elRect = el.getBoundingClientRect() if (elRect.width == null) { // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093 elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top }) } var elOffset = isBody ? { top: 0, left: 0 } : $element.offset() var scroll = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() } var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null return $.extend({}, elRect, scroll, outerDims, elOffset) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) { var delta = { top: 0, left: 0 } if (!this.$viewport) return delta var viewportPadding = this.options.viewport && this.options.viewport.padding || 0 var viewportDimensions = this.getPosition(this.$viewport) if (/right|left/.test(placement)) { var topEdgeOffset = pos.top - viewportPadding - viewportDimensions.scroll var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight if (topEdgeOffset < viewportDimensions.top) { // top overflow delta.top = viewportDimensions.top - topEdgeOffset } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset } } else { var leftEdgeOffset = pos.left - viewportPadding var rightEdgeOffset = pos.left + viewportPadding + actualWidth if (leftEdgeOffset < viewportDimensions.left) { // left overflow delta.left = viewportDimensions.left - leftEdgeOffset } else if (rightEdgeOffset > viewportDimensions.width) { // right overflow delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset } } return delta } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.getUID = function (prefix) { do prefix += ~~(Math.random() * 1000000) while (document.getElementById(prefix)) return prefix } Tooltip.prototype.tip = function () { return (this.$tip = this.$tip || $(this.options.template)) } Tooltip.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = this if (e) { self = $(e.currentTarget).data('bs.' + this.type) if (!self) { self = new this.constructor(e.currentTarget, this.getDelegateOptions()) $(e.currentTarget).data('bs.' + this.type, self) } } self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { var that = this clearTimeout(this.timeout) this.hide(function () { that.$element.off('.' + that.type).removeData('bs.' + that.type) }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.tooltip $.fn.tooltip = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.3.2 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.VERSION = '3.3.2' Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content').children().detach().end()[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return (this.$arrow = this.$arrow || this.tip().find('.arrow')) } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } var old = $.fn.popover $.fn.popover = Plugin $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery);
mohamed-mehany/SyntaxTerror
blog/public/assets/test/dummy_rails/app/assets/javascripts/application-768a0262af2eb7663859c5e8395c2b25.js
JavaScript
mit
350,371
#include "Agent.h" #include <algorithm> Agent::Agent() { } Agent::Agent(float _speed, float _health, const glm::vec2 & _startPos, const GameEngine::GLTexture & _texture, GameEngine::ColorRGBA8 & _color, std::weak_ptr<World> _world) : m_movementSpeed(_speed), m_health(_health), m_worldPos(_startPos), m_texture(_texture), m_color(_color), m_world(_world) { } Agent::~Agent() {} void Agent::Draw(GameEngine::SpriteBatch & _batch) { const glm::vec4 uvRect(0.0f, 0.0f, 1.0f, 1.0f); glm::vec4 destRect; destRect.x = m_worldPos.x; //bottom left world pos destRect.y = m_worldPos.y; //bottom left world pos destRect.z = AGENT_DIAMETER; //width destRect.w = AGENT_DIAMETER; //height _batch.Draw(destRect, uvRect, m_texture.id, 0.0f, m_color, m_direction); } bool Agent::CollideWithLevel() { std::vector<glm::vec2> collideTilePositions; // Check the four corners // First corner (bottom left) CheckTilePosition(collideTilePositions, m_worldPos.x, m_worldPos.y); // Second Corner (bottom right) CheckTilePosition(collideTilePositions, m_worldPos.x + AGENT_DIAMETER, m_worldPos.y); // Third Corner (top left) CheckTilePosition(collideTilePositions, m_worldPos.x, m_worldPos.y + AGENT_DIAMETER); // Fourth Corner (top right) CheckTilePosition(collideTilePositions, m_worldPos.x + AGENT_DIAMETER, m_worldPos.y + AGENT_DIAMETER); // Check if there was no collision if (collideTilePositions.empty()) { return false; } //Store the world center position of the player to use it for sorting glm::vec2 localWorld = m_worldPos + glm::vec2(AGENT_RADIUS); /*sort the tiles to collide based on distance from the center of the player, so that you collide with the nearest walls first and avoid the getting stuck on walls bug */ std::sort(collideTilePositions.begin(), collideTilePositions.end(), [&localWorld](const glm::vec2& _p1, const glm::vec2& _p2) { auto distance1 = glm::distance(localWorld, _p1); auto distance2 = glm::distance(localWorld, _p2); return distance1 < distance2; }); // Do the collision starting from closes tile to collide with to furthest for (auto& tilePos : collideTilePositions) { CollideWithTile(tilePos); } return true; } bool Agent::CollideWithAgent(Agent* _agent) { // direction vector between the two agents (center of this agent minus center of other agent) glm::vec2 direction = GetCenterPos() - _agent->GetCenterPos(); // Length of the direction vector float distance = glm::length(direction); // Depth of the collision float collisionDepth = AGENT_DIAMETER - distance; // If collision depth > 0 then we did collide if (collisionDepth > 0) { // Get the direction times the collision depth so we can push them away from each other glm::vec2 collisionDepthVec = glm::normalize(direction) * collisionDepth; // Push them in opposite directions m_worldPos += collisionDepthVec / 2.0f; _agent->m_worldPos -= collisionDepthVec / 2.0f; return true; } return false; } void Agent::ApplyDamage(float _damage) { m_health -= _damage; } void Agent::CheckTilePosition(std::vector<glm::vec2>& _collideTilePositions, float _x, float _y) { //Get the node/tile at this agent's world pos std::weak_ptr<Node> node = m_world.lock()->GetWorldGrid().lock()->GetNodeAt(glm::vec2(_x, _y)); //if this is not a walkable tile, then collide with it if (!node.lock()->walkable) { _collideTilePositions.push_back(node.lock()->worldPos); } } void Agent::CollideWithTile(const glm::vec2 & _tilePos) { constexpr float TILE_RADIUS = TILE_WIDTH / 2.0f; // The minimum distance before a collision occurs constexpr float MIN_DISTANCE = AGENT_RADIUS + TILE_RADIUS; // Center position of the agent glm::vec2 centerAgentPos = m_worldPos + glm::vec2(AGENT_RADIUS); // direction vector from the agent to the tile glm::vec2 direction = centerAgentPos - _tilePos; // Get the depth of the collision float xDepth = MIN_DISTANCE - abs(direction.x); float yDepth = MIN_DISTANCE - abs(direction.y); // If both the depths are > 0, then we collided if (xDepth > 0 && yDepth > 0) { // Check which collision depth is less if (std::max(xDepth, 0.0f) < std::max(yDepth, 0.0f)) { // X collsion depth is smaller so we push in X direction if (direction.x < 0) { m_worldPos.x -= xDepth; } else { m_worldPos.x += xDepth; } } else { // Y collsion depth is smaller so we push in X direction if (direction.y < 0) { m_worldPos.y -= yDepth; } else { m_worldPos.y += yDepth; } } } }
VasilStamatov/GraphicsLearning
AI_Game/Agent.cpp
C++
mit
4,846
#!/usr/bin/env python # -*- coding: utf-8 -*- """ | This file is part of the web2py Web Framework | Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> | License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Provides: - List; like list but returns None instead of IndexOutOfBounds - Storage; like dictionary allowing also for `obj.foo` for `obj['foo']` """ try: import cPickle as pickle except: import pickle import copy_reg import gluon.portalocker as portalocker __all__ = ['List', 'Storage', 'Settings', 'Messages', 'StorageList', 'load_storage', 'save_storage'] DEFAULT = lambda:0 class Storage(dict): """ A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`, and setting obj.foo = None deletes item foo. Example:: >>> o = Storage(a=1) >>> print o.a 1 >>> o['a'] 1 >>> o.a = 2 >>> print o['a'] 2 >>> del o.a >>> print o.a None """ __slots__ = () __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__ __getitem__ = dict.get __getattr__ = dict.get __getnewargs__ = lambda self: getattr(dict,self).__getnewargs__(self) __repr__ = lambda self: '<Storage %s>' % dict.__repr__(self) # http://stackoverflow.com/questions/5247250/why-does-pickle-getstate-accept-as-a-return-value-the-very-instance-it-requi __getstate__ = lambda self: None __copy__ = lambda self: Storage(self) def getlist(self, key): """ Returns a Storage value as a list. If the value is a list it will be returned as-is. If object is None, an empty list will be returned. Otherwise, `[value]` will be returned. Example output for a query string of `?x=abc&y=abc&y=def`:: >>> request = Storage() >>> request.vars = Storage() >>> request.vars.x = 'abc' >>> request.vars.y = ['abc', 'def'] >>> request.vars.getlist('x') ['abc'] >>> request.vars.getlist('y') ['abc', 'def'] >>> request.vars.getlist('z') [] """ value = self.get(key, []) if value is None or isinstance(value, (list, tuple)): return value else: return [value] def getfirst(self, key, default=None): """ Returns the first value of a list or the value itself when given a `request.vars` style key. If the value is a list, its first item will be returned; otherwise, the value will be returned as-is. Example output for a query string of `?x=abc&y=abc&y=def`:: >>> request = Storage() >>> request.vars = Storage() >>> request.vars.x = 'abc' >>> request.vars.y = ['abc', 'def'] >>> request.vars.getfirst('x') 'abc' >>> request.vars.getfirst('y') 'abc' >>> request.vars.getfirst('z') """ values = self.getlist(key) return values[0] if values else default def getlast(self, key, default=None): """ Returns the last value of a list or value itself when given a `request.vars` style key. If the value is a list, the last item will be returned; otherwise, the value will be returned as-is. Simulated output with a query string of `?x=abc&y=abc&y=def`:: >>> request = Storage() >>> request.vars = Storage() >>> request.vars.x = 'abc' >>> request.vars.y = ['abc', 'def'] >>> request.vars.getlast('x') 'abc' >>> request.vars.getlast('y') 'def' >>> request.vars.getlast('z') """ values = self.getlist(key) return values[-1] if values else default def pickle_storage(s): return Storage, (dict(s),) copy_reg.pickle(Storage, pickle_storage) PICKABLE = (str, int, long, float, bool, list, dict, tuple, set) class StorageList(Storage): """ Behaves like Storage but missing elements defaults to [] instead of None """ def __getitem__(self, key): return self.__getattr__(key) def __getattr__(self, key): if key in self: return self.get(key) else: r = [] self[key] = r return r def load_storage(filename): fp = None try: fp = portalocker.LockedFile(filename, 'rb') storage = pickle.load(fp) finally: if fp: fp.close() return Storage(storage) def save_storage(storage, filename): fp = None try: fp = portalocker.LockedFile(filename, 'wb') pickle.dump(dict(storage), fp) finally: if fp: fp.close() class Settings(Storage): def __setattr__(self, key, value): if key != 'lock_keys' and self['lock_keys'] and key not in self: raise SyntaxError('setting key \'%s\' does not exist' % key) if key != 'lock_values' and self['lock_values']: raise SyntaxError('setting value cannot be changed: %s' % key) self[key] = value class Messages(Settings): def __init__(self, T): Storage.__init__(self, T=T) def __getattr__(self, key): value = self[key] if isinstance(value, str): return self.T(value) return value class FastStorage(dict): """ Eventually this should replace class Storage but causes memory leak because of http://bugs.python.org/issue1469629 >>> s = FastStorage() >>> s.a = 1 >>> s.a 1 >>> s['a'] 1 >>> s.b >>> s['b'] >>> s['b']=2 >>> s['b'] 2 >>> s.b 2 >>> isinstance(s,dict) True >>> dict(s) {'a': 1, 'b': 2} >>> dict(FastStorage(s)) {'a': 1, 'b': 2} >>> import pickle >>> s = pickle.loads(pickle.dumps(s)) >>> dict(s) {'a': 1, 'b': 2} >>> del s.b >>> del s.a >>> s.a >>> s.b >>> s['a'] >>> s['b'] """ def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self def __getattr__(self, key): return getattr(self, key) if key in self else None def __getitem__(self, key): return dict.get(self, key, None) def copy(self): self.__dict__ = {} s = FastStorage(self) self.__dict__ = self return s def __repr__(self): return '<Storage %s>' % dict.__repr__(self) def __getstate__(self): return dict(self) def __setstate__(self, sdict): dict.__init__(self, sdict) self.__dict__ = self def update(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self class List(list): """ Like a regular python list but a[i] if i is out of bounds returns None instead of `IndexOutOfBounds` """ def __call__(self, i, default=DEFAULT, cast=None, otherwise=None): """Allows to use a special syntax for fast-check of `request.args()` validity Args: i: index default: use this value if arg not found cast: type cast otherwise: can be: - None: results in a 404 - str: redirect to this address - callable: calls the function (nothing is passed) Example: You can use:: request.args(0,default=0,cast=int,otherwise='http://error_url') request.args(0,default=0,cast=int,otherwise=lambda:...) """ n = len(self) if 0 <= i < n or -n <= i < 0: value = self[i] elif default is DEFAULT: value = None else: value, cast = default, False if cast: try: value = cast(value) except (ValueError, TypeError): from http import HTTP, redirect if otherwise is None: raise HTTP(404) elif isinstance(otherwise, str): redirect(otherwise) elif callable(otherwise): return otherwise() else: raise RuntimeError("invalid otherwise") return value if __name__ == '__main__': import doctest doctest.testmod()
shashisp/blumix-webpy
app/gluon/storage.py
Python
mit
8,573
/* <one line to give the program's name and a brief idea of what it does.> Copyright (C) 2012 <copyright holder> <email> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "bot.h" #include "../communication/boost/concept_check.hpp" Bot::Bot() { position.x = 20; position.y = 20; color = al_map_rgb(255, 0, 0); AI = true; init(); } Bot::Bot(slm::vec2 p):position(p) { color = al_map_rgb(255, 0, 0); AI = true; init(); } Bot::Bot(slm::vec2 p, ALLEGRO_COLOR c):position(p),color(c) { AI = true; init(); } void Bot::init() { currentPath = -1; orientation = 0; velocity = slm::vec2(0,0); rotation = 0; sterring = new Sterring(slm::vec2(0,0), 0); health = 100; ammo = 50; dead = false; } Bot::~Bot() {} void Bot::render() { ostringstream ss; if(health > 0) { ss << "h:" << health << " a:" << ammo; al_draw_filled_circle(position.x, position.y, 20, color); al_draw_filled_circle(nearestNode->position.x, nearestNode->position.y, 5, al_map_rgb(160, 160, 0)); al_draw_text(font, al_map_rgb(0, 0, 0), position.x, position.y - 30, ALLEGRO_ALIGN_CENTRE, ss.str().c_str()); Pathfinding::getInstance().drawPath(currentPath); } else { ss << "DEAD"; al_draw_filled_circle(position.x, position.y, 20, al_map_rgb(150,150,150)); al_draw_text(font, al_map_rgb(0, 0, 0), position.x, position.y - 30, ALLEGRO_ALIGN_CENTRE, ss.str().c_str()); } } void Bot::setMap(AIMap* m) { map = m; } void Bot::setPosition(slm::vec2 p) { position = p; } void Bot::setSterring(Sterring *s) { sterring = s; } void Bot::findNearestNode() { if(dead) return; float minDist = map->size.x*map->size.y; for(int i = 0; i < map->graphNodes.size(); i++) { float dist = slm::distance(position, map->graphNodes[i]->position); if(dist < minDist) { minDist = dist; nearestNode = map->graphNodes[i]; } } } void Bot::getSterring() { sterring = Pathfinding::getInstance().getSterring(position, currentPath); } void Bot::updatePosition(float time) { if(dead) return; if(AI) getSterring(); position += velocity * time; orientation += rotation * time; velocity += sterring->linear * time; // let player be faster if(AI) velocity = slm::clamp(velocity, slm::vec2(-MAX_SPEED,-MAX_SPEED), slm::vec2(MAX_SPEED,MAX_SPEED)); else velocity = slm::clamp(velocity, slm::vec2(-2*MAX_SPEED,-2*MAX_SPEED), slm::vec2(2*MAX_SPEED,2*MAX_SPEED)); rotation += sterring->angular * time; if(slm::length(sterring->linear) == 0) { velocity *= (1.0 - FRICTION*time); if(slm::length(velocity) < (MAX_SPEED*0.5)) velocity = slm::vec2(0,0); } updateNearestNode(); } void Bot::updateNearestNode() { float minDist = slm::distance(position, nearestNode->position); if(minDist > 2*map->distance) { findNearestNode(); return; } AIMap_Node* newNearest = nearestNode; for(int i = 0; i < nearestNode->neighbours.size(); i++) { float tmpDist = slm::distance(position, nearestNode->neighbours[i]->position); if(tmpDist < minDist) { minDist = tmpDist; newNearest = nearestNode->neighbours[i]; } } nearestNode = newNearest; } AIMap_Node* Bot::getNearestNode() { return nearestNode; } void Bot::setFollow(Followable* f) { followed = f; }
fridek/uj-gamedev-ai-project
bot/bot.cpp
C++
mit
3,941
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Servidor.Control { internal class CifradoAES { internal string cifrar(string transaccionSerializada) { return transaccionSerializada; } internal string descifrar(string respuesta) { return respuesta; } } }
IsidroE/CrypProject
Proyecto/Servidor/Servidor/Control/CifradoAES.cs
C#
mit
421
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC /* remove Window tab on Mac */ ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow)); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton())); /* setup/change UI elements when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* update the display unit, to not use the default ("BTC") */ updateDisplayUnit(); /* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */ connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang())); /* disable apply button after settings are loaded as there is nothing to save */ disableApplyButton(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); /* Window */ #ifndef Q_OS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); } void OptionsDialog::enableApplyButton() { ui->applyButton->setEnabled(true); } void OptionsDialog::disableApplyButton() { ui->applyButton->setEnabled(false); } void OptionsDialog::enableSaveButtons() { /* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */ if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_resetButton_clicked() { if(model) { // confirmation dialog QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"), tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if(btnRetVal == QMessageBox::Cancel) return; disableApplyButton(); /* disable restart warning messages display */ fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true; /* reset all options and save the default values (QSettings) */ model->Reset(); mapper->toFirst(); mapper->submit(); /* re-enable restart warning messages display */ fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false; } } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); disableApplyButton(); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting GulfCoin."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting GulfCoin."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { /* Update transactionFee with the current unit */ ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fProxyIpValid = fState; if(fProxyIpValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fProxyIpValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(event->type() == QEvent::FocusOut) { if(object == ui->proxyIp) { CService addr; /* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */ emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)); } } return QDialog::eventFilter(object, event); }
coingulf/gulfcoin
src/qt/optionsdialog.cpp
C++
mit
8,954
#!/usr/bin/env python from ..debugging import bacpypes_debugging, ModuleLogger from ..capability import Capability from ..basetypes import ErrorType, PropertyIdentifier from ..primitivedata import Atomic, Null, Unsigned from ..constructeddata import Any, Array, ArrayOf, List from ..apdu import \ SimpleAckPDU, ReadPropertyACK, ReadPropertyMultipleACK, \ ReadAccessResult, ReadAccessResultElement, ReadAccessResultElementChoice from ..errors import ExecutionError from ..object import PropertyError # some debugging _debug = 0 _log = ModuleLogger(globals()) # handy reference ArrayOfPropertyIdentifier = ArrayOf(PropertyIdentifier) # # ReadProperty and WriteProperty Services # @bacpypes_debugging class ReadWritePropertyServices(Capability): def __init__(self): if _debug: ReadWritePropertyServices._debug("__init__") Capability.__init__(self) def do_ReadPropertyRequest(self, apdu): """Return the value of some property of one of our objects.""" if _debug: ReadWritePropertyServices._debug("do_ReadPropertyRequest %r", apdu) # extract the object identifier objId = apdu.objectIdentifier # check for wildcard if (objId == ('device', 4194303)) and self.localDevice is not None: if _debug: ReadWritePropertyServices._debug(" - wildcard device identifier") objId = self.localDevice.objectIdentifier # get the object obj = self.get_object_id(objId) if _debug: ReadWritePropertyServices._debug(" - object: %r", obj) if not obj: raise ExecutionError(errorClass='object', errorCode='unknownObject') try: # get the datatype datatype = obj.get_datatype(apdu.propertyIdentifier) if _debug: ReadWritePropertyServices._debug(" - datatype: %r", datatype) # get the value value = obj.ReadProperty(apdu.propertyIdentifier, apdu.propertyArrayIndex) if _debug: ReadWritePropertyServices._debug(" - value: %r", value) if value is None: raise PropertyError(apdu.propertyIdentifier) # change atomic values into something encodeable if issubclass(datatype, Atomic) or (issubclass(datatype, (Array, List)) and isinstance(value, list)): value = datatype(value) elif issubclass(datatype, Array) and (apdu.propertyArrayIndex is not None): if apdu.propertyArrayIndex == 0: value = Unsigned(value) elif issubclass(datatype.subtype, Atomic): value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting {0} and got {1}" \ .format(datatype.subtype.__name__, type(value).__name__)) elif issubclass(datatype, List): value = datatype(value) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting {0} and got {1}" \ .format(datatype.__name__, type(value).__name__)) if _debug: ReadWritePropertyServices._debug(" - encodeable value: %r", value) # this is a ReadProperty ack resp = ReadPropertyACK(context=apdu) resp.objectIdentifier = objId resp.propertyIdentifier = apdu.propertyIdentifier resp.propertyArrayIndex = apdu.propertyArrayIndex # save the result in the property value resp.propertyValue = Any() resp.propertyValue.cast_in(value) if _debug: ReadWritePropertyServices._debug(" - resp: %r", resp) except PropertyError: raise ExecutionError(errorClass='property', errorCode='unknownProperty') # return the result self.response(resp) def do_WritePropertyRequest(self, apdu): """Change the value of some property of one of our objects.""" if _debug: ReadWritePropertyServices._debug("do_WritePropertyRequest %r", apdu) # get the object obj = self.get_object_id(apdu.objectIdentifier) if _debug: ReadWritePropertyServices._debug(" - object: %r", obj) if not obj: raise ExecutionError(errorClass='object', errorCode='unknownObject') try: # check if the property exists if obj.ReadProperty(apdu.propertyIdentifier, apdu.propertyArrayIndex) is None: raise PropertyError(apdu.propertyIdentifier) # get the datatype, special case for null if apdu.propertyValue.is_application_class_null(): datatype = Null else: datatype = obj.get_datatype(apdu.propertyIdentifier) if _debug: ReadWritePropertyServices._debug(" - datatype: %r", datatype) # special case for array parts, others are managed by cast_out if issubclass(datatype, Array) and (apdu.propertyArrayIndex is not None): if apdu.propertyArrayIndex == 0: value = apdu.propertyValue.cast_out(Unsigned) else: value = apdu.propertyValue.cast_out(datatype.subtype) else: value = apdu.propertyValue.cast_out(datatype) if _debug: ReadWritePropertyServices._debug(" - value: %r", value) # change the value value = obj.WriteProperty(apdu.propertyIdentifier, value, apdu.propertyArrayIndex, apdu.priority) # success resp = SimpleAckPDU(context=apdu) if _debug: ReadWritePropertyServices._debug(" - resp: %r", resp) except PropertyError: raise ExecutionError(errorClass='property', errorCode='unknownProperty') # return the result self.response(resp) # # read_property_to_any # @bacpypes_debugging def read_property_to_any(obj, propertyIdentifier, propertyArrayIndex=None): """Read the specified property of the object, with the optional array index, and cast the result into an Any object.""" if _debug: read_property_to_any._debug("read_property_to_any %s %r %r", obj, propertyIdentifier, propertyArrayIndex) # get the datatype datatype = obj.get_datatype(propertyIdentifier) if _debug: read_property_to_any._debug(" - datatype: %r", datatype) if datatype is None: raise ExecutionError(errorClass='property', errorCode='datatypeNotSupported') # get the value value = obj.ReadProperty(propertyIdentifier, propertyArrayIndex) if _debug: read_property_to_any._debug(" - value: %r", value) if value is None: raise ExecutionError(errorClass='property', errorCode='unknownProperty') # change atomic values into something encodeable if issubclass(datatype, Atomic) or (issubclass(datatype, (Array, List)) and isinstance(value, list)): value = datatype(value) elif issubclass(datatype, Array) and (propertyArrayIndex is not None): if propertyArrayIndex == 0: value = Unsigned(value) elif issubclass(datatype.subtype, Atomic): value = datatype.subtype(value) elif not isinstance(value, datatype.subtype): raise TypeError("invalid result datatype, expecting %s and got %s" \ % (datatype.subtype.__name__, type(value).__name__)) elif not isinstance(value, datatype): raise TypeError("invalid result datatype, expecting %s and got %s" \ % (datatype.__name__, type(value).__name__)) if _debug: read_property_to_any._debug(" - encodeable value: %r", value) # encode the value result = Any() result.cast_in(value) if _debug: read_property_to_any._debug(" - result: %r", result) # return the object return result # # read_property_to_result_element # @bacpypes_debugging def read_property_to_result_element(obj, propertyIdentifier, propertyArrayIndex=None): """Read the specified property of the object, with the optional array index, and cast the result into an Any object.""" if _debug: read_property_to_result_element._debug("read_property_to_result_element %s %r %r", obj, propertyIdentifier, propertyArrayIndex) # save the result in the property value read_result = ReadAccessResultElementChoice() try: if not obj: raise ExecutionError(errorClass='object', errorCode='unknownObject') read_result.propertyValue = read_property_to_any(obj, propertyIdentifier, propertyArrayIndex) if _debug: read_property_to_result_element._debug(" - success") except PropertyError as error: if _debug: read_property_to_result_element._debug(" - error: %r", error) read_result.propertyAccessError = ErrorType(errorClass='property', errorCode='unknownProperty') except ExecutionError as error: if _debug: read_property_to_result_element._debug(" - error: %r", error) read_result.propertyAccessError = ErrorType(errorClass=error.errorClass, errorCode=error.errorCode) # make an element for this value read_access_result_element = ReadAccessResultElement( propertyIdentifier=propertyIdentifier, propertyArrayIndex=propertyArrayIndex, readResult=read_result, ) if _debug: read_property_to_result_element._debug(" - read_access_result_element: %r", read_access_result_element) # fini return read_access_result_element # # ReadWritePropertyMultipleServices # @bacpypes_debugging class ReadWritePropertyMultipleServices(Capability): def __init__(self): if _debug: ReadWritePropertyMultipleServices._debug("__init__") Capability.__init__(self) def do_ReadPropertyMultipleRequest(self, apdu): """Respond to a ReadPropertyMultiple Request.""" if _debug: ReadWritePropertyMultipleServices._debug("do_ReadPropertyMultipleRequest %r", apdu) # response is a list of read access results (or an error) resp = None read_access_result_list = [] # loop through the request for read_access_spec in apdu.listOfReadAccessSpecs: # get the object identifier objectIdentifier = read_access_spec.objectIdentifier if _debug: ReadWritePropertyMultipleServices._debug(" - objectIdentifier: %r", objectIdentifier) # check for wildcard if (objectIdentifier == ('device', 4194303)) and self.localDevice is not None: if _debug: ReadWritePropertyMultipleServices._debug(" - wildcard device identifier") objectIdentifier = self.localDevice.objectIdentifier # get the object obj = self.get_object_id(objectIdentifier) if _debug: ReadWritePropertyMultipleServices._debug(" - object: %r", obj) # build a list of result elements read_access_result_element_list = [] # loop through the property references for prop_reference in read_access_spec.listOfPropertyReferences: # get the property identifier propertyIdentifier = prop_reference.propertyIdentifier if _debug: ReadWritePropertyMultipleServices._debug(" - propertyIdentifier: %r", propertyIdentifier) # get the array index (optional) propertyArrayIndex = prop_reference.propertyArrayIndex if _debug: ReadWritePropertyMultipleServices._debug(" - propertyArrayIndex: %r", propertyArrayIndex) # check for special property identifiers if propertyIdentifier in ('all', 'required', 'optional'): if not obj: # build a property access error read_result = ReadAccessResultElementChoice() read_result.propertyAccessError = ErrorType(errorClass='object', errorCode='unknownObject') # make an element for this error read_access_result_element = ReadAccessResultElement( propertyIdentifier=propertyIdentifier, propertyArrayIndex=propertyArrayIndex, readResult=read_result, ) # add it to the list read_access_result_element_list.append(read_access_result_element) else: for propId, prop in obj._properties.items(): if _debug: ReadWritePropertyMultipleServices._debug(" - checking: %r %r", propId, prop.optional) # skip propertyList for ReadPropertyMultiple if (propId == 'propertyList'): if _debug: ReadWritePropertyMultipleServices._debug(" - ignore propertyList") continue if (propertyIdentifier == 'all'): pass elif (propertyIdentifier == 'required') and (prop.optional): if _debug: ReadWritePropertyMultipleServices._debug(" - not a required property") continue elif (propertyIdentifier == 'optional') and (not prop.optional): if _debug: ReadWritePropertyMultipleServices._debug(" - not an optional property") continue # read the specific property read_access_result_element = read_property_to_result_element(obj, propId, propertyArrayIndex) # check for undefined property if read_access_result_element.readResult.propertyAccessError \ and read_access_result_element.readResult.propertyAccessError.errorCode == 'unknownProperty': continue # add it to the list read_access_result_element_list.append(read_access_result_element) else: # read the specific property read_access_result_element = read_property_to_result_element(obj, propertyIdentifier, propertyArrayIndex) # add it to the list read_access_result_element_list.append(read_access_result_element) # build a read access result read_access_result = ReadAccessResult( objectIdentifier=objectIdentifier, listOfResults=read_access_result_element_list ) if _debug: ReadWritePropertyMultipleServices._debug(" - read_access_result: %r", read_access_result) # add it to the list read_access_result_list.append(read_access_result) # this is a ReadPropertyMultiple ack if not resp: resp = ReadPropertyMultipleACK(context=apdu) resp.listOfReadAccessResults = read_access_result_list if _debug: ReadWritePropertyMultipleServices._debug(" - resp: %r", resp) # return the result self.response(resp) # def do_WritePropertyMultipleRequest(self, apdu): # """Respond to a WritePropertyMultiple Request.""" # if _debug: ReadWritePropertyMultipleServices._debug("do_ReadPropertyMultipleRequest %r", apdu) # # raise NotImplementedError()
JoelBender/bacpypes
py27/bacpypes/service/object.py
Python
mit
15,660
#include "FeatureIterator.h" #include "Random.h" #include <functional> namespace dungeon { //////////////////////////////////////////////////////////////////////////////// // ADJUSTERS //////////////////////////////////////////////////////////////////////////////// AForward::AForward(const Feature& feature) : mStart(randomRange(0,feature.height() - 1)), mOffset(feature.offset(mStart)) { } AMirror::AMirror(const Feature& feature) : mStart(randomRange(0,feature.height() - 1)), mOffset(feature.offset(feature.height() - 1 - mStart)) { } ATranspose::ATranspose(const Feature& feature) : mStart(randomRange(0,feature.width(0) - 1)), mOffset(-mStart - feature.offset(0)) { } AMirrorTranspose::AMirrorTranspose(const Feature& feature) : mStart(randomRange(0,feature.width(feature.height() - 1) - 1)), mOffset(-mStart - feature.offset(feature.height() - 1)) { } //////////////////////////////////////////////////////////////////////////////// // ITERATORS //////////////////////////////////////////////////////////////////////////////// IForward::IForward(int height) : mHeight(height), mCurrent(0) { } int IForward::begin() const { mCurrent = 0; return mCurrent; } int IForward::next() { ++mCurrent; return mCurrent; } int IForward::end() const { return mHeight; } IBackward::IBackward(int height) : mHeight(height), mCurrent(0) { } int IBackward::begin() const { mCurrent = mHeight - 1; return mCurrent; } int IBackward::next() { --mCurrent; return mCurrent; } int IBackward::end() const { return -1; } }
DeonPoncini/libdungeon
src/FeatureIterator.cpp
C++
mit
1,608
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var React = require("react"); var Utilities_1 = require("../../Utilities"); var stylesImport = require("./Check.scss"); var styles = stylesImport; var Check = (function (_super) { __extends(Check, _super); function Check() { return _super !== null && _super.apply(this, arguments) || this; } Check.prototype.shouldComponentUpdate = function (newProps) { return this.props.isChecked !== newProps.isChecked || this.props.checked !== newProps.checked; }; Check.prototype.render = function () { var _a = this.props, isChecked = _a.isChecked, checked = _a.checked; isChecked = isChecked || checked; return (React.createElement("div", { className: Utilities_1.css('ms-Check', styles.root, (_b = {}, _b['is-checked ' + styles.rootIsChecked] = isChecked, _b)) }, React.createElement("div", { className: Utilities_1.css('ms-Icon ms-Check-background', styles.background) }), React.createElement("i", { className: Utilities_1.css('ms-Check-check ms-Icon ms-Icon--CheckMark', styles.check) }))); var _b; }; return Check; }(Utilities_1.BaseComponent)); Check.defaultProps = { isChecked: false }; exports.Check = Check; //# sourceMappingURL=Check.js.map
SpatialMap/SpatialMapDev
node_modules/office-ui-fabric-react/lib/components/Check/Check.js
JavaScript
mit
1,851
# Logic for creating a security key during password reset module Authenticatable class SecurityKey < ActiveRecord::Base # Uses the hashable concern include Hashable # Requires user id and an expiration_date to be present validates :user_id,:expiration_date, presence: true # ActiveRecord association to the user who create the security key belongs_to :user # Runs the method to create security key before saving the record before_create :set_key # Assigns security using method from hashable concern def set_key self.key = hash_from_salt end # Check to see if password is before date of expiration. def not_expired?(date) date <= self.expiration_date end end end
vmcilwain/authenticatable
app/models/authenticatable/security_key.rb
Ruby
mit
764
var Buffer = require('buffer').Buffer, Jpeg = require('jpeg').Jpeg; function randomColorComponent() { return Math.floor(Math.random() * 256); } /** * Creates a random image */ module.exports = function(width, height, callback) { var buffer = new Buffer(width * height * 3); for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { var pixelStart = x * width * 3 + y * 3; buffer[pixelStart + 0] = randomColorComponent(); buffer[pixelStart + 1] = randomColorComponent(); buffer[pixelStart + 2] = randomColorComponent(); } } var image = new Jpeg(buffer, width, height); image.encode(function(result) { callback(null, result); }); };
davidpadbury/random-image-generator
index.js
JavaScript
mit
754
import { html } from 'lit'; import { Story, Meta } from '@storybook/web-components'; export default { title: 'Addons / Toolbars', } as Meta; const getCaptionForLocale = (locale: string) => { switch (locale) { case 'es': return 'Hola!'; case 'fr': return 'Bonjour !'; case 'zh': return '你好!'; case 'kr': return '안녕하세요!'; case 'en': default: return 'Hello'; } }; export const Locale: Story = (args, { globals: { locale } }) => { return html` <div>Your locale is '${locale}', so I say: ${getCaptionForLocale(locale)}</div> `; };
storybooks/storybook
examples/web-components-kitchen-sink/src/stories/addons/toolbars/addon-toolbars.stories.ts
TypeScript
mit
605
# Copyright (C) 2012-2020 Ben Kurtovic <ben.kurtovic@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. """ Contains data about certain markup, like HTML tags and external links. When updating this file, please also update the the C tokenizer version: - mwparserfromhell/parser/ctokenizer/definitions.c - mwparserfromhell/parser/ctokenizer/definitions.h """ __all__ = [ "get_html_tag", "is_parsable", "is_visible", "is_single", "is_single_only", "is_scheme", ] URI_SCHEMES = { # [wikimedia/mediawiki.git]/includes/DefaultSettings.php @ 5c660de5d0 "bitcoin": False, "ftp": True, "ftps": True, "geo": False, "git": True, "gopher": True, "http": True, "https": True, "irc": True, "ircs": True, "magnet": False, "mailto": False, "mms": True, "news": False, "nntp": True, "redis": True, "sftp": True, "sip": False, "sips": False, "sms": False, "ssh": True, "svn": True, "tel": False, "telnet": True, "urn": False, "worldwind": True, "xmpp": False, } PARSER_BLACKLIST = [ # https://www.mediawiki.org/wiki/Parser_extension_tags @ 2020-12-21 "categorytree", "ce", "chem", "gallery", "graph", "hiero", "imagemap", "inputbox", "math", "nowiki", "pre", "score", "section", "source", "syntaxhighlight", "templatedata", "timeline", ] INVISIBLE_TAGS = [ # https://www.mediawiki.org/wiki/Parser_extension_tags @ 2020-12-21 "categorytree", "gallery", "graph", "imagemap", "inputbox", "math", "score", "section", "templatedata", "timeline", ] # [wikimedia/mediawiki.git]/includes/parser/Sanitizer.php @ 95e17ee645 SINGLE_ONLY = ["br", "wbr", "hr", "meta", "link", "img"] SINGLE = SINGLE_ONLY + ["li", "dt", "dd", "th", "td", "tr"] MARKUP_TO_HTML = { "#": "li", "*": "li", ";": "dt", ":": "dd", } def get_html_tag(markup): """Return the HTML tag associated with the given wiki-markup.""" return MARKUP_TO_HTML[markup] def is_parsable(tag): """Return if the given *tag*'s contents should be passed to the parser.""" return tag.lower() not in PARSER_BLACKLIST def is_visible(tag): """Return whether or not the given *tag* contains visible text.""" return tag.lower() not in INVISIBLE_TAGS def is_single(tag): """Return whether or not the given *tag* can exist without a close tag.""" return tag.lower() in SINGLE def is_single_only(tag): """Return whether or not the given *tag* must exist without a close tag.""" return tag.lower() in SINGLE_ONLY def is_scheme(scheme, slashes=True): """Return whether *scheme* is valid for external links.""" scheme = scheme.lower() if slashes: return scheme in URI_SCHEMES return scheme in URI_SCHEMES and not URI_SCHEMES[scheme]
earwig/mwparserfromhell
src/mwparserfromhell/definitions.py
Python
mit
3,915
// Copyright (c) SimControl e.U. - Wilhelm Medetz. See LICENSE.txt in the project root for more information. using System; // TODO CR namespace SimControl.Reactive { /// <summary>Exception trigger.</summary> public class ExceptionTrigger: Trigger { /// <summary>Constructor.</summary> /// <param name="exception">The exception.</param> public ExceptionTrigger(Exception exception) { // Contract.Requires(exception != null); exceptionType = exception.InnerException.GetType(); this.exception = exception; } /// <summary>Constructor.</summary> /// <param name="exceptionType">Type of the exception.</param> protected ExceptionTrigger(Type exceptionType) { // Contract.Requires(exceptionType != null && (exceptionType == typeof(Exception) || exceptionType.IsSubclassOf(typeof(Exception)))); this.exceptionType = exceptionType; } internal override bool Matches(Trigger trigger) => trigger is ExceptionTrigger other && (exceptionType == other.exceptionType || other.exceptionType.IsSubclassOf(exceptionType)); internal readonly Exception exception; internal readonly Type exceptionType; } /// <summary>Exception trigger.</summary> /// <typeparam name="T"></typeparam> /// <seealso cref="Trigger"/> public sealed class ExceptionTrigger<T>: ExceptionTrigger, IGenericTrigger<T> where T : Exception { /// <summary>Default constructor.</summary> public ExceptionTrigger() : base(typeof(T)) { } } }
SimControl/SimControl.Reactive
SimControl.Reactive/ExceptionTrigger.cs
C#
mit
1,633
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.processor.block; import static org.spongepowered.common.data.DataTransactionBuilder.fail; import com.google.common.base.Optional; import net.minecraft.block.state.IBlockState; import net.minecraft.util.BlockPos; import net.minecraft.world.World; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.data.DataHolder; import org.spongepowered.api.data.DataPriority; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.DataView; import org.spongepowered.api.data.manipulator.block.DirectionalData; import org.spongepowered.api.service.persistence.InvalidDataException; import org.spongepowered.common.data.DataTransactionBuilder; import org.spongepowered.common.data.SpongeBlockProcessor; import org.spongepowered.common.data.SpongeDataProcessor; import org.spongepowered.common.data.manipulator.block.SpongeDirectionalData; import org.spongepowered.common.interfaces.block.IMixinBlockDirectional; public class SpongeDirectionalProcessor implements SpongeDataProcessor<DirectionalData>, SpongeBlockProcessor<DirectionalData> { @Override public Optional<DirectionalData> fillData(DataHolder dataHolder, DirectionalData manipulator, DataPriority priority) { return Optional.absent(); } @Override public DataTransactionResult setData(DataHolder dataHolder, DirectionalData manipulator, DataPriority priority) { return DataTransactionBuilder.successNoData(); } @Override public boolean remove(DataHolder dataHolder) { return false; } @Override public Optional<DirectionalData> build(DataView container) throws InvalidDataException { return Optional.absent(); } @Override public DirectionalData create() { return new SpongeDirectionalData(); } @Override public Optional<DirectionalData> createFrom(DataHolder dataHolder) { return Optional.absent(); } @Override public Optional<DirectionalData> fromBlockPos(final World world, final BlockPos blockPos) { IBlockState blockState = world.getBlockState(blockPos); if (blockState.getBlock() instanceof IMixinBlockDirectional) { return Optional.of(((IMixinBlockDirectional) blockState.getBlock()).getDirectionalData(blockState)); } return Optional.absent(); } @Override public DataTransactionResult setData(World world, BlockPos blockPos, DirectionalData manipulator, DataPriority priority) { IBlockState blockState = world.getBlockState(blockPos); if (blockState.getBlock() instanceof IMixinBlockDirectional) { return ((IMixinBlockDirectional) blockState.getBlock()).setDirectionalData(manipulator, world, blockPos, priority); } return fail(manipulator); } @Override public boolean remove(World world, BlockPos blockPos) { IBlockState blockState = world.getBlockState(blockPos); if (blockState.getBlock() instanceof IMixinBlockDirectional) { // ((IMixinBlockDirectional) blockState.getBlock()).resetDirectionData(blockState); return true; } return false; } @Override public Optional<BlockState> removeFrom(IBlockState blockState) { return Optional.absent(); } @Override public Optional<DirectionalData> createFrom(IBlockState blockState) { if (blockState.getBlock() instanceof IMixinBlockDirectional) { ((IMixinBlockDirectional) blockState.getBlock()).getDirectionalData(blockState); } return Optional.absent(); } @Override public Optional<DirectionalData> getFrom(DataHolder dataHolder) { return Optional.absent(); } }
gabizou/SpongeCommon
src/main/java/org/spongepowered/common/data/processor/block/SpongeDirectionalProcessor.java
Java
mit
5,006
<?php /** * CodeIgniter * * An open source application development framework for PHP 5.2.4 or newer * * This content is released under the MIT License (MIT) * * Copyright (c) 2014, British Columbia Institute of Technology * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @package CodeIgniter * @author EllisLab Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (http://ellislab.com/) * @copyright Copyright (c) 2014, British Columbia Institute of Technology (http://bcit.ca/) * @license http://opensource.org/licenses/MIT MIT License * @link http://codeigniter.com * @since Version 1.0.0 * @filesource */ defined('BASEPATH') OR exit('No direct script access allowed'); $lang['date_year'] = 'Год'; $lang['date_years'] = 'Лет'; $lang['date_month'] = 'Месяц'; $lang['date_months'] = 'Месяцев'; $lang['date_week'] = 'Неделя'; $lang['date_weeks'] = 'Недель'; $lang['date_day'] = 'День'; $lang['date_days'] = 'Дней'; $lang['date_hour'] = 'Час'; $lang['date_hours'] = 'Часов'; $lang['date_minute'] = 'Минута'; $lang['date_minutes'] = 'Минут'; $lang['date_second'] = 'Секунда'; $lang['date_seconds'] = 'Секунд'; $lang['UM12'] = '(UTC -12:00) Бейкер/Хауленд'; $lang['UM11'] = '(UTC -11:00) Ниуэ'; $lang['UM10'] = '(UTC -10:00) Гавайи'; $lang['UM95'] = '(UTC -9:30) Маркизские острова'; $lang['UM9'] = '(UTC -9:00) Аляска'; $lang['UM8'] = '(UTC -8:00) Североамериканское и тихоокеанское время (США и Канада)'; $lang['UM7'] = '(UTC -7:00) Горное время (США и Канада), Мексика (Чиуауа, Ла-Пас, Мацатлан)'; $lang['UM6'] = '(UTC -6:00) Центральное время (США и Канада), Центральноамериканское время, Мексика (Гвадалахара, Мехико, Монтеррей'; $lang['UM5'] = '(UTC -5:00) Североамериканское восточное время (США и Канада), Южноамериканское тихоокеанское время (Богота, Лима, Кито)'; $lang['UM45'] = '(UTC -4:30) Каракас'; $lang['UM4'] = '(UTC -4:00) Атлантическое время (Канада), Южноамериканское тихоокеанское время, Ла-Пас, Сантьяго)'; $lang['UM35'] = '(UTC -3:30) Ньюфаундленд'; $lang['UM3'] = '(UTC -3:00) Южноамериканское восточное время (Аргентина, Бразилия, Буэнос-Айрес, Джорджтаун), Гренландия'; $lang['UM2'] = '(UTC -2:00) Среднеатлантическое время'; $lang['UM1'] = '(UTC -1:00) Азорские острова, Кабо-Верде'; $lang['UTC'] = '(UTC) Западноевропейское время (Дублин, Эдинбург, Лиссабон, Лондон, Касабланка, Монровия)'; $lang['UP1'] = '(UTC +1:00) Центральноевропейское время, Западное центральноафриканское время'; $lang['UP2'] = '(UTC +2:00) Восточноевропейское время, Египет, Израиль, Ливан, Ливия, Турция, ЮАР'; $lang['UP3'] = '(UTC +3:00) Восточноафриканское время, Ирак, Кувейт, Саудовская Аравия'; $lang['UP35'] = '(UTC +3:30) Тегеранское время'; $lang['UP4'] = '(UTC +4:00) Московское время, Самара, ОАЭ, Оман, Азербайджан, Армения, Грузия'; $lang['UP45'] = '(UTC +4:30) Афганистан'; $lang['UP5'] = '(UTC +5:00) Екатеринбург, Западноазиатское время (Исламабад, Карачи, Узбекистан)'; $lang['UP55'] = '(UTC +5:30) Индия, Шри-Ланка'; $lang['UP575'] = '(UTC +5:45) Непал'; $lang['UP6'] = '(UTC +6:00) Омское время, Новосибирск, Кемерово, Центральноазиатское время (Бангладеш, Казахстан, Киргизия)'; $lang['UP65'] = '(UTC +6:30) Мьянма, Кокосовые острова'; $lang['UP7'] = '(UTC +7:00) Красноярское время, Юго-Восточная Азия (Бангкок, Джакарта, Ханой)'; $lang['UP8'] = '(UTC +8:00) Иркутское время, Улан-Батор, Куала-Лумпур, Гонконг, Китай, Сингапур, Тайвань, западноавстралийское время (Перт)'; $lang['UP875'] = '(UTC +8:45) Западноавстралийское время'; $lang['UP9'] = '(UTC +9:00) Якутское время, Корея, Япония'; $lang['UP95'] = '(UTC +9:30) Центральноавстралийское время'; $lang['UP10'] = '(UTC +10:00) Владивостокское время, Восточноавстралийское время'; $lang['UP105'] = '(UTC +10:30) Остров Лорд-Хау'; $lang['UP11'] = '(UTC +11:00) Магаданское время, Центрально-тихоокеанское время (Соломоновы Острова, Новая Каледония)'; $lang['UP115'] = '(UTC +11:30) Остров Норфолк'; $lang['UP12'] = '(UTC +12:00) Маршалловы Острова, Фиджи, Новая Зеландия'; $lang['UP1275'] = '(UTC +12:45) Острова Чатем'; $lang['UP13'] = '(UTC +13:00) Самоа, Тонга'; $lang['UP14'] = '(UTC +14:00) Острова Лайн (Кирибати)'; /* End of file date_lang.php */ /* Location: ./application/language/russian/date_lang.php */
grcasanova/Codeigniter-Bundle
CodeIgniter/application/language/russian/date_lang.php
PHP
mit
6,785
package com.dreamdevs.sunshine.fragment; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView; import com.dreamdevs.sunshine.R; import com.dreamdevs.sunshine.adapter.ForecastAdapter; import com.dreamdevs.sunshine.data.WeatherContract; import com.dreamdevs.sunshine.sync.SunshineSyncAdapter; import com.dreamdevs.sunshine.util.Utility; public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>, SharedPreferences.OnSharedPreferenceChangeListener { private static final String LOG_TAG = ForecastFragment.class.getSimpleName(); private static final int FORECAST_LOADER = 0; // For the forecast view we're showing only a small subset of the stored data // Specify the columns we need private static final String[] FORECAST_COLUMNS = { // In this case the id needs to be fully qualified with a table name, since // the content provider joins the location & weather tables in the background // (both have an _id column) // On the one hand, that's annoying. On the other, you can search the weather table // using the location set by the user, which is only in the Location table. // So the convenience is worth it. WeatherContract.WeatherEntry.TABLE_NAME + "." + WeatherContract.WeatherEntry._ID, WeatherContract.WeatherEntry.COLUMN_DATE, WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, WeatherContract.LocationEntry.COLUMN_COORD_LAT, WeatherContract.LocationEntry.COLUMN_COORD_LONG }; // These indices are tied to FORECAST_COLUMNS. If FORECAST_COLUMNS changes, these // must change. public static final int COL_WEATHER_ID = 0; public static final int COL_WEATHER_DATE = 1; public static final int COL_WEATHER_DESC = 2; public static final int COL_WEATHER_MAX_TEMP = 3; public static final int COL_WEATHER_MIN_TEMP = 4; public static final int COL_LOCATION_SETTING = 5; public static final int COL_WEATHER_CONDITION_ID = 6; public static final int COL_COORD_LAT = 7; public static final int COL_COORD_LONG = 8; private ForecastAdapter mForecastAdapter; private int mPosition = ListView.INVALID_POSITION; private static final String SELECTED_KEY = "selected_position"; private static final int SET_LIST_ITEM_SELECTED = 100; private ListView mListView; private boolean mUseTodayLayout; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if(msg.what == SET_LIST_ITEM_SELECTED) { setListItemSelected(); } } }; public ForecastFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Add this line in order for this fragment to handle menu events. setHasOptionsMenu(true); } @Override public void onResume() { PreferenceManager.getDefaultSharedPreferences(getActivity()) .registerOnSharedPreferenceChangeListener(this); super.onResume(); } @Override public void onPause() { PreferenceManager.getDefaultSharedPreferences(getActivity()) .unregisterOnSharedPreferenceChangeListener(this); super.onPause(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.forecastfragment, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_map) { openPreferredLocationInMap(); return true; } return super.onOptionsItemSelected(item); } private void updateWeather() { SunshineSyncAdapter.syncImmediately(getActivity()); } private void openPreferredLocationInMap() { // Using the URI scheme for showing a location found on a map. This super-handy // intent can is detailed in the "Common Intents" page of Android's developer site: // http://developer.android.com/guide/components/intents-common.html#Maps if ( null != mForecastAdapter ) { Cursor c = mForecastAdapter.getCursor(); if ( null != c ) { c.moveToPosition(0); String posLat = c.getString(COL_COORD_LAT); String posLong = c.getString(COL_COORD_LONG); Uri geoLocation = Uri.parse("geo:" + posLat + "," + posLong); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(geoLocation); if (intent.resolveActivity(getActivity().getPackageManager()) != null) { startActivity(intent); } else { Log.d(LOG_TAG, "Couldn't call " + geoLocation.toString() + ", no receiving apps installed!"); } } } } public void onLocationChanged() { updateWeather(); getLoaderManager().restartLoader(FORECAST_LOADER, null, this); } @Override public void onActivityCreated(Bundle savedInstanceState) { getLoaderManager().initLoader(FORECAST_LOADER, null, this); super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // The CursorAdapter will take data from our cursor and populate the ListView. mForecastAdapter = new ForecastAdapter(getActivity(), null, 0); mForecastAdapter.setUseTodayLayout(mUseTodayLayout); View rootView = inflater.inflate(R.layout.fragment_main, container, false); // Get a reference to the ListView, and attach this adapter to it. mListView = (ListView) rootView.findViewById(R.id.listview_forecast); mListView.setEmptyView(rootView.findViewById(R.id.listview_forecast_empty)); mListView.setAdapter(mForecastAdapter); // We'll call our MainActivity mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) { // CursorAdapter returns a cursor at the correct position for getItem(), or null // if it cannot seek to that position. Cursor cursor = (Cursor) adapterView.getItemAtPosition(position); if (cursor != null) { String locationSetting = Utility.getPreferredLocation(getActivity()); ((Callback) getActivity()).onItemSelected(WeatherContract.WeatherEntry .buildWeatherLocationWithDate(locationSetting, cursor.getLong(COL_WEATHER_DATE))); } mPosition = position; } }); if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY)) { mPosition = savedInstanceState.getInt(SELECTED_KEY); } mForecastAdapter.setUseTodayLayout(mUseTodayLayout); return rootView; } @Override public void onSaveInstanceState(Bundle outState) { if (mPosition != ListView.INVALID_POSITION) { outState.putInt(SELECTED_KEY, mPosition); } super.onSaveInstanceState(outState); } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { String locationSetting = Utility.getPreferredLocation(getActivity()); // Sort order: Ascending, by date. String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherContract.WeatherEntry .buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis()); return new CursorLoader( getActivity(), weatherForLocationUri, FORECAST_COLUMNS, null, null, sortOrder); } private void setListItemSelected() { if (!mUseTodayLayout) { int position = mPosition == ListView.INVALID_POSITION ? 0 : mPosition; Cursor cursor = (Cursor) mForecastAdapter.getItem(position); if (cursor != null) { String locationSetting = Utility.getPreferredLocation(getActivity()); long date = cursor.getLong(COL_WEATHER_DATE); ((Callback) getActivity()).onItemSelected(WeatherContract.WeatherEntry .buildWeatherLocationWithDate(locationSetting, date)); } if (mPosition != ListView.INVALID_POSITION) { mListView.smoothScrollToPosition(mPosition); } } } @Override public void onLoadFinished(Loader<Cursor> loader, final Cursor cursor) { mForecastAdapter.swapCursor(cursor); if (cursor == null) { updateEmptyView(); } mHandler.sendEmptyMessage(SET_LIST_ITEM_SELECTED); } @Override public void onLoaderReset(Loader<Cursor> loader) { mForecastAdapter.swapCursor(null); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(getString(R.string.pref_location_status_key))) { updateEmptyView(); } } /** * A callback interface that all activities containing this fragment must * implement. This mechanism allows activities to be notified of item * selections. */ public interface Callback { /** * DetailFragmentCallback for when an item has been selected. */ void onItemSelected(Uri dateUri); } public void setUseTodayLayout(boolean useTodayLayout) { mUseTodayLayout = useTodayLayout; if (mForecastAdapter != null) { mForecastAdapter.setUseTodayLayout(mUseTodayLayout); } } private void updateEmptyView() { if (mForecastAdapter.getCount() == 0) { TextView emptyView = (TextView) getView().findViewById(R.id.listview_forecast_empty); if (null != emptyView) { int message = R.string.empty_forecast_list; @SunshineSyncAdapter.LocationStatus int location = Utility.getLocationStatus(getActivity()); switch (location) { case SunshineSyncAdapter.LOCATION_STATUS_SERVER_DOWN: message = R.string.empty_forecast_list_server_down; break; case SunshineSyncAdapter.LOCATION_STATUS_SERVER_INVALID: message = R.string.empty_forecast_list_server_error; break; case SunshineSyncAdapter.LOCATION_STATUS_INVALID: message = R.string.empty_forecast_list_invalid_location; break; default: if (!Utility.isNetworkAvaille(getActivity())) { message = R.string.empty_forecast_list_no_network; } } emptyView.setText(message); } } } }
7odri9o/Sunshine
app/src/main/java/com/dreamdevs/sunshine/fragment/ForecastFragment.java
Java
mit
12,550
//Copyright (c) 2010 Lex Li // //Permission is hereby granted, free of charge, to any person obtaining a copy of this //software and associated documentation files (the "Software"), to deal in the Software //without restriction, including without limitation the rights to use, copy, modify, merge, //publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons //to whom the Software is furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all copies or //substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, //INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR //PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE //FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR //OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER //DEALINGS IN THE SOFTWARE. using System.Diagnostics; using System.Reflection; using System.Text; using log4net; namespace Lextm.Common { public static class LogExtension { private const string EnterMark = "-->"; private const string LeaveMark = "<--"; public static void EnterMethod(this ILog logger) { if (logger.IsDebugEnabled) { logger.Debug(GetCallerName(new StringBuilder(EnterMark))); } } public static void LeaveMethod(this ILog logger) { if (logger.IsDebugEnabled) { logger.Debug(GetCallerName(new StringBuilder(LeaveMark))); } } private static string GetCallerName(StringBuilder result) { var mi = (new StackTrace(true)).GetFrame(2).GetMethod(); result.AppendFormat("{0}.{1}(", mi.ReflectedType.Name, mi.Name); foreach (var parameter in mi.GetParameters()) { result.AppendFormat(parameter.IsOut ? "out {0}, " : "{0}, ", parameter.ParameterType); } if (mi.GetParameters().Length > 0) { result.Length = result.Length - 2; } return result.Append(")").ToString(); } } }
yonglehou/sharpsnmplib
lib/LogExtension.cs
C#
mit
2,438
from __future__ import print_function from __future__ import division # python bpzchisq2run.py ACS-Subaru # PRODUCES ACS-Subaru_bpz.cat # ADDS A FEW THINGS TO THE BPZ CATALOG # INCLUDING chisq2 AND LABEL HEADERS # ~/p/bpzchisq2run.py NOW INCLUDED! # ~/Tonetti/colorpro/bpzfinalize7a.py # ~/UDF/Elmegreen/phot8/bpzfinalize7.py # ~/UDF/bpzfinalize7a.py, 7, 5, 4, 23_djh, 23, 3 # NOW TAKING BPZ OUTPUT w/ 3 REDSHIFT PEAKS # ALSO USING NEW i-band CATALOG istel.cat -- w/ CORRECT IDs # python bpzfinalize.py bvizjh_cut_sexseg2_allobjs_newres_offset3_djh_Burst_1M from builtins import range from past.utils import old_div from coetools import * sum = add.reduce # Just to make sure ################## # add nf, jhgood, stellarity, x, y inbpz = capfile(sys.argv[1], 'bpz') inroot = inbpz[:-4] infile = loadfile(inbpz) for line in infile: if line[:7] == '##INPUT': incat = line[8:] break for line in infile: if line[:9] == '##N_PEAKS': npeaks = string.atoi(line[10]) break #inchisq2 = inroot + '.chisq2' #outbpz = inroot + '_b.bpz' outbpz = inroot + '_bpz.cat' if npeaks == 1: labels = string.split( 'id zb zbmin zbmax tb odds zml tml chisq') elif npeaks == 3: labels = string.split( 'id zb zbmin zbmax tb odds zb2 zb2min zb2max tb2 odds2 zb3 zb3min zb3max tb3 odds3 zml tml chisq') else: print('N_PEAKS = %d!?' % npeaks) sys.exit(1) labelnicks = {'Z_S': 'zspec', 'M_0': 'M0'} read = 0 ilabel = 0 for iline in range(len(infile)): line = infile[iline] if line[:2] == '##': if read: break else: read = 1 if read == 1: ilabel += 1 label = string.split(line)[-1] if ilabel >= 10: labels.append(labelnicks.get(label, label)) mybpz = loadvarswithclass(inbpz, labels=labels) mycat = loadvarswithclass(incat) #icat = loadvarswithclass('/home/coe/UDF/istel.cat') #icat = icat.takeids(mycat.id) #bpzchisq2 = loadvarswithclass(inchisq2) ################################# # CHISQ2, nfdet, nfobs if os.path.exists(inroot + '.flux_comparison'): data = loaddata(inroot + '.flux_comparison+') #nf = 6 nf = old_div((len(data) - 5), 3) # id M0 zb tb*3 id = data[0] ft = data[5:5 + nf] # FLUX (from spectrum for that TYPE) fo = data[5 + nf:5 + 2 * nf] # FLUX (OBSERVED) efo = data[5 + 2 * nf:5 + 3 * nf] # FLUX_ERROR (OBSERVED) # chisq 2 eft = old_div(ft, 15.) eft = max(eft) # for each galaxy, take max eft among filters ef = sqrt(efo**2 + eft**2) # (6, 18981) + (18981) done correctly dfosq = (old_div((ft - fo), ef))**2 dfosqsum = sum(dfosq) detected = greater(fo, 0) nfdet = sum(detected) observed = less(efo, 1) nfobs = sum(observed) # DEGREES OF FREEDOM dof = clip2(nfobs - 3., 1, None) # 3 params (z, t, a) chisq2clip = old_div(dfosqsum, dof) sedfrac = divsafe(max(fo - efo), max(ft), -1) # SEDzero chisq2 = chisq2clip[:] chisq2 = where(less(sedfrac, 1e-10), 900., chisq2) chisq2 = where(equal(nfobs, 1), 990., chisq2) chisq2 = where(equal(nfobs, 0), 999., chisq2) ################################# #print 'BPZ tb N_PEAKS BUG FIX' #mybpz.tb = mybpz.tb + 0.667 #mybpz.tb2 = where(greater(mybpz.tb2, 0), mybpz.tb2 + 0.667, -1.) #mybpz.tb3 = where(greater(mybpz.tb3, 0), mybpz.tb3 + 0.667, -1.) mybpz.add('chisq2', chisq2) mybpz.add('nfdet', nfdet) mybpz.add('nfobs', nfobs) #mybpz.add('jhgood', jhgood) if 'stel' in mycat.labels: mybpz.add('stel', mycat.stel) elif 'stellarity' in mycat.labels: mybpz.add('stel', mycat.stellarity) if 'maxsigisoaper' in mycat.labels: mybpz.add('sig', mycat.maxsigisoaper) if 'sig' in mycat.labels: mybpz.assign('sig', mycat.maxsigisoaper) #mybpz.add('x', mycat.x) #mybpz.add('y', mycat.y) if 'zspec' not in mybpz.labels: if 'zspec' in mycat.labels: mybpz.add('zspec', mycat.zspec) print(mycat.zspec) if 'zqual' in mycat.labels: mybpz.add('zqual', mycat.zqual) print(mybpz.labels) mybpz.save(outbpz, maxy=None) ################## # det # 0 < mag < 99 # dmag > 0 # fo > 0 # efo -> 1.6e-8, e.g. # undet # mag = 99 # dmag = -m_1sigma # fo = 0 # efo = 0 -> 5e13, e.g. # unobs # mag = -99 # dmag = 0 # fo = 0 # efo = inf (1e108) ## # original chisq usually matches this: ## dfosq = ((ft - fo) / efo) ** 2 ## dfosqsum = sum(dfosq) ## observed = less(efo, 1) ## nfobs = sum(observed) ## chisq = dfosqsum / (nfobs - 1.)
boada/planckClusters
MOSAICpipe/bpz-1.99.3/bpzfinalize.py
Python
mit
4,563
module Capistrano module RbEnv VERSION = "1.0.6git" end end
yyuu/capistrano-rbenv
lib/capistrano-rbenv/version.rb
Ruby
mit
68
import React, { Component } from 'react' import PropTypes from 'prop-types' import themed from '@rentpath/react-themed' import clsx from 'clsx' import isEqual from 'lodash/isEqual' import { randomId } from '@rentpath/react-ui-utils' import SubmitButton from './SubmitButton' import Header from './Header' import { Form, Field, Name, Message, Email, Phone, RadioGroup, OptInNewsLetter, TermsOfService, } from '../Form' const FIELD_MAPPING = { header: Header, name: Name, message: Message, email: Email, phone: Phone, tos: TermsOfService, submit: SubmitButton, opt_in_newsletter: OptInNewsLetter, terms_of_service: TermsOfService, } const FIELDS = [ { name: 'header' }, { name: 'message' }, { name: 'name' }, { name: 'email' }, { name: 'phone' }, { name: 'submit' }, { name: 'opt_in_newsletter' }, { name: 'terms_of_service' }, ] @themed(/^(LeadForm|Field)/) export default class LeadForm extends Component { static propTypes = { theme: PropTypes.object, className: PropTypes.string, fields: PropTypes.arrayOf( PropTypes.shape({ name: PropTypes.string, field: PropTypes.oneOfType([ PropTypes.func, PropTypes.node, ]), }), ), children: PropTypes.node, } static defaultProps = { theme: {}, fields: FIELDS, } constructor(props) { super(props) this.generateRandomId() } componentWillReceiveProps() { this.generateRandomId() } shouldComponentUpdate(nextProps) { return !isEqual(this.props.fields, nextProps.fields) } get fields() { const { fields } = this.props return fields.map(fieldComposition => { const { field, className, ...props } = fieldComposition const name = props.name const FormField = field || FIELD_MAPPING[name] || this.fallbackField(props.type) return ( <FormField data-tid={`lead-form-${name}`} key={`${this.id}-${name}`} {...props} /> ) }) } generateRandomId() { this.id = randomId('leadform') } fallbackField(type) { return type === 'radiogroup' ? RadioGroup : Field } render() { const { className, theme, fields, children, ...props } = this.props return ( <Form className={clsx( theme.LeadForm, className, )} {...props} > {this.fields} {children} </Form> ) } }
rentpath/react-ui
packages/react-ui-core/src/LeadForm/LeadForm.js
JavaScript
mit
2,529
<?php namespace Poker; use Faker\Factory; use Symfony\Component\Console\Helper\Table; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class RandomGame extends GameCommand { use GameTrait; /** * Configures the current command. */ public function configure() { $this->setName('random') ->setDescription('Just random some people and start a poker game.') ->addOption('number', null, InputOption::VALUE_OPTIONAL, 'set player number of this game.', 2); } /** * Executes the current command. */ public function execute(InputInterface $input, OutputInterface $output) { $number = $input->getOption('number'); $faker = Factory::create(); for ($i=0; $i < $number; $i++) { $username = $faker->firstname; $hand = $this->random->generateHand(); $hands[] = $hand; $rows[] = [$username, implode(' ', $hand)]; $data[] = [$username, $this->transfer->toFlowers(implode(' ', $hand))]; } $this->exercuteGame($input, $output, $data, $rows, $hands); } }
RryLee/phppoker
src/RandomGame.php
PHP
mit
1,239
export * from './user'; export * from './template';
nswweb/templateMgr
server/src/schemas/index.js
JavaScript
mit
51
package TankWarGame; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; public class EnergyBar extends GameObject { int energy; int defaultEnergy = 5000/30; public int getEnergy() { return energy; } public void setEnergy(int energy) { this.energy = energy; } public EnergyBar(int x,int y,int width,int weight,Image[] images,int energy) { // TODO Auto-generated constructor stub super(x, y, width, weight, images); this.energy = energy; } void draw(Graphics g) { g.setColor(Color.RED); g.fillRect(x, y, energy *40 /defaultEnergy, height); energy--; } }
TakeshiTseng/JavaTankWarGame
src/TankWarGame/EnergyBar.java
Java
mit
633
package com.amee.domain.data.builder.v2; import com.amee.base.utils.XMLUtils; import com.amee.domain.Builder; import com.amee.domain.ItemBuilder; import com.amee.domain.ItemService; import com.amee.domain.TimeZoneHolder; import com.amee.domain.item.BaseItemValue; import com.amee.domain.item.NumberValue; import com.amee.platform.science.StartEndDate; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; public class ItemValueBuilder implements Builder { private BaseItemValue itemValue; private ItemBuilder itemBuilder; private ItemService itemService; public ItemValueBuilder(BaseItemValue itemValue, ItemService itemService) { this.itemValue = itemValue; this.itemService = itemService; } public ItemValueBuilder(BaseItemValue itemValue, ItemBuilder itemBuilder, ItemService itemService) { this(itemValue, itemService); this.itemBuilder = itemBuilder; } public JSONObject getJSONObject() throws JSONException { return getJSONObject(true); } public JSONObject getJSONObject(boolean detailed) throws JSONException { JSONObject obj = new JSONObject(); obj.put("uid", itemValue.getUid()); obj.put("path", itemValue.getPath()); obj.put("name", itemValue.getName()); obj.put("value", itemValue.getValueAsString()); if (NumberValue.class.isAssignableFrom(itemValue.getClass())) { NumberValue numberValue = (NumberValue) itemValue; obj.put("unit", numberValue.getUnit()); obj.put("perUnit", numberValue.getPerUnit()); } else { obj.put("unit", ""); obj.put("perUnit", ""); } obj.put("startDate", StartEndDate.getLocalStartEndDate(itemService.getStartDate(itemValue), TimeZoneHolder.getTimeZone()).toString()); obj.put("itemValueDefinition", itemValue.getItemValueDefinition().getJSONObject(false)); obj.put("displayName", itemValue.getDisplayName()); obj.put("displayPath", itemValue.getDisplayPath()); if (detailed) { obj.put("created", itemValue.getCreated()); obj.put("modified", itemValue.getModified()); obj.put("item", itemBuilder.getJSONObject(true)); } return obj; } public Element getElement(Document document) { return getElement(document, true); } public Element getElement(Document document, boolean detailed) { Element element = document.createElement("ItemValue"); element.setAttribute("uid", itemValue.getUid()); element.appendChild(XMLUtils.getElement(document, "Path", itemValue.getPath())); element.appendChild(XMLUtils.getElement(document, "Name", itemValue.getName())); element.appendChild(XMLUtils.getElement(document, "Value", itemValue.getValueAsString())); if (NumberValue.class.isAssignableFrom(itemValue.getClass())) { NumberValue numberValue = (NumberValue) itemValue; element.appendChild(XMLUtils.getElement(document, "Unit", numberValue.getUnit().toString())); element.appendChild(XMLUtils.getElement(document, "PerUnit", numberValue.getPerUnit().toString())); } else { element.appendChild(XMLUtils.getElement(document, "Unit", "")); element.appendChild(XMLUtils.getElement(document, "PerUnit", "")); } element.appendChild(XMLUtils.getElement(document, "StartDate", StartEndDate.getLocalStartEndDate(itemService.getStartDate(itemValue), TimeZoneHolder.getTimeZone()).toString())); element.appendChild(itemValue.getItemValueDefinition().getElement(document, false)); if (detailed) { element.setAttribute("Created", itemValue.getCreated().toString()); element.setAttribute("Modified", itemValue.getModified().toString()); element.appendChild(itemBuilder.getIdentityElement(document)); } return element; } public JSONObject getIdentityJSONObject() throws JSONException { JSONObject obj = new JSONObject(); obj.put("uid", itemValue.getUid()); obj.put("path", itemValue.getPath()); return obj; } public Element getIdentityElement(Document document) { return XMLUtils.getIdentityElement(document, "ItemValue", itemValue); } }
OpenAMEE/amee.platform.api
amee-platform-domain/src/main/java/com/amee/domain/data/builder/v2/ItemValueBuilder.java
Java
mit
4,429
// This file is part of the :(){ :|:& };:'s project // Licensing information can be found in the LICENSE file // (C) 2014 :(){ :|:& };:. All rights reserved. #include "sys/common.h" CVar * CVar::root = NULL; // ----------------------------------------------------------------------------- void CVar::Init(const std::string& name, int flags, const std::string& val, float min, float max, const char ** pool, const std::string& desc) { this->name = name; this->min = min; this->max = max; this->pool = pool; this->desc = desc; this->valueString = ""; this->next = root; root = this; this->flags = flags & ~CVAR_READONLY; SetString(val); this->flags = flags & ~CVAR_MODIFIED; } // ----------------------------------------------------------------------------- void CVar::SetBool(bool b) { flags |= CVAR_MODIFIED; if (flags & CVAR_READONLY) { EXCEPT << "Attempting to set readonly cvar '" << name << "'"; } valueBool = b; valueInt = b ? 1 : 0; valueFloat = b ? 1.0f : 0.0f; valueString = b ? "true" : "false"; return; } // ----------------------------------------------------------------------------- void CVar::SetInt(int i) { flags |= CVAR_MODIFIED; if (flags & CVAR_READONLY) { EXCEPT << "Attempting to set readonly cvar '" << name << "'"; } valueBool = i ? true : false; valueInt = i; valueFloat = (float)valueInt; if (flags & CVAR_BOOL) { valueString = valueBool ? "true" : "false"; } else if (flags & CVAR_INT || flags & CVAR_STRING) { valueString.resize(20); sprintf(&valueString[0], "%d", valueInt); } else if (flags & CVAR_FLOAT) { valueString.resize(20); sprintf(&valueString[0], "%ff", valueFloat); } } // ----------------------------------------------------------------------------- void CVar::SetFloat(float f) { flags |= CVAR_MODIFIED; if (flags & CVAR_READONLY) { EXCEPT << "Attempting to set readonly cvar '" << name << "'";; } valueFloat = f; valueBool = abs(valueFloat) <= 1e-5 ? false : true; valueInt = (int)valueFloat; if (flags & CVAR_BOOL) { valueString = strdup(valueBool ? "true" : "false"); } else if (flags & CVAR_INT) { valueString.resize(20); sprintf(&valueString[0], "%d", valueInt); } else if (flags & CVAR_FLOAT || flags & CVAR_STRING) { valueString.resize(20); sprintf(&valueString[0], "%ff", valueFloat); } } // ----------------------------------------------------------------------------- void CVar::SetString(const std::string& str) { flags |= CVAR_MODIFIED; if (flags & CVAR_READONLY) { EXCEPT << "Attempting to set readonly cvar '" << name << "'"; } if (pool) { valueBool = false; valueInt = 0; valueFloat = 0.0f; valueString = ""; for (int i = 0; pool[i]; ++i) { if (str == pool[i]) { valueBool = true; valueInt = i; valueFloat = (float)i; valueString = str; } } return; } if (flags & CVAR_BOOL) { valueBool = str == "true"; valueInt = valueBool ? 1 : 0; valueFloat = valueBool ? 1.0f : 0.0f; valueString = valueBool ? "true" : "false"; return; } else if (flags & CVAR_INT) { valueInt = atoi(str.c_str()); valueBool = valueInt ? true : false; valueFloat = (float)valueInt; valueString.resize(20); sprintf(&valueString[0], "%d", valueInt); return; } else if (flags & CVAR_FLOAT) { valueFloat = (float)atof(str.c_str()); valueBool = abs(valueFloat) <= 1e-5 ? false : true; valueInt = (int)valueFloat; valueString.resize(20); sprintf(&valueString[0], "%ff", valueFloat); return; } else if (flags & CVAR_STRING) { valueBool = !str.empty(); valueInt = !str.empty(); valueFloat = str.empty() ? 0.0f : 1.0f; valueString = str; return; } }
DoCGameDev/RPG-Engine
src/sys/cvar.cc
C++
mit
3,887
package cvut.fit.borrowsystem.domain.entity; import org.springframework.data.mongodb.core.mapping.Document; /** * Created by Jakub Tuček on 03/06/16. */ @Document(collection = "item") public class Book extends Item { private int isbn; public Book() { } public Book(String itemName, int count, int isbn) { super(itemName, count); this.isbn = isbn; } public int getIsbn() { return isbn; } public void setIsbn(int isbn) { this.isbn = isbn; } }
jakub-tucek/simple-spring-borrow-system
src/main/java/cvut/fit/borrowsystem/domain/entity/Book.java
Java
mit
521
var gulp = require("gulp"), del = require("del"), ts = require("gulp-typescript"), tsProject = ts.createProject("tsconfig.json") typedoc = require("gulp-typedoc"); var compileTS = function () { return tsProject.src() .pipe(tsProject()) .js.pipe(gulp.dest("app")); }; gulp.task("doc", function() { return gulp .src(["src/**/*.ts"]) .pipe(typedoc({ module: "commonjs", target: "es5", out: "docs/", name: "My project title" })) ; }); gulp.task("ts", compileTS); gulp.task("cleanup", function() { return del([__dirname + "/app"]); }); gulp.task("default", ["cleanup", "ts"], function () { compileTS(); gulp.watch("src/**/*.ts", ["ts"]); });
SantiMA10/HomePi
gulpfile.js
JavaScript
mit
674
#============================================================================== #description : Solves travelling salesman problem by using Hill Climbing. #author : Yakup Cengiz #date : 20151121 #version : 0.1 #notes : #python_version : 3.5.0 #Reference : http://www.psychicorigami.com/category/tsp/ #============================================================================== import math import sys import os import random CommonPath = os.path.abspath(os.path.join('..', 'Common')) sys.path.append(CommonPath) import tsp def GenerateInitialPath(tour_length): tour=list(range(tour_length)) random.shuffle(tour) return tour MAX_ITERATION = 50000 def reversed_sections(tour): '''generator to return all possible variations where the section between two cities are swapped''' for i,j in tsp.AllEdges(len(tour)): if i != j: copy=tour[:] if i < j: copy[i:j+1]=reversed(tour[i:j+1]) else: copy[i+1:]=reversed(tour[:j]) copy[:j]=reversed(tour[i+1:]) if copy != tour: # no point returning the same tour yield copy def kirkpatrick_cooling(start_temp, alpha): T = start_temp while True: yield T T = alpha * T def P(prev_score,next_score,temperature): if next_score > prev_score: return 1.0 else: return math.exp( -abs(next_score-prev_score)/temperature ) class ObjectiveFunction: '''class to wrap an objective function and keep track of the best solution evaluated''' def __init__(self,objective_function): self.objective_function=objective_function self.best=None self.best_score=None def __call__(self,solution): score=self.objective_function(solution) if self.best is None or score > self.best_score: self.best_score=score self.best=solution return score def ApplySimulatedAnnealing(init_function,move_operator,objective_function,max_evaluations,start_temp,alpha): # wrap the objective function (so we record the best) objective_function=ObjectiveFunction(objective_function) current = init_function() current_score = objective_function(current) iterationCount = 1 cooling_schedule = kirkpatrick_cooling(start_temp, alpha) for temperature in cooling_schedule: done = False # examine moves around our current position for next in move_operator(current): if iterationCount >= max_evaluations: done=True break next_score=objective_function(next) iterationCount+=1 # probablistically accept this solution always accepting better solutions p = P(current_score, next_score, temperature) # random.random() basic function random() generates a random float uniformly in the range [0.0, 1.0). # p function returns data in range [0.0, 1.0] if random.random() < p: current = next current_score= next_score break # see if completely finished if done: break best_score = objective_function.best_score best = objective_function.best return (iterationCount,best_score,best) def SolveTSP(): print("Starting to solve travel salesman problem") coordinates = tsp.ReadCoordinatesFromFile(".\cityCoordinates.csv") distance_matrix = tsp.ComputeDistanceMatrix(coordinates); init_function = lambda: GenerateInitialPath(len(coordinates)) objective_function = lambda tour: -tsp.ComputeTourLength(distance_matrix, tour) start_temp,alpha = 100, 0.995 iterationCount,best_score,shortestPath = ApplySimulatedAnnealing(init_function, reversed_sections, objective_function, MAX_ITERATION,start_temp,alpha) print(iterationCount, best_score, shortestPath); tsp.DrawPath(coordinates, shortestPath, "TSP.png"); if __name__ == "__main__": SolveTSP();
yakupc/Artificial-Intelligence
Algorithms/SolveTSPSimulatedAnnealing/SolveTSPSimulatedAnnealing.py
Python
mit
4,196
/* global describe, it, beforeEach */ 'use strict'; process.env.NODE_ENV = 'test'; var sharedModule = require('../lib/module-shared'); var instance1; var instance2; var should = require('should'); var stubs = {}; describe('Private Module Tests', function () { beforeEach(function (done) { for (var stub in stubs) { try { stubs[stub].restore(); } catch (err) {} } done(); }); describe('Initializing', function () { describe('when creating a new instance of the module', function () { it('should not have an error', function (done) { var x = sharedModule({ mocking: true }); x.should.have.property('initializeModule'); should.not.exist(x.initialized); done(); }); }); }); describe('Function Calls', function () { describe('when calling "initializeModule"', function () { it('should not have an error', function (done) { var x = sharedModule({ mocking: {} }); x.should.have.property('initializeModule'); should.not.exist(x.initialized); x.initializeModule(x); should.exist(x.initialized); done(); }); }); describe('when creating more than one instance', function () { describe('and the module is already initialized', function () { it('the new instance should return the first created instance', function (done) { instance1 = sharedModule({ mocking: true }); instance2 = sharedModule({ mocking: true }); should.exist(instance1.initialized); instance1.initialized.should.equal(true); done(); }); }); describe('if we add .name = "instance1" to the first instance', function () { it('"instance2" should have a name', function (done) { delete instance1.name; delete instance2.name; instance1.name = 'instance1'; instance1.name.should.equal('instance1'); instance2.name.should.equal('instance1'); done(); }); }); describe('if we add .name = "instance2" to the second instance', function () { it('"instance1" should have a name', function (done) { delete instance1.name; delete instance2.name; instance2.name = 'instance2'; instance2.name.should.equal('instance2'); instance1.name.should.equal('instance2'); done(); }); }); describe('if we add .name to both instances and they are different names', function () { it('they should still have the same names', function (done) { delete instance1.name; delete instance2.name; instance1.name = 'instance1'; instance1.name.should.equal('instance1'); instance2.name.should.equal('instance1'); instance2.name = 'instance2'; instance1.name.should.equal('instance2'); instance2.name.should.equal('instance2'); instance1.name.should.equal(instance2.name); instance2.name.should.equal(instance1.name); done(); }); }); }); }); });
Icehunter/npm-base-package
test/module-shared-tests.js
JavaScript
mit
3,863
"""django_todo URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^todo/', include('todo.urls')), url(r'^accounts/', include('accounts.urls')), ]
GunnerJnr/_CodeInstitute
Stream-3/Full-Stack-Development/21.Django REST Framework/4.User-Authentication/django_todo/django_todo/urls.py
Python
mit
869
<?php /* * This file is part of the ItaPaypalPlugin package. * (c) Matteo Montanari <matteo@italinux.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /** * @package PayPal */ /** * Make sure our parent class is defined. */ require_once 'PayPal/Type/AbstractRequestType.php'; /** * GetBillingAgreementCustomerDetailsRequestType * * @package PayPal */ class GetBillingAgreementCustomerDetailsRequestType extends AbstractRequestType { var $Token; function GetBillingAgreementCustomerDetailsRequestType() { parent::AbstractRequestType(); $this->_namespace = 'urn:ebay:api:PayPalAPI'; $this->_elements = array_merge($this->_elements, array ( 'Token' => array ( 'required' => true, 'type' => 'ExpressCheckoutTokenType', 'namespace' => 'urn:ebay:api:PayPalAPI', ), )); } function getToken() { return $this->Token; } function setToken($Token, $charset = 'iso-8859-1') { $this->Token = $Token; $this->_elements['Token']['charset'] = $charset; } }
italinux/PaypalPlugin-v1
sdk/lib/PayPal/Type/GetBillingAgreementCustomerDetailsRequestType.php
PHP
mit
1,251
package com.jim.portal.controller; import com.jim.portal.entity.BooksEntity; import com.jim.portal.hibernate.BookManagementRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Created by jim on 2017/1/5. * This class is ... */ @Controller @RequestMapping(value = "/book") public class BookController extends BaseController { @Autowired private BookManagementRepository bookManagementRepository; @RequestMapping(value = "/updateBook", method = RequestMethod.GET) public String updateBook(){ return "system/book/update-book"; } @RequestMapping(value = "/update", method = RequestMethod.POST) public String update(BooksEntity booksEntity, String id){ result.clear(); try { bookManagementRepository.update(booksEntity, id); result.put("result", 0); }catch (Exception ex){ result.put("result", 1); result.put("msg", ex.toString()); } return gson.toJson(result); } @RequestMapping(value = "/createBook", method = RequestMethod.GET) public String createBook(){ return "system/book/create-book"; } @RequestMapping(value = "/save", method = RequestMethod.POST) public String save(BooksEntity booksEntity){ result.clear(); try { BooksEntity book = bookManagementRepository.create(booksEntity); result.put("result", 0); result.put("msg", book); }catch (Exception ex){ result.put("result", 1); result.put("msg", ex.toString()); } return gson.toJson(result); } }
liu1084/springmvc-cookbook
cloudstreetmarket-parent/cloudstreetmarket-webapp/src/main/java/com/jim/portal/controller/BookController.java
Java
mit
1,630
<?php /** * miniShop * * @author Team phpManufaktur <team@phpmanufaktur.de> * @link https://kit2.phpmanufaktur.de/miniShop * @copyright 2014 Ralf Hertsch <ralf.hertsch@phpmanufaktur.de> * @license MIT License (MIT) http://www.opensource.org/licenses/MIT */ namespace phpManufaktur\miniShop\Data\Setup; use Silex\Application; use phpManufaktur\miniShop\Data\Shop\Base; use phpManufaktur\miniShop\Data\Shop\Group; use phpManufaktur\miniShop\Data\Shop\Article; use phpManufaktur\miniShop\Data\Shop\Basket; use phpManufaktur\miniShop\Data\Shop\Order; class Uninstall { protected $app = null; /** * Execute the update for the miniShop * * @param Application $app */ public function Controller(Application $app) { $this->app = $app; $baseTable = new Base($app); $baseTable->dropTable(); $groupTable = new Group($app); $groupTable->dropTable(); $articleTable = new Article($app); $articleTable->dropTable(); $basketTable = new Basket($app); $basketTable->dropTable(); $orderTable = new Order($app); $orderTable->dropTable(); return $app['translator']->trans('Successfull uninstalled the extension %extension%.', array('%extension%' => 'miniShop')); } }
phpManufaktur/kfMiniShop
Data/Setup/Uninstall.php
PHP
mit
1,312
# coding: utf-8 [ { pt: 'Arte', en: 'Art' }, { pt: 'Artes plásticas', en: 'Visual Arts' }, { pt: 'Circo', en: 'Circus' }, { pt: 'Comunidade', en: 'Community' }, { pt: 'Humor', en: 'Humor' }, { pt: 'Quadrinhos', en: 'Comicbooks' }, { pt: 'Dança', en: 'Dance' }, { pt: 'Design', en: 'Design' }, { pt: 'Eventos', en: 'Events' }, { pt: 'Moda', en: 'Fashion' }, { pt: 'Gastronomia', en: 'Gastronomy' }, { pt: 'Cinema & Vídeo', en: 'Film & Video' }, { pt: 'Jogos', en: 'Games' }, { pt: 'Jornalismo', en: 'Journalism' }, { pt: 'Música', en: 'Music' }, { pt: 'Fotografia', en: 'Photography' }, { pt: 'Ciência e Tecnologia', en: 'Science & Technology' }, { pt: 'Teatro', en: 'Theatre' }, { pt: 'Esporte', en: 'Sport' }, { pt: 'Web', en: 'Web' }, { pt: 'Carnaval', en: 'Carnival' }, { pt: 'Arquitetura & Urbanismo', en: 'Architecture & Urbanism' }, { pt: 'Literatura', en: 'Literature' }, { pt: 'Mobilidade e Transporte', en: 'Mobility & Transportation' }, { pt: 'Meio Ambiente', en: 'Environment' }, { pt: 'Negócios Sociais', en: 'Social Business' }, { pt: 'Educação', en: 'Education' }, { pt: 'Filmes de Ficção', en: 'Fiction Films' }, { pt: 'Filmes Documentários', en: 'Documentary Films' }, { pt: 'Filmes Universitários', en: 'Experimental Films' } ].each do |name| category = Category.find_or_initialize_by_name_pt name[:pt] category.update_attributes({ name_en: name[:en] }) end [ 'confirm_backer','payment_slip','project_success','backer_project_successful', 'backer_project_unsuccessful','project_received', 'project_received_channel', 'updates','project_unsuccessful', 'project_visible','processing_payment','new_draft_project', 'new_draft_channel', 'project_rejected', 'pending_backer_project_unsuccessful', 'project_owner_backer_confirmed', 'adm_project_deadline', 'project_in_wainting_funds' ].each do |name| NotificationType.find_or_create_by_name name end #configuracoes necessarias para nao dar bug { company_name: 'Catarse', host: 'localhost:3000', base_url: "http://localhost:3000", blog_url: "http://localhost:3000", email_contact: 'contato@razaosocial.org.br', email_payments: 'financeiro@razaosocial.org.br', email_projects: 'projetos@razaosocial.org.br', email_system: 'system@razaosocial.org.br', email_no_reply: 'no-reply@razaosocial.org.br', facebook_url: "https://www.facebook.com/pages/Instituto-Raz%C3%A3o-Social/135206043213648", facebook_app_id: '173747042661491', twitter_username: "institutors", mailchimp_url: "http://catarse.us5.list-manage.com/subscribe/post?u=ebfcd0d16dbb0001a0bea3639&amp;id=149c39709e", catarse_fee: '0.13', support_forum: 'http://suporte.razaosocial.org.br/' }.each do |name, value| Configuration.find_or_create_by_name name, value: value end Channel.find_or_create_by_name!( name: "Channel name", permalink: "sample-permalink", description: "Lorem Ipsum" ) OauthProvider.find_or_create_by_name!( name: 'facebook', key: 'your_facebook_app_key', secret: 'your_facebook_app_secret', path: 'facebook' )
razaosocial/irs_crowdfunding
db/seeds.rb
Ruby
mit
3,096
/* Copyright (c) 2015 Pozirk Games * http://www.pozirk.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.pozirk.ads; //import android.util.Log; import com.amazon.device.ads.*; import org.haxe.lime.HaxeObject; public class AmazonAdsListener implements AdListener { protected HaxeObject _callback = null; protected String _who = null; public AmazonAdsListener(HaxeObject callback, String who) { _callback = callback; _who = who; } public void onAdLoaded(Ad ad, AdProperties adProperties) { //Log.d("amazonads", "onAdLoaded"); _callback.call("onStatus", new Object[] {"AD_LOADED", _who, "type: "+_who}); } public void onAdFailedToLoad(Ad ad, AdError error) { //Log.d("amazonads", "onAdFailedToLoad: "+error.getMessage()); _callback.call("onStatus", new Object[] {"AD_FAILED_TO_LOAD", _who, "type: "+_who+", "+error.getCode()+": "+error.getMessage()}); } public void onAdExpanded(Ad ad) { _callback.call("onStatus", new Object[] {"AD_EXPANDED", _who, "type: "+_who}); } public void onAdCollapsed(Ad ad) { _callback.call("onStatus", new Object[] {"AD_COLLAPSED", _who, "type: "+_who}); } public void onAdDismissed(Ad ad) { _callback.call("onStatus", new Object[] {"AD_DISMISSED", _who, "type: "+_who}); } }
openfl/extension-amazonads
dependencies/amazonads/src/com/pozirk/ads/AmazonAdsListener.java
Java
mit
2,319
package com.codepoetics.protonpack.selectors; import java.util.Comparator; import java.util.Objects; import java.util.stream.Stream; public final class Selectors { private Selectors() { } public static <T> Selector<T> roundRobin() { return new Selector<T>() { private int startIndex = 0; @Override public Integer apply(T[] options) { int result = startIndex; while (options[result] == null) { result = (result + 1) % options.length; } startIndex = (result + 1) % options.length; return result; } }; } public static <T extends Comparable<T>> Selector<T> takeMin() { return takeMin(Comparator.naturalOrder()); } public static <T> Selector<T> takeMin(Comparator<? super T> comparator) { return new Selector<T>() { private int startIndex = 0; @Override public Integer apply(T[] options) { T smallest = Stream.of(options).filter(Objects::nonNull).min(comparator).get(); int result = startIndex; while (options[result] == null || comparator.compare(smallest, options[result]) != 0) { result = (result + 1) % options.length; } startIndex = (result + 1) % options.length; return result; } }; } public static <T extends Comparable<T>> Selector<T> takeMax() { return takeMax(Comparator.naturalOrder()); } public static <T> Selector<T> takeMax(Comparator<? super T> comparator) { return takeMin(comparator.reversed()); } }
poetix/protonpack
src/main/java/com/codepoetics/protonpack/selectors/Selectors.java
Java
mit
1,740
<?php namespace Cinemino\SiteBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction($name) { return $this->render('CineminoSiteBundle:Default:index.html.twig', array('name' => $name)); } }
hclerb/Cinemino
src/Cinemino/SiteBundle/Controller/DefaultController.php
PHP
mit
307
<?php namespace JDT\Api; use Illuminate\Http\Request; use Illuminate\Routing\Router; use Laravel\Passport\Passport; use Illuminate\Http\UploadedFile; use JDT\Api\Http\InternalApiRequest; use Illuminate\Filesystem\Filesystem; use Laravel\Passport\ApiTokenCookieFactory; use Symfony\Component\HttpFoundation\Cookie; use Illuminate\Contracts\Container\Container; use JDT\Api\Exceptions\InternalHttpException; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Debug\ExceptionHandler; use Illuminate\Support\Facades\Request as RequestFacade; use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; class InternalRequest { /** * Setup Params. */ protected $container; protected $cookieFactory; protected $fileSystem; protected $requestStack; protected $routeStack; /** * Request Params. */ protected $attach; protected $be; protected $cookies; protected $headers; protected $content; protected $on; protected $once = false; protected $with; /** * InternalRequest constructor. * @param \Illuminate\Contracts\Container\Container $container * @param \Illuminate\Filesystem\Filesystem $fileSystem * @param \Illuminate\Routing\Router $router * @param \Laravel\Passport\ApiTokenCookieFactory $cookieFactory */ public function __construct(Container $container, Filesystem $fileSystem, Router $router, ApiTokenCookieFactory $cookieFactory) { $this->container = $container; $this->fileSystem = $fileSystem; $this->router = $router; $this->cookieFactory = $cookieFactory; $this->reset(); $this->setupRequestStack(); } /** * @return \JDT\Api\InternalRequest */ public function reset():self { $this->attach = []; $this->cookies = []; $this->headers = []; $this->content = null; $this->on = null; $this->with = []; if ($this->once === true) { $this->be = null; $this->once = false; } return $this; } /** * Setup the request stack by grabbing the initial request. */ protected function setupRequestStack() { $this->requestStack[] = $this->container['request']; } /** * @param array $attach * @return \JDT\Api\InternalRequest */ public function attach(array $files) { foreach ($files as $key => $file) { if (is_array($file)) { $file = new UploadedFile($file['path'], basename($file['path']), $file['mime'], $file['size']); } elseif (is_string($file)) { $finfo = finfo_open(FILEINFO_MIME_TYPE); $file = new UploadedFile($file, basename($file), finfo_file($finfo, $file), $this->fileSystem->size($file)); } elseif (!$file instanceof UploadedFile) { continue; } $this->attach[$key] = $file; } return $this; } /** * @param \Illuminate\Contracts\Auth\Authenticatable $user * @return \JDT\Api\InternalRequest */ public function be(Authenticatable $user):self { $this->be = $user; return $this; } /** * @param \Symfony\Component\HttpFoundation\Cookie $cookie * @return \JDT\Api\InternalRequest */ public function cookie(Cookie $cookie):self { $value = $cookie->getValue(); if ($cookie->getName() === Passport::cookie()) { $value = encrypt($value); } $this->cookies[$cookie->getName()] = $value; return $this; } /** * @param string $key * @param string $value * @return \JDT\Api\InternalRequest */ public function header(string $key, string $value):self { $this->headers[$key] = $value; return $this; } /** * @param array|string $json * @return \JDT\Api\InternalRequest */ public function json($json):self { if (is_array($json)) { $json = json_encode($json); } $this->content = $content; return $this->header('Content-Type', 'application/json'); } /** * @param string $on * @return \JDT\Api\InternalRequest */ public function on(string $on):self { $this->on = $on; return $this; } /** * @return \JDT\Api\InternalRequest */ public function once():self { $this->once = true; return $this; } /** * @param string|array $with * @return \JDT\Api\InternalRequest */ public function with($with):self { $this->with = array_merge($this->with, is_array($with) ? $with : func_get_args()); return $this; } /** * @param string $routeName * @param array $params * @return \JDT\Api\InternalResult */ public function delete(string $routeName, array $params = []):InternalResult { return $this->queueRequest('delete', $routeName, $params); } /** * @param string $routeName * @param array $params * @return \JDT\Api\InternalResult */ public function get(string $routeName, array $params = []):InternalResult { return $this->queueRequest('get', $routeName, $params); } /** * @param string $routeName * @param array $params * @return \JDT\Api\InternalResult */ public function patch(string $routeName, array $params = []):InternalResult { return $this->queueRequest('patch', $routeName, $params); } /** * @param string $routeName * @param array $params * @return \JDT\Api\InternalResult */ public function post(string $routeName, array $params = []):InternalResult { return $this->queueRequest('post', $routeName, $params); } /** * @param string $routeName * @param array $params * @return \JDT\Api\InternalResult */ public function put(string $routeName, array $params = []):InternalResult { return $this->queueRequest('put', $routeName, $params); } /** * @param string $method * @param string $routeName * @param array $params * @return \JDT\Api\InternalResult */ protected function queueRequest(string $method, string $routeName, array $params = []):InternalResult { $allowedMethods = [ 'delete', 'get', 'patch', 'post', 'put', ]; if (!in_array($method, $allowedMethods)) { throw new \BadMethodCallException('Unknown method "' . $method . '"'); } $uri = route($routeName, $params, false); // Sometimes after setting the initial request another request might be made prior to // internally dispatching an API request. We need to capture this request as well // and add it to the request stack as it has become the new parent request to // this internal request. This will generally occur during tests when // using the crawler to navigate pages that also make internal // requests. if (end($this->requestStack) != $this->container['request']) { $this->requestStack[] = $this->container['request']; } $this->requestStack[] = $request = $this->createRequest($method, $uri, $params); $result = $this->dispatch($request); if (empty($result->getContent())) { $content = []; } else { $content = json_decode($result->getContent(), true); } return new InternalResult($content, $result->getOriginalContent(), $result->getStatusCode()); } /** * @param string $method * @param string $uri * @param array $params * @return InternalApiRequest */ protected function createRequest(string $method, string $uri, array $params = []) { $parameters = array_merge($this->with, $params); // If the URI does not have a scheme then we can assume that there it is not an // absolute URI, in this case we'll prefix the root requests path to the URI. $rootUrl = $this->getRootRequest()->root(); if ((!parse_url($uri, PHP_URL_SCHEME)) && parse_url($rootUrl) !== false) { $uri = rtrim($rootUrl, '/') . '/' . ltrim($uri, '/'); } if ($this->be !== null) { $token = uniqid(); $this->cookie($this->cookieFactory->make($this->be->getKey(), $token)); $this->header('X-CSRF-TOKEN', $token); } $request = InternalApiRequest::create( $uri, $method, $parameters, $this->cookies, $this->attach, $this->container['request']->server->all(), $this->content ); $request->headers->set('host', $this->on); foreach ($this->headers as $header => $value) { $request->headers->set($header, $value); } $request->headers->set('accept', $this->getAcceptHeader()); return $request; } /** * Build the "Accept" header. * * @return string */ protected function getAcceptHeader():string { return 'application/vnd.jb.v1+json'; } /** * @param \JDT\Api\Http\InternalApiRequest $request * @return \Illuminate\Http\Response|mixed * @throws InternalHttpException|HttpExceptionInterface */ protected function dispatch(InternalApiRequest $request) { $this->routeStack[] = $this->router->getCurrentRoute(); $this->clearCachedFacadeInstance(); $exceptionHandler = $this->container->make(ExceptionHandler::class); $this->container->offsetUnset(ExceptionHandler::class); try { $this->container->instance('request', $request); $response = $this->router->dispatch($request); if (!$response->isSuccessful() && !$response->isRedirection()) { throw new InternalHttpException($response); } } finally { $this->container->instance(ExceptionHandler::class, $exceptionHandler); $this->refreshRequestStack(); } return $response; } /** * Refresh the request stack. * * This is done by resetting the authentication, popping * the last request from the stack, replacing the input, * and resetting the version and parameters. * * @return void */ protected function refreshRequestStack() { if ($route = array_pop($this->routeStack)) { $this->router->setCurrentRoute($route); } $this->replaceRequestInstance(); $this->clearCachedFacadeInstance(); $this->reset(); } /** * Replace the request instance with the previous request instance. * * @return void */ protected function replaceRequestInstance() { array_pop($this->requestStack); $request = end($this->requestStack); $this->container->instance('request', $request); $this->router->setCurrentRequest($request); } /** * Clear the cached facade instance. * * @return void */ protected function clearCachedFacadeInstance() { // Facades cache the resolved instance so we need to clear out the // request instance that may have been cached. Otherwise we'll // may get unexpected results. RequestFacade::clearResolvedInstance('request'); } /** * Get the root request instance. * * @return \Illuminate\Http\Request */ protected function getRootRequest():Request { return reset($this->requestStack); } }
jdtsoftware/api
src/InternalRequest.php
PHP
mit
11,858
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DotNetFrameworkVersionResponseCSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DotNetFrameworkVersionResponseCSharp")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1367e980-73f8-4862-8abb-c6184b511644")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
guitarrapc/AzureFunctionsIntroduction
v1/src/DotNetFrameworkVersionResponseCSharp/Properties/AssemblyInfo.cs
C#
mit
1,408
class Public::PeopleController < ApplicationController layout false after_action :allow_iframe skip_before_action :verify_authenticity_token skip_before_action :authenticate_user! # GET /people/new def new @referrer = false if params[:referrer] begin uri = URI.parse(params[:referrer]) @referrer = params[:referrer] if uri.is_a?(URI::HTTP) rescue URI::InvalidURIError @referrer = false end end @person = ::Person.new end # POST /people # rubocop:disable Metrics/MethodLength def create @person = ::Person.new(person_params) @person.signup_at = Time.current success_msg = 'Thanks! We will be in touch soon!' error_msg = "Oops! Looks like something went wrong. Please get in touch with us at <a href='mailto:#{ENV['MAILER_SENDER']}?subject=Patterns sign up problem'>#{ENV['MAILER_SENDER']}</a> to figure it out!" if @person.save msg = success_msg add_tag(params[:age_range]) unless params[:age_range].blank? add_tag(params[:referral]) unless params[:referral].blank? else msg = error_msg end respond_to do |format| @msg = msg format.html { render action: 'create' } end end # rubocop:enable Metrics/MethodLength def deactivate @person =Person.find_by(token: d_params[:token]) if @person && @person.id == d_params[:person_id].to_i @person.deactivate!('email') else redirect_to root_path end end private def d_params params.permit(:person_id, :token) end # rubocop:disable Metrics/MethodLength def person_params params.require(:person).permit(:first_name, :last_name, :email_address, :phone_number, :preferred_contact_method, :address_1, :address_2, :city, :state, :postal_code, :token, :primary_device_id, :primary_device_description, :secondary_device_id, :secondary_device_description, :primary_connection_id, :primary_connection_description, :secondary_connection_id, :secondary_connection_description, :participation_type) end # rubocop:enable Metrics/MethodLength def allow_iframe response.headers.except! 'X-Frame-Options' end def add_tag(tag) tag = Tag.find_or_initialize_by(name: tag) tag.created_by ||= 1 # first user. tag.save! Tagging.create(taggable_type: 'Person', taggable_id: @person.id, created_by: 1, tag: tag) end end
smartchicago/kimball
app/controllers/public/people_controller.rb
Ruby
mit
2,632
<?php class AnnotatorException extends Exception { } class Annotator { const INFO = 0; const BEFORE = 1; const AFTER = 2; const AROUND = 3; public static $annotations = array(); /** * Register annotation handler * * @param string $annotation Annotation code * @param callable $handler Annotation handler * @param int $type Annotation type */ public static function register($annotation, $handler, $type) { if (!preg_match('!^[a-z0-9_]+$!i', $annotation)) { throw new AnnotatorException('Invalid annotation'); } if (in_array($annotation, array('before', 'after', 'around'))) { throw new AnnotatorException('Annotation "' . $annotation . '" is reserved'); } if (isset(self::$annotations[$annotation])) { throw new AnnotatorException('Annotation "' . $annotation . '" already registered'); } if (!is_callable($handler)) { throw new AnnotatorException('Handler must be callable'); } if (!is_int($type) || ($type < 0) || ($type > 3)) { throw new AnnotatorException('Invalid type'); } self::$annotations[$annotation] = array('type' => $type, 'handler' => $handler); } /** * Compile annotated class * * @param string $class Class name */ public static function compile($class) { try { $class = new ReflectionClass($class); } catch (Exception $e) { throw new AnnotatorException('Class ' . $class . ' does not exist'); } $methods = $class->getMethods(); $annotations = array('info', 'before', 'after', 'around'); $annotations = array_merge($annotations, array_keys(self::$annotations)); $pattern = '!\*\s*@((' . implode('|', $annotations) . ')[ \t]*([^\n\r]*))!'; foreach ($methods as $method) { $comment = $method->getDocComment(); if (empty($comment)) { continue; } preg_match_all($pattern, $comment, $matches); if (empty($matches[1])) { continue; } $flags = 0; $before = ''; $after = ''; $around = ''; if ($method->isStatic()) { $treatment = 'self::'; $callable = 'array(\'' . $class->name . '\', \'' . $method->name . '\')'; $flags = $flags | RUNKIT_ACC_STATIC; } else { $treatment = '$this->'; $callable = 'array($this, \'' . $method->name . '\')'; } foreach ($matches[2] as $position => $annotation) { $options = preg_split('![ ]+!', $matches[3][$position]); switch ($annotation) { case 'info' : call_user_func(array_shift($options), array($class->name, $method->name), $options); break; case 'before' : $before .= array_shift($options) . '(' . $callable . ', $__annotator_parameters, ' . var_export($options, true) . ');' . PHP_EOL; break; case 'after' : $after .= '$__annotator_result = ' . array_shift($options) . '(' . $callable . ', $__annotator_parameters, ' . var_export($options, true) . ', $__annotator_result);' . PHP_EOL; break; case 'around' : $around .= '$__annotator_proceed = function() use($__annotator_proceed, $__annotator_parameters) { return ' . array_shift($options) . '(' . $callable . ', $__annotator_parameters, ' . var_export($options, true) . ', $__annotator_proceed); };'; break; default : switch (self::$annotations[$annotation]['type']) { case self::INFO : call_user_func(self::$annotations[$annotation]['handler'], array($class->name, $method->name), $options); break; case self::BEFORE : $before .= 'call_user_func(Annotator::$annotations[\'' . $annotation . '\'][\'handler\'], ' . $callable . ', $__annotator_parameters, ' . var_export($options, true) . ');' . PHP_EOL; break; case self::AFTER : $after .= '$__annotator_result = call_user_func(Annotator::$annotations[\'' . $annotation . '\'][\'handler\'], ' . $callable . ', $__annotator_parameters, ' . var_export($options, true) . ', $__annotator_result);' . PHP_EOL; break; case self::AROUND : $around .= '$__annotator_proceed = function() use($__annotator_proceed, $__annotator_parameters) { return call_user_func(Annotator::$annotations[\'' . $annotation . '\'][\'handler\'], ' . $callable . ', $__annotator_parameters, ' . var_export($options, true) . ', $__annotator_proceed); };'; break; } break; } } if (empty($before) && empty($after) && empty($around)) { continue; } if ($method->isPublic()) { $flags = $flags | RUNKIT_ACC_PUBLIC; } elseif ($method->isProtected()) { $flags = $flags | RUNKIT_ACC_PROTECTED; } elseif ($method->isPrivate()) { $flags = $flags | RUNKIT_ACC_PRIVATE; } $parameters = $method->getParameters(); $parametersForDefinition = array(); $parametersForCall = array(); $parametersForAdvice = array(); $parametersForUse = array(); foreach ($parameters as $parameter) { $value = ''; $reference = ''; if ($parameter->isDefaultValueAvailable()) { $value = '=' . var_export($parameter->getDefaultValue(), true); } if ($parameter->isPassedByReference()) { $reference = '&'; } $parametersForDefinition[] = $reference . '$' . $parameter->name . $value; $parametersForCall[] = $reference . '$' . $parameter->name; $parametersForAdvice[] = '$__annotator_parameters[\'' . $parameter->name . '\'] = ' . '&$' . $parameter->name . ';'; $parametersForUse[] = '$' . $parameter->name; } $use = ''; if (!empty($parametersForUse)) { $use = 'use (' . implode(', ', $parametersForUse) . ')'; } $function = ' $__annotator_parameters = array(); ' . implode(' ', $parametersForAdvice) . ' ' . $before . ' $__annotator_proceed = function() ' . $use . ' { return ' . $treatment . '__annotator_' . $method->name . '(' . implode(', ', $parametersForCall) . '); }; ' . $around . ' $__annotator_result = $__annotator_proceed(); ' . $after . ' return $__annotator_result; '; runkit_method_rename($class->name, $method->name, '__annotator_' . $method->name); runkit_method_add( $class->name, $method->name, implode(',', $parametersForDefinition), $function, $flags ); } } }
baryshev/Annotator
Annotator.php
PHP
mit
6,141
using AppShell.NativeMaps; namespace AppShell.Samples.NativeMaps { public class NativeMapsShellCore : ShellCore { public override void Run() { Push<MasterDetailShellViewModel>(new { Name = "Main", Master = new NativeMapsMasterViewModel(serviceDispatcher) }); serviceDispatcher.Dispatch<INavigationService>(n => n.Push<MapViewModel>(new { Title = "Single Map", ZoomLevel = 15.0, Center = new Location(48.21, 16.37) })); } } }
cschwarz/AppShell
samples/NativeMaps/AppShell.Samples.NativeMaps/NativeMapsShellCore.cs
C#
mit
490
import { featureCollection, lineString, multiLineString, // Typescript Definitions Polygon, LineString, MultiLineString, MultiPolygon, Feature, FeatureCollection } from '@turf/helpers' import lineStringToPolygon from './' // Fixtures const coords = [[125, -30], [145, -30], [145, -20], [125, -20], [125, -30]]; const line = lineString(coords); const multiLine = multiLineString([coords, coords]); const fc = featureCollection([line, multiLine]); // Assert results with types const poly1: Feature<Polygon> = lineStringToPolygon(line); const poly2: Feature<Polygon> = lineStringToPolygon(multiLine); const poly3: Feature<MultiPolygon> = lineStringToPolygon(fc);
hooplert/jesper
packages/turf-linestring-to-polygon/types.ts
TypeScript
mit
702
module Ruboty module Variable module Actions class Get < Ruboty::Variable::Actions::Variable def call(key) if var.data.has_key?(key) message.reply(var.get(key)) else message.reply(undefined_message(key)) end end def undefined_message(key) "Undefined #{key}" end end end end end
snakazawa/ruboty-variable
lib/ruboty/variable/actions/get.rb
Ruby
mit
400
<?php /** * Trait for Control that use Vue Lookup component. */ declare(strict_types=1); namespace Atk4\Ui\Form\Control; use Atk4\Ui\Callback; trait VueLookupTrait { /** @var Callback */ public $dataCb; public function initVueLookupCallback(): void { if (!$this->dataCb) { $this->dataCb = Callback::addTo($this); } $this->dataCb->set(\Closure::fromCallable([$this, 'outputApiResponse'])); } /** * Output lookup search query data. * * @return never */ public function outputApiResponse() { $fieldName = $_GET['atk_vlookup_field'] ?? null; $query = $_GET['atk_vlookup_q'] ?? null; $data = []; if ($fieldName) { $ref = $this->getModel()->getField($fieldName)->getReference(); $model = $ref->refModel($this->model); $refFieldName = $ref->getTheirFieldName(); if (!empty($query)) { $model->addCondition($model->title_field, 'like', '%' . $query . '%'); } foreach ($model as $row) { $data[] = ['key' => $row->get($refFieldName), 'text' => $row->getTitle(), 'value' => $row->get($refFieldName)]; } } $this->getApp()->terminateJson([ 'success' => true, 'results' => $data, ]); } }
atk4/ui
src/Form/Control/VueLookupTrait.php
PHP
mit
1,370
//////////////////////////////////////////////////////////////////////////// // // This file is part of RTIMULibCS // // Copyright (c) 2015, richards-tech, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. namespace RTIMULibCS.Devices.LSM9DS1 { /// <summary> /// Configuration of the LSM9DS1 IMU-sensor. /// </summary> public class LSM9DS1Config { public LSM9DS1Config() { GyroSampleRate = GyroSampleRate.Freq119Hz; GyroBandwidthCode = GyroBandwidthCode.BandwidthCode1; GyroHighPassFilterCode = GyroHighPassFilterCode.FilterCode4; GyroFullScaleRange = GyroFullScaleRange.Range500; AccelSampleRate = AccelSampleRate.Freq119Hz; AccelFullScaleRange = AccelFullScaleRange.Range8g; AccelLowPassFilter = AccelLowPassFilter.Freq50Hz; CompassSampleRate = CompassSampleRate.Freq20Hz; MagneticFullScaleRange = MagneticFullScaleRange.Range4Gauss; } /// <summary> /// The gyro sample rate /// </summary> public GyroSampleRate GyroSampleRate { get; } /// <summary> /// The gyro bandwidth code /// </summary> public GyroBandwidthCode GyroBandwidthCode { get; } /// <summary> /// The gyro high pass filter cutoff code /// </summary> public GyroHighPassFilterCode GyroHighPassFilterCode { get; } /// <summary> /// The gyro full scale range /// </summary> public GyroFullScaleRange GyroFullScaleRange { get; } /// <summary> /// The accel sample rate /// </summary> public AccelSampleRate AccelSampleRate { get; } /// <summary> /// The accel full scale range /// </summary> public AccelFullScaleRange AccelFullScaleRange { get; } /// <summary> /// The accel low pass filter /// </summary> public AccelLowPassFilter AccelLowPassFilter { get; } /// <summary> /// The compass sample rate /// </summary> public CompassSampleRate CompassSampleRate { get; } /// <summary> /// The compass full scale range /// </summary> public MagneticFullScaleRange MagneticFullScaleRange { get; } } }
emmellsoft/RPi.SenseHat
RPi.SenseHat/RTIMULibCS/Devices/LSM9DS1/LSM9DS1Config.cs
C#
mit
3,360
// C++. #include <cassert> #include <sstream> #include <algorithm> // Qt. #include <QWidget> #include <QMessageBox> #include <QDesktopWidget> #include <QFileDialog> // Infra. #include <QtCommon/Util/RestoreCursorPosition.h> #include <QtCommon/Scaling/ScalingManager.h> #include <Utils/Include/rgaCliDefs.h> // Local. #include <RadeonGPUAnalyzerGUI/Include/Qt/rgBuildSettingsView.h> #include <RadeonGPUAnalyzerGUI/Include/Qt/rgBuildSettingsViewVulkan.h> #include <RadeonGPUAnalyzerGUI/Include/Qt/rgCheckBox.h> #include <RadeonGPUAnalyzerGUI/Include/Qt/rgIncludeDirectoriesView.h> #include <RadeonGPUAnalyzerGUI/Include/Qt/rgLineEdit.h> #include <RadeonGPUAnalyzerGUI/Include/Qt/rgPreprocessorDirectivesDialog.h> #include <RadeonGPUAnalyzerGUI/Include/rgCliUtils.h> #include <RadeonGPUAnalyzerGUI/Include/rgConfigManager.h> #include <RadeonGPUAnalyzerGUI/Include/rgStringConstants.h> #include <RadeonGPUAnalyzerGUI/Include/rgUtils.h> // Checkbox tool tip stylesheets. static const char* s_STR_FILEMENU_TITLE_BAR_TOOLTIP_WIDTH = "min-width: %1px; width: %2px;"; static const char* s_STR_FILEMENU_TITLE_BAR_TOOLTIP_HEIGHT = "min-height: %1px; height: %2px; max-height: %3px;"; // The delimiter to use to join and split a string of option items. static const char* s_OPTIONS_LIST_DELIMITER = ";"; rgBuildSettingsViewVulkan::rgBuildSettingsViewVulkan(QWidget* pParent, const rgBuildSettingsVulkan& buildSettings, bool isGlobalSettings) : rgBuildSettingsView(pParent, isGlobalSettings), m_initialSettings(buildSettings) { // Setup the UI. ui.setupUi(this); // Set the background to white. QPalette pal = palette(); pal.setColor(QPalette::Background, Qt::white); this->setAutoFillBackground(true); this->setPalette(pal); // Create the include directories editor view. m_pIncludeDirectoriesView = new rgIncludeDirectoriesView(s_OPTIONS_LIST_DELIMITER, this); // Create the preprocessor directives editor dialog. m_pPreprocessorDirectivesDialog = new rgPreprocessorDirectivesDialog(s_OPTIONS_LIST_DELIMITER, this); // Connect the signals. ConnectSignals(); // Connect focus in/out events for all of the line edits. ConnectLineEditFocusEvents(); // Connect clicked events for check boxes. ConnectCheckBoxClickedEvents(); // Initialize the UI based on the incoming build settings. PushToWidgets(buildSettings); // Initialize the command line preview text. UpdateCommandLineText(); // Set tooltips for general items. ui.targetGPUsLabel->setToolTip(STR_BUILD_SETTINGS_TARGET_GPUS_TOOLTIP); ui.predefinedMacrosLabel->setToolTip(STR_BUILD_SETTINGS_PREDEFINED_MACROS_TOOLTIP); ui.includeDirectoriesLabel->setToolTip(STR_BUILD_SETTINGS_ADDITIONAL_INC_DIRECTORY_TOOLTIP); // Set tooltip for Vulkan runtime section. ui.vulkanOptionsHeaderLabel->setToolTip(STR_BUILD_SETTINGS_VULKAN_RUNTIME_TOOLTIP); // Set tooltip for ICD location item. ui.ICDLocationLabel->setToolTip(CLI_OPT_ICD_DESCRIPTION); // Set tooltips for alternative compiler (glslang) component. // Use the same tooltip for both the title and the item purposely. ui.alternativeCompilerHeaderLabel->setToolTip(STR_BUILD_SETTINGS_ALTERNATIVE_COMPILER_GLSLANG_TOOLTIP); ui.glslangOptionsLabel->setToolTip(CLI_OPT_GLSLANG_OPT_DESCRIPTION_A); ui.compilerBinariesLabel->setToolTip(CLI_DESC_ALTERNATIVE_VK_BIN_FOLDER); // Set tooltip for the General section. ui.generalHeaderLabel->setToolTip(STR_BUILD_SETTINGS_GENERAL_TOOLTIP); // Set the tooltip for the command line section of the build settings. ui.settingsCommandLineHeaderLabel->setToolTip(STR_BUILD_SETTINGS_CMD_LINE_TOOLTIP); // Set the mouse cursor to the pointing hand cursor for various widgets. SetCursor(); // Set the event filter for "All Options" text edit. ui.allOptionsTextEdit->installEventFilter(this); // Hide HLSL options for now. HideHLSLOptions(); } void rgBuildSettingsViewVulkan::HideHLSLOptions() { // Hide HLSL options for now. ui.vulkanOptionsHeaderLabel->hide(); ui.generateDebugInfoCheckBox->hide(); ui.generateDebugInfoLabel->hide(); ui.noExplicitBindingsCheckBox->hide(); ui.noExplicitBindingsLabel->hide(); ui.useHLSLBlockOffsetsCheckBox->hide(); ui.useHLSLBlockOffsetsLabel->hide(); ui.useHLSLIOMappingCheckBox->hide(); ui.useHLSLIOMappingLabel->hide(); } void rgBuildSettingsViewVulkan::ConnectCheckBoxClickedEvents() { bool isConnected = false; isConnected = connect(ui.generateDebugInfoCheckBox, &rgCheckBox::clicked, this, &rgBuildSettingsViewVulkan::HandleCheckBoxClickedEvent); assert(isConnected); isConnected = connect(ui.noExplicitBindingsCheckBox, &rgCheckBox::clicked, this, &rgBuildSettingsViewVulkan::HandleCheckBoxClickedEvent); assert(isConnected); isConnected = connect(ui.useHLSLBlockOffsetsCheckBox, &rgCheckBox::clicked, this, &rgBuildSettingsViewVulkan::HandleCheckBoxClickedEvent); assert(isConnected); isConnected = connect(ui.useHLSLIOMappingCheckBox, &rgCheckBox::clicked, this, &rgBuildSettingsViewVulkan::HandleCheckBoxClickedEvent); assert(isConnected); isConnected = connect(ui.enableValidationLayersCheckBox, &rgCheckBox::clicked, this, &rgBuildSettingsViewVulkan::HandleCheckBoxClickedEvent); assert(isConnected); } // Make the UI reflect the values in the supplied settings struct. void rgBuildSettingsViewVulkan::PushToWidgets(const rgBuildSettingsVulkan& settings) { // Disable any signals from the widgets while they're being populated. QSignalBlocker signalBlockerTargetGPUsLineEdit(ui.targetGPUsLineEdit); QSignalBlocker signalBlockerPredefinedMacrosLineEdit(ui.predefinedMacrosLineEdit); QSignalBlocker signalBlockerIncludeDirectoriesLineEdit(ui.includeDirectoriesLineEdit); QSignalBlocker signalBlockerGenerateDebugInfoCheckBox(ui.generateDebugInfoCheckBox); QSignalBlocker signalBlockerNoExplicitBindingsCheckBox(ui.noExplicitBindingsCheckBox); QSignalBlocker signalBlockerUseHLSLBlockOffsetsCheckBox(ui.useHLSLBlockOffsetsCheckBox); QSignalBlocker signalBlockerUseHLSLIOMappingCheckBox(ui.useHLSLIOMappingCheckBox); QSignalBlocker signalBlockerEnableValidationLayersCheckBox(ui.enableValidationLayersCheckBox); QSignalBlocker signalBlockerICDLocationLineEdit(ui.ICDLocationLineEdit); QSignalBlocker signalBlockerGlslangOptionsLineEdit(ui.glslangOptionsLineEdit); QSignalBlocker signalBlockerCompilerBinariesLineEdit(ui.compilerBinariesLineEdit); QSignalBlocker signalBlockerOutputFileBinaryNameLineEdit(ui.outputFileBinaryNameLineEdit); // The items below are common build settings for all API types. QString targetGpusList(rgUtils::BuildSemicolonSeparatedStringList(settings.m_targetGpus).c_str()); ui.targetGPUsLineEdit->setText(targetGpusList); QString predefinedMacros(rgUtils::BuildSemicolonSeparatedStringList(settings.m_predefinedMacros).c_str()); ui.predefinedMacrosLineEdit->setText(predefinedMacros); QString additionalIncludeDirs(rgUtils::BuildSemicolonSeparatedStringList(settings.m_additionalIncludeDirectories).c_str()); ui.includeDirectoriesLineEdit->setText(additionalIncludeDirs); // Items below are Vulkan-specific build settings only. ui.generateDebugInfoCheckBox->setChecked(settings.m_isGenerateDebugInfoChecked); ui.noExplicitBindingsCheckBox->setChecked(settings.m_isNoExplicitBindingsChecked); ui.useHLSLBlockOffsetsCheckBox->setChecked(settings.m_isUseHlslBlockOffsetsChecked); ui.useHLSLIOMappingCheckBox->setChecked(settings.m_isUseHlslIoMappingChecked); ui.enableValidationLayersCheckBox->setChecked(settings.m_isEnableValidationLayersChecked); ui.ICDLocationLineEdit->setText(QString::fromStdString(settings.m_ICDLocation)); ui.glslangOptionsLineEdit->setText(QString::fromStdString(settings.m_glslangOptions)); ui.compilerBinariesLineEdit->setText(QString::fromStdString(std::get<CompilerFolderType::Bin>(settings.m_compilerPaths))); // Output binary file name. ui.outputFileBinaryNameLineEdit->setText(settings.m_binaryFileName.c_str()); } rgBuildSettingsVulkan rgBuildSettingsViewVulkan::PullFromWidgets() const { rgBuildSettingsVulkan settings; // Target GPUs. std::vector<std::string> targetGPUsVector; const std::string& commaSeparatedTargetGPUs = ui.targetGPUsLineEdit->text().toStdString(); rgUtils::splitString(commaSeparatedTargetGPUs, rgConfigManager::RGA_LIST_DELIMITER, targetGPUsVector); settings.m_targetGpus = targetGPUsVector; // Predefined Macros. std::vector<std::string> predefinedMacrosVector; const std::string& commaSeparatedPredefinedMacros = ui.predefinedMacrosLineEdit->text().toStdString(); rgUtils::splitString(commaSeparatedPredefinedMacros, rgConfigManager::RGA_LIST_DELIMITER, predefinedMacrosVector); settings.m_predefinedMacros = predefinedMacrosVector; // Additional Include Directories. std::vector<std::string> additionalIncludeDirectoriesVector; const std::string& commaSeparatedAdditionalIncludeDirectories = ui.includeDirectoriesLineEdit->text().toStdString(); rgUtils::splitString(commaSeparatedAdditionalIncludeDirectories, rgConfigManager::RGA_LIST_DELIMITER, additionalIncludeDirectoriesVector); settings.m_additionalIncludeDirectories = additionalIncludeDirectoriesVector; // Vulkan-specific settings. settings.m_isGenerateDebugInfoChecked = ui.generateDebugInfoCheckBox->isChecked(); settings.m_isNoExplicitBindingsChecked = ui.noExplicitBindingsCheckBox->isChecked(); settings.m_isUseHlslBlockOffsetsChecked = ui.useHLSLBlockOffsetsCheckBox->isChecked(); settings.m_isUseHlslIoMappingChecked = ui.useHLSLIOMappingCheckBox->isChecked(); settings.m_isEnableValidationLayersChecked = ui.enableValidationLayersCheckBox->isChecked(); settings.m_ICDLocation = ui.ICDLocationLineEdit->text().toStdString(); settings.m_glslangOptions = ui.glslangOptionsLineEdit->text().toStdString(); std::get<CompilerFolderType::Bin>(settings.m_compilerPaths) = ui.compilerBinariesLineEdit->text().toStdString(); // Binary output file name. settings.m_binaryFileName = ui.outputFileBinaryNameLineEdit->text().toStdString(); return settings; } void rgBuildSettingsViewVulkan::ConnectSignals() { // Add target GPU button. bool isConnected = connect(this->ui.addTargetGPUsButton, &QPushButton::clicked, this, &rgBuildSettingsViewVulkan::HandleAddTargetGpusButtonClick); assert(isConnected); // Add include directories editor dialog button. isConnected = connect(this->ui.includeDirsBrowseButton, &QPushButton::clicked, this, &rgBuildSettingsViewVulkan::HandleIncludeDirsBrowseButtonClick); assert(isConnected); // Add preprocessor directives editor dialog button. isConnected = connect(this->ui.predefinedMacrosBrowseButton, &QPushButton::clicked, this, &rgBuildSettingsViewVulkan::HandlePreprocessorDirectivesBrowseButtonClick); assert(isConnected); // Connect all textboxes within the view. isConnected = connect(this->ui.targetGPUsLineEdit, &QLineEdit::textChanged, this, &rgBuildSettingsViewVulkan::HandleTextEditChanged); assert(isConnected); // Handle changes to the Predefined Macros setting. isConnected = connect(this->ui.predefinedMacrosLineEdit, &QLineEdit::textChanged, this, &rgBuildSettingsViewVulkan::HandleTextEditChanged); assert(isConnected); // Handle changes to the Include Directories setting. isConnected = connect(this->ui.includeDirectoriesLineEdit, &QLineEdit::textChanged, this, &rgBuildSettingsViewVulkan::HandleTextEditChanged); assert(isConnected); // Connect the include directory editor dialog's "OK" button click. isConnected = connect(m_pIncludeDirectoriesView, &rgIncludeDirectoriesView::OKButtonClicked, this, &rgBuildSettingsViewVulkan::HandleIncludeDirsUpdated); assert(isConnected); // Connect the preprocessor directives editor dialog's "OK" button click. isConnected = connect(m_pPreprocessorDirectivesDialog, &rgPreprocessorDirectivesDialog::OKButtonClicked, this, &rgBuildSettingsViewVulkan::HandlePreprocessorDirectivesUpdated); assert(isConnected); // Handle changes to the Generate Debug Info checkbox. isConnected = connect(this->ui.generateDebugInfoCheckBox, &rgCheckBox::stateChanged, this, &rgBuildSettingsViewVulkan::HandleCheckboxStateChanged); assert(isConnected); // Handle changes to the No Explicit Bindings checkbox. isConnected = connect(this->ui.noExplicitBindingsCheckBox, &rgCheckBox::stateChanged, this, &rgBuildSettingsViewVulkan::HandleCheckboxStateChanged); assert(isConnected); // Handle changes to the Use HLSL Block Offsets checkbox. isConnected = connect(this->ui.useHLSLBlockOffsetsCheckBox, &rgCheckBox::stateChanged, this, &rgBuildSettingsViewVulkan::HandleCheckboxStateChanged); assert(isConnected); // Handle changes to the Use HLSL IO Mapping checkbox. isConnected = connect(this->ui.useHLSLIOMappingCheckBox, &rgCheckBox::stateChanged, this, &rgBuildSettingsViewVulkan::HandleCheckboxStateChanged); assert(isConnected); // Handle changes to the Enable Validation Layers checkbox. isConnected = connect(this->ui.enableValidationLayersCheckBox, &rgCheckBox::stateChanged, this, &rgBuildSettingsViewVulkan::HandleCheckboxStateChanged); assert(isConnected); // Handle clicking of ICD location browse button. isConnected = connect(this->ui.ICDLocationBrowseButton, &QPushButton::clicked, this, &rgBuildSettingsViewVulkan::HandleICDLocationBrowseButtonClick); assert(isConnected); // Handle changes to the ICD location line edit. isConnected = connect(this->ui.ICDLocationLineEdit, &QLineEdit::textChanged, this, &rgBuildSettingsViewVulkan::HandleICDLocationLineEditChanged); assert(isConnected); // Handle changes to the glslang options line edit. isConnected = connect(this->ui.glslangOptionsLineEdit, &QLineEdit::textChanged, this, &rgBuildSettingsViewVulkan::HandleGlslangOptionsLineEditChanged); assert(isConnected); // Handle clicking of the Alternative Compiler path browse button. isConnected = connect(this->ui.compilerBrowseButton, &QPushButton::clicked, this, &rgBuildSettingsViewVulkan::HandleAlternativeCompilerBrowseButtonClicked); assert(isConnected); // Handle changes to the Alternative Compiler path line edit. isConnected = connect(this->ui.compilerBinariesLineEdit, &QLineEdit::textChanged, this, &rgBuildSettingsViewVulkan::HandleAlternativeCompilerLineEditChanged); assert(isConnected); // Binary Output File name textChanged signal. isConnected = connect(this->ui.outputFileBinaryNameLineEdit, &QLineEdit::textChanged, this, &rgBuildSettingsViewVulkan::HandleOutputBinaryEditBoxChanged); assert(isConnected); // Binary Output File name editingFinished signal. isConnected = connect(this->ui.outputFileBinaryNameLineEdit, &QLineEdit::editingFinished, this, &rgBuildSettingsViewVulkan::HandleOutputBinaryFileEditingFinished); assert(isConnected); } void rgBuildSettingsViewVulkan::HandleOutputBinaryFileEditingFinished() { // Verify that the output binary file text is not empty before losing the focus. if (this->ui.outputFileBinaryNameLineEdit->text().trimmed().isEmpty() || !rgUtils::IsValidFileName(ui.outputFileBinaryNameLineEdit->text().toStdString())) { // Initialize the binary output file name edit line. std::shared_ptr<rgBuildSettings> pDefaultSettings = rgConfigManager::Instance().GetUserGlobalBuildSettings(rgProjectAPI::Vulkan); auto pVkDefaultSettings = std::dynamic_pointer_cast<rgBuildSettingsVulkan>(pDefaultSettings); assert(pVkDefaultSettings != nullptr); if (pVkDefaultSettings != nullptr) { this->ui.outputFileBinaryNameLineEdit->setText(pVkDefaultSettings->m_binaryFileName.c_str()); } this->ui.outputFileBinaryNameLineEdit->setFocus(); } // Signal to any listeners that the values in the UI have changed. HandlePendingChangesStateChanged(GetHasPendingChanges()); // Update the command line preview text. UpdateCommandLineText(); } void rgBuildSettingsViewVulkan::HandleOutputBinaryEditBoxChanged(const QString& text) { // Update the tooltip. ui.outputFileBinaryNameLineEdit->setToolTip(text); // Restore the cursor to the original position when the text has changed. QtCommon::QtUtil::RestoreCursorPosition cursorPosition(ui.outputFileBinaryNameLineEdit); // Signal to any listeners that the values in the UI have changed. HandlePendingChangesStateChanged(GetHasPendingChanges()); // Update the command line preview text. UpdateCommandLineText(); } void rgBuildSettingsViewVulkan::HandleICDLocationBrowseButtonClick(bool /* checked */) { QString selectedFile = QFileDialog::getOpenFileName(this, tr(STR_ICD_LOCATION_DIALOG_SELECT_FILE_TITLE), ui.ICDLocationLineEdit->text(), tr(STR_DIALOG_FILTER_ICD)); if (!selectedFile.isEmpty()) { ui.ICDLocationLineEdit->setText(selectedFile); // Inform the UI of a possible change to the pending state. HandlePendingChangesStateChanged(GetHasPendingChanges()); // Update the command line preview text. UpdateCommandLineText(); } } void rgBuildSettingsViewVulkan::HandleICDLocationLineEditChanged(const QString& text) { // Restore the cursor to the original position when the text has changed. QtCommon::QtUtil::RestoreCursorPosition cursorPosition(ui.ICDLocationLineEdit); // Set the text value. ui.ICDLocationLineEdit->setText(text); // Inform the UI of a possible change to the pending state. HandlePendingChangesStateChanged(GetHasPendingChanges()); // Update the command line preview text. UpdateCommandLineText(); } void rgBuildSettingsViewVulkan::HandleGlslangOptionsLineEditChanged(const QString& text) { // Restore the cursor to the original position when the text has changed. QtCommon::QtUtil::RestoreCursorPosition cursorPosition(ui.glslangOptionsLineEdit); // Set the text value. ui.glslangOptionsLineEdit->setText(text); // Inform the UI of a possible change to the pending state. HandlePendingChangesStateChanged(GetHasPendingChanges()); // Update the command line preview text. UpdateCommandLineText(); } void rgBuildSettingsViewVulkan::HandleAlternativeCompilerBrowseButtonClicked() { QFileDialog fileDialog; QLineEdit* pLineEdit = ui.compilerBinariesLineEdit; assert(pLineEdit != nullptr); if (pLineEdit != nullptr) { QString currentDir = (pLineEdit->text().isEmpty() ? QString::fromStdString(rgConfigManager::Instance().GetLastSelectedFolder()) : pLineEdit->text()); QString selectedDirectory = QFileDialog::getExistingDirectory(this, tr(STR_INCLUDE_DIR_DIALOG_SELECT_DIR_TITLE), currentDir, QFileDialog::ShowDirsOnly); if (!selectedDirectory.isEmpty()) { ui.compilerBinariesLineEdit->setText(selectedDirectory); // Inform the UI of a possible change to the pending state. HandlePendingChangesStateChanged(GetHasPendingChanges()); // Update the command line preview text. UpdateCommandLineText(); } } } void rgBuildSettingsViewVulkan::HandleAlternativeCompilerLineEditChanged(const QString& text) { // Restore the cursor to the original position when the text has changed. QtCommon::QtUtil::RestoreCursorPosition cursorPosition(ui.compilerBinariesLineEdit); // Set the text value. ui.compilerBinariesLineEdit->setText(text); // Inform the UI of a possible change to the pending state. HandlePendingChangesStateChanged(GetHasPendingChanges()); // Update the command line preview text. UpdateCommandLineText(); } void rgBuildSettingsViewVulkan::ConnectLineEditFocusEvents() { bool isConnected = false; isConnected = connect(this->ui.includeDirectoriesLineEdit, &rgLineEdit::LineEditFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusInEvent); assert(isConnected); isConnected = connect(this->ui.includeDirectoriesLineEdit, &rgLineEdit::LineEditFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusOutEvent); assert(isConnected); isConnected = connect(this->ui.predefinedMacrosLineEdit, &rgLineEdit::LineEditFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusInEvent); assert(isConnected); isConnected = connect(this->ui.predefinedMacrosLineEdit, &rgLineEdit::LineEditFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusOutEvent); assert(isConnected); isConnected = connect(this->ui.targetGPUsLineEdit, &rgLineEdit::LineEditFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusInEvent); assert(isConnected); isConnected = connect(this->ui.targetGPUsLineEdit, &rgLineEdit::LineEditFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusOutEvent); assert(isConnected); isConnected = connect(this->ui.ICDLocationLineEdit, &rgLineEdit::LineEditFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusInEvent); assert(isConnected); isConnected = connect(this->ui.ICDLocationLineEdit, &rgLineEdit::LineEditFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusOutEvent); assert(isConnected); isConnected = connect(this->ui.glslangOptionsLineEdit, &rgLineEdit::LineEditFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusInEvent); assert(isConnected); isConnected = connect(this->ui.glslangOptionsLineEdit, &rgLineEdit::LineEditFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusOutEvent); assert(isConnected); isConnected = connect(this->ui.compilerBinariesLineEdit, &rgLineEdit::LineEditFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusInEvent); assert(isConnected); isConnected = connect(this->ui.compilerBinariesLineEdit, &rgLineEdit::LineEditFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleLineEditFocusOutEvent); assert(isConnected); isConnected = connect(this->ui.addTargetGPUsButton, &rgBrowseButton::BrowseButtonFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleBrowseButtonFocusInEvent); assert(isConnected); isConnected = connect(this->ui.addTargetGPUsButton, &rgBrowseButton::BrowseButtonFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleBrowseButtonFocusOutEvent); assert(isConnected); isConnected = connect(this->ui.predefinedMacrosBrowseButton, &rgBrowseButton::BrowseButtonFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleBrowseButtonFocusInEvent); assert(isConnected); isConnected = connect(this->ui.predefinedMacrosBrowseButton, &rgBrowseButton::BrowseButtonFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleBrowseButtonFocusOutEvent); assert(isConnected); isConnected = connect(this->ui.includeDirsBrowseButton, &rgBrowseButton::BrowseButtonFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleBrowseButtonFocusInEvent); assert(isConnected); isConnected = connect(this->ui.includeDirsBrowseButton, &rgBrowseButton::BrowseButtonFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleBrowseButtonFocusOutEvent); assert(isConnected); isConnected = connect(this->ui.ICDLocationBrowseButton, &rgBrowseButton::BrowseButtonFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleBrowseButtonFocusInEvent); assert(isConnected); isConnected = connect(this->ui.ICDLocationBrowseButton, &rgBrowseButton::BrowseButtonFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleBrowseButtonFocusOutEvent); assert(isConnected); isConnected = connect(this->ui.compilerBrowseButton, &rgBrowseButton::BrowseButtonFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleBrowseButtonFocusInEvent); assert(isConnected); isConnected = connect(this->ui.compilerBrowseButton, &rgBrowseButton::BrowseButtonFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleBrowseButtonFocusOutEvent); assert(isConnected); isConnected = connect(this->ui.enableValidationLayersCheckBox, &rgCheckBox::CheckBoxFocusInEvent, this, &rgBuildSettingsViewVulkan::HandleCheckBoxFocusInEvent); assert(isConnected); isConnected = connect(this->ui.enableValidationLayersCheckBox, &rgCheckBox::CheckBoxFocusOutEvent, this, &rgBuildSettingsViewVulkan::HandleCheckBoxFocusOutEvent); assert(isConnected); } void rgBuildSettingsViewVulkan::HandleAddTargetGpusButtonClick() { // Set the frame border color to red. emit SetFrameBorderRedSignal(); // Trim out any spaces within the target GPUs string. QString selectedGPUs = this->ui.targetGPUsLineEdit->text(); // Create a new Target GPU Selection dialog instance. m_pTargetGpusDialog = new rgTargetGpusDialog(selectedGPUs, this); // Register the target gpu dialog box with the scaling manager. ScalingManager::Get().RegisterObject(m_pTargetGpusDialog); // Center the dialog on the view (registering with the scaling manager // shifts it out of the center so we need to manually center it). rgUtils::CenterOnWidget(m_pTargetGpusDialog, this); // Present the dialog to the user. m_pTargetGpusDialog->setModal(true); int dialogResult = m_pTargetGpusDialog->exec(); // If the user clicked "OK", extract the Checked items into a comma-separated string, // and put the string in the Target GPUs textbox. if (dialogResult == 1) { // After the dialog is hidden, extract the list of families selected by the user. std::vector<std::string> selectedFamilies = m_pTargetGpusDialog->GetSelectedCapabilityGroups(); // Remove gfx notation if needed. std::transform(selectedFamilies.begin(), selectedFamilies.end(), selectedFamilies.begin(), [&](std::string& family) { return rgUtils::RemoveGfxNotation(family); }); // Create a comma-separated list of GPU families that the user selected. std::stringstream familyListString; size_t numFamilies = selectedFamilies.size(); for (size_t familyIndex = 0; familyIndex < numFamilies; ++familyIndex) { // Append the family name to the string. familyListString << selectedFamilies[familyIndex]; // Append a comma between each family name, until the last one. if ((familyIndex + 1) < numFamilies) { familyListString << rgConfigManager::RGA_LIST_DELIMITER; } } // Set the target GPUs text. ui.targetGPUsLineEdit->setText(familyListString.str().c_str()); // Inform the UI of a possible change to the pending state. HandlePendingChangesStateChanged(GetHasPendingChanges()); } } void rgBuildSettingsViewVulkan::HandleTextEditChanged() { // Determine which control's text has been updated. QLineEdit* pLineEdit = static_cast<QLineEdit*>(QObject::sender()); assert(pLineEdit != nullptr); if (pLineEdit != nullptr) { // Inform the UI of a possible change to the pending state. HandlePendingChangesStateChanged(GetHasPendingChanges()); // Update the command line preview text. UpdateCommandLineText(); } } std::string rgBuildSettingsViewVulkan::GetTitleString() { std::stringstream titleString; // Build the title string. if (m_isGlobalSettings) { // For the global settings. titleString << STR_BUILD_SETTINGS_DEFAULT_TITLE; titleString << " "; titleString << STR_API_NAME_VULKAN; titleString << " "; } else { // For project-specific settings. titleString << STR_BUILD_SETTINGS_PROJECT_TITLE; titleString << " "; } titleString << STR_MENU_BUILD_SETTINGS_LOWER; return titleString.str(); } const std::string rgBuildSettingsViewVulkan::GetTitleTooltipString() const { std::stringstream tooltipString; if (m_isGlobalSettings) { tooltipString << STR_BUILD_SETTINGS_GLOBAL_TOOLTIP_A; tooltipString << STR_API_NAME_VULKAN; tooltipString << STR_BUILD_SETTINGS_GLOBAL_TOOLTIP_B; } else { tooltipString << STR_BUILD_SETTINGS_PROJECT_TOOLTIP_A; tooltipString << STR_API_NAME_VULKAN; tooltipString << STR_BUILD_SETTINGS_PROJECT_TOOLTIP_B; } return tooltipString.str(); } void rgBuildSettingsViewVulkan::UpdateCommandLineText() { rgBuildSettingsVulkan apiBuildSetting = PullFromWidgets(); // Generate a command line string from the build settings structure. std::string buildSettings; bool ret = rgCliUtils::GenerateVulkanBuildSettingsString(apiBuildSetting, buildSettings); assert(ret); if (ret) { ui.allOptionsTextEdit->setPlainText(buildSettings.c_str()); } } void rgBuildSettingsViewVulkan::HandlePendingChangesStateChanged(bool hasPendingChanges) { // Let the base class determine if there is a need to signal listeners // about the pending changes state. rgBuildSettingsView::SetHasPendingChanges(hasPendingChanges); } bool rgBuildSettingsViewVulkan::IsTargetGpusStringValid(std::vector<std::string>& errors) const { bool isValid = true; // The target GPUs string must be non-empty. std::string targetGpusString = ui.targetGPUsLineEdit->text().toStdString(); if (targetGpusString.empty()) { // The Target GPUs field is invalid since it is empty. errors.push_back(STR_ERR_TARGET_GPUS_CANNOT_BE_EMPTY); isValid = false; } else { // Split the comma-separated GPUs string. std::vector<std::string> targetGPUsVector; rgUtils::splitString(targetGpusString, rgConfigManager::RGA_LIST_DELIMITER, targetGPUsVector); // Use the Config Manager to verify that the specified GPUs are valid. std::vector<std::string> invalidGpus; rgConfigManager& configManager = rgConfigManager::Instance(); for (const std::string& targetGpuFamilyName : targetGPUsVector) { std::string trimmedName; rgUtils::TrimLeadingAndTrailingWhitespace(targetGpuFamilyName, trimmedName); // Is the given target GPU family name supported? if (!configManager.IsGpuFamilySupported(trimmedName)) { // Add the GPU to a list of invalid names if it's not supported. invalidGpus.push_back(trimmedName); } } if (!invalidGpus.empty()) { // Build an error string indicating the invalid GPUs. std::stringstream errorStream; errorStream << STR_ERR_INVALID_GPUS_SPECIFIED; int numInvalid = static_cast<int>(invalidGpus.size()); for (int gpuIndex = 0; gpuIndex < numInvalid; ++gpuIndex) { errorStream << invalidGpus[gpuIndex]; if (gpuIndex != (numInvalid - 1)) { errorStream << ", "; } } // Add an error indicating that the GPU name is invalid. errors.push_back(errorStream.str()); isValid = false; } } return isValid; } bool rgBuildSettingsViewVulkan::ValidatePendingSettings() { std::vector<std::string> errorFields; bool isValid = IsTargetGpusStringValid(errorFields); if (!isValid) { std::stringstream errorStream; errorStream << STR_ERR_INVALID_PENDING_SETTING; errorStream << std::endl; // Loop through all errors and append them to the stream. for (const std::string error : errorFields) { errorStream << error; errorStream << std::endl; } // Display an error message box to the user telling them what to fix. rgUtils::ShowErrorMessageBox(errorStream.str().c_str(), this); } return isValid; } void rgBuildSettingsViewVulkan::SetCursor() { // Set the cursor for buttons to pointing hand cursor. ui.addTargetGPUsButton->setCursor(Qt::PointingHandCursor); ui.includeDirsBrowseButton->setCursor(Qt::PointingHandCursor); ui.predefinedMacrosBrowseButton->setCursor(Qt::PointingHandCursor); ui.ICDLocationBrowseButton->setCursor(Qt::PointingHandCursor); ui.compilerBrowseButton->setCursor(Qt::PointingHandCursor); // Set the cursor for check boxes to pointing hand cursor. ui.generateDebugInfoCheckBox->setCursor(Qt::PointingHandCursor); ui.noExplicitBindingsCheckBox->setCursor(Qt::PointingHandCursor); ui.useHLSLBlockOffsetsCheckBox->setCursor(Qt::PointingHandCursor); ui.useHLSLIOMappingCheckBox->setCursor(Qt::PointingHandCursor); ui.enableValidationLayersCheckBox->setCursor(Qt::PointingHandCursor); } void rgBuildSettingsViewVulkan::HandleIncludeDirsBrowseButtonClick() { // Set the frame border color to red. emit SetFrameBorderRedSignal(); // Position the window in the middle of the screen. m_pIncludeDirectoriesView->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, m_pIncludeDirectoriesView->size(), qApp->desktop()->availableGeometry())); // Set the current include dirs. m_pIncludeDirectoriesView->SetListItems(ui.includeDirectoriesLineEdit->text()); // Show the window. m_pIncludeDirectoriesView->exec(); } void rgBuildSettingsViewVulkan::HandleIncludeDirsUpdated(QStringList includeDirs) { QString includeDirsText; // Create a delimiter-separated string. if (!includeDirs.isEmpty()) { includeDirsText = includeDirs.join(s_OPTIONS_LIST_DELIMITER); } // Update the text box. ui.includeDirectoriesLineEdit->setText(includeDirsText); // Inform the rest of the UI that the settings have been changed. HandlePendingChangesStateChanged(GetHasPendingChanges()); } void rgBuildSettingsViewVulkan::HandlePreprocessorDirectivesBrowseButtonClick() { // Set the frame border color to red. emit SetFrameBorderRedSignal(); // Position the window in the middle of the screen. m_pPreprocessorDirectivesDialog->setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, m_pPreprocessorDirectivesDialog->size(), qApp->desktop()->availableGeometry())); // Set the current preprocessor directives in the dialog. m_pPreprocessorDirectivesDialog->SetListItems(ui.predefinedMacrosLineEdit->text()); // Show the dialog. m_pPreprocessorDirectivesDialog->exec(); } void rgBuildSettingsViewVulkan::HandlePreprocessorDirectivesUpdated(QStringList preprocessorDirectives) { QString preprocessorDirectivesText; // Create a delimiter-separated string. if (!preprocessorDirectives.isEmpty()) { preprocessorDirectivesText = preprocessorDirectives.join(s_OPTIONS_LIST_DELIMITER); } // Update the text box. ui.predefinedMacrosLineEdit->setText(preprocessorDirectivesText); // Inform the rest of the UI that the settings have been changed. HandlePendingChangesStateChanged(GetHasPendingChanges()); } void rgBuildSettingsViewVulkan::HandleLineEditFocusInEvent() { emit SetFrameBorderRedSignal(); } void rgBuildSettingsViewVulkan::HandleLineEditFocusOutEvent() { emit SetFrameBorderBlackSignal(); } void rgBuildSettingsViewVulkan::HandleBrowseButtonFocusInEvent() { emit SetFrameBorderRedSignal(); } void rgBuildSettingsViewVulkan::HandleBrowseButtonFocusOutEvent() { emit SetFrameBorderBlackSignal(); } void rgBuildSettingsViewVulkan::HandleCheckBoxFocusInEvent() { emit SetFrameBorderRedSignal(); } void rgBuildSettingsViewVulkan::HandleCheckBoxFocusOutEvent() { emit SetFrameBorderBlackSignal(); } void rgBuildSettingsViewVulkan::HandleCheckBoxClickedEvent() { emit SetFrameBorderRedSignal(); } void rgBuildSettingsViewVulkan::HandleCheckboxStateChanged() { // Make sure it was a checkbox that caused this state change (just to be sure). QCheckBox* pCheckBox = static_cast<QCheckBox*>(QObject::sender()); assert(pCheckBox != nullptr); if (pCheckBox != nullptr) { // Inform the UI of a possible change to the pending state. HandlePendingChangesStateChanged(GetHasPendingChanges()); // Update the command line preview text. UpdateCommandLineText(); } } bool rgBuildSettingsViewVulkan::GetHasPendingChanges() const { rgBuildSettingsVulkan currentSettings = PullFromWidgets(); bool hasChanges = !m_initialSettings.HasSameSettings(currentSettings); return hasChanges; } bool rgBuildSettingsViewVulkan::RevertPendingChanges() { PushToWidgets(m_initialSettings); // Make sure the rest of the UI knows that the settings don't need to be saved. HandlePendingChangesStateChanged(false); return false; } void rgBuildSettingsViewVulkan::RestoreDefaultSettings() { bool isRestored = false; if (m_isGlobalSettings) { // If this is for the global settings, then restore to the hard-coded defaults. // Get the hardcoded default build settings. std::shared_ptr<rgBuildSettings> pDefaultBuildSettings = rgConfigManager::GetDefaultBuildSettings(rgProjectAPI::Vulkan); std::shared_ptr<rgBuildSettingsVulkan> pApiBuildSettings = std::dynamic_pointer_cast<rgBuildSettingsVulkan>(pDefaultBuildSettings); assert(pApiBuildSettings != nullptr); if (pApiBuildSettings != nullptr) { // Reset our initial settings back to the defaults. m_initialSettings = *pApiBuildSettings; // Update the UI to reflect the new initial settings. PushToWidgets(m_initialSettings); // Update the ConfigManager to use the new settings. rgConfigManager::Instance().SetApiBuildSettings(STR_API_NAME_VULKAN, &m_initialSettings); // Save the settings file. isRestored = rgConfigManager::Instance().SaveGlobalConfigFile(); // Inform the rest of the UI that the settings have been changed. HandlePendingChangesStateChanged(GetHasPendingChanges()); } } else { // This view is showing project-specific settings, so restore back to the stored settings in the project. std::shared_ptr<rgBuildSettings> pDefaultSettings = rgConfigManager::Instance().GetUserGlobalBuildSettings(rgProjectAPI::Vulkan); auto pVkDefaultSettings = std::dynamic_pointer_cast<rgBuildSettingsVulkan>(pDefaultSettings); m_initialSettings = *pVkDefaultSettings; PushToWidgets(m_initialSettings); // Inform the rest of the UI that the settings have been changed. HandlePendingChangesStateChanged(GetHasPendingChanges()); // Let the rgBuildView know that the build settings have been updated. emit ProjectBuildSettingsSaved(pVkDefaultSettings); isRestored = true; } // Show an error dialog if the settings failed to be reset. if (!isRestored) { rgUtils::ShowErrorMessageBox(STR_ERR_CANNOT_RESTORE_DEFAULT_SETTINGS, this); } } bool rgBuildSettingsViewVulkan::SaveSettings() { bool canBeSaved = ValidatePendingSettings(); if (canBeSaved) { // Reset the initial settings to match what the UI shows. m_initialSettings = PullFromWidgets(); if (m_isGlobalSettings) { // Update the config manager to use these new settings. rgConfigManager& configManager = rgConfigManager::Instance(); configManager.SetApiBuildSettings(STR_API_NAME_VULKAN, &m_initialSettings); // Save the global config settings. canBeSaved = configManager.SaveGlobalConfigFile(); } else { // Save the project settings. std::shared_ptr<rgBuildSettingsVulkan> pTmpPtr = std::make_shared<rgBuildSettingsVulkan>(m_initialSettings); emit ProjectBuildSettingsSaved(pTmpPtr); } if (canBeSaved) { // Make sure the rest of the UI knows that the settings have been saved. HandlePendingChangesStateChanged(false); } } // Set focus to target GPUs browse button. ui.addTargetGPUsButton->setFocus(); return canBeSaved; } void rgBuildSettingsViewVulkan::mousePressEvent(QMouseEvent* pEvent) { Q_UNUSED(pEvent); emit SetFrameBorderRedSignal(); } bool rgBuildSettingsViewVulkan::eventFilter(QObject* pObject, QEvent* pEvent) { // Intercept events for "All Options" widget. if (pEvent != nullptr) { if (pEvent->type() == QEvent::FocusIn) { HandleLineEditFocusInEvent(); } else if (pEvent->type() == QEvent::FocusOut) { HandleLineEditFocusOutEvent(); } } // Continue default processing. return QObject::eventFilter(pObject, pEvent); } void rgBuildSettingsViewVulkan::SetInitialWidgetFocus() { ui.addTargetGPUsButton->setFocus(); }
GPUOpen-Tools/RGA
RadeonGPUAnalyzerGUI/Src/rgBuildSettingsViewVulkan.cpp
C++
mit
41,275
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("CurrentDateAndTime")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CurrentDateAndTime")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e9d0d198-c923-4227-a06a-ed25e74cd28b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
marianamn/Telerik-Academy-Activities
Homeworks/01. CSharp-Basics/01. Intro Programing Homework/CurrentDateAndTime/Properties/AssemblyInfo.cs
C#
mit
1,412
<?php /* PMUserBundle:Registration:register_content.html.twig */ class __TwigTemplate_f6e31e9e2fb72ad7021d9bf921bafcc5a9a3a5263216ec6875135a086381234f 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()) { // line 2 echo " <form class=\"form-horizontal\" method=\"post\" "; // line 3 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'enctype'); echo " role=\"form\"> "; // line 4 if ( !$this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "vars", array()), "valid", array())) { // line 5 echo " <div class=\"alert alert-error\"> <strong>Votre formulaire contient les erreurs suivantes :</strong> "; // line 7 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'errors'); echo " "; // line 8 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "name", array()), 'errors'); echo " "; // line 9 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "firstname", array()), 'errors'); echo " "; // line 10 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "email", array()), 'errors'); echo " "; // line 11 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "username", array()), 'errors'); echo " "; // line 12 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "plainPassword", array()), "first", array()), 'errors'); echo " "; // line 13 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "plainPassword", array()), "second", array()), 'errors'); echo " </div> <br /> "; } // line 17 echo " <fieldset> <legend>Utilisateur :</legend> <div class=\"form-group\"> "; // line 22 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "name", array()), 'label', array("label_attr" => array("class" => "col-sm-4 control-label"), "label" => "Nom, Prénom :")); echo " <div class=\"col-sm-4\"> "; // line 24 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "name", array()), 'widget', array("attr" => array("placeholder" => "Nom de l'utilisateur", "class" => "form-control"))); echo " </div> <div class=\"col-sm-4\"> "; // line 27 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "firstname", array()), 'widget', array("attr" => array("placeholder" => "Prénom", "class" => "form-control"))); echo " </div> </div> <div class=\"form-group\"> "; // line 31 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "email", array()), 'label', array("label_attr" => array("class" => "col-sm-4 control-label"), "label" => "Adresse mail :")); echo " <div class=\"col-sm-8\"> "; // line 33 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "email", array()), 'widget', array("attr" => array("placeholder" => "mail@exemple.com", "class" => "form-control"))); echo " </div> </div> <div class=\"form-group main-hide-div\"> "; // line 38 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "username", array()), 'label', array("label_attr" => array("class" => "col-sm-4 control-label"), "label" => "Nom d'utilisateur :")); echo " <div class=\"col-sm-8\"> "; // line 40 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "username", array()), 'widget', array("attr" => array("placeholder" => "Votre email : mail@exemple.com", "class" => "form-control"))); echo " </div> </div> <div class=\"form-group main-hide-div\"> "; // line 45 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "plainPassword", array()), "first", array()), 'label', array("label_attr" => array("class" => "col-sm-4 control-label"), "label" => "Mot de passe :")); echo " <div class=\"col-sm-8\"> "; // line 47 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "plainPassword", array()), "first", array()), 'widget', array("attr" => array("placeholder" => "Mot de Passe", "class" => "form-control"))); echo " </div> </div> <div class=\"form-group main-hide-div\"> "; // line 52 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "plainPassword", array()), "second", array()), 'label', array("label_attr" => array("class" => "col-sm-4 control-label"), "label" => "Vérification :")); echo " <div class=\"col-sm-8\"> "; // line 54 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock($this->getAttribute($this->getAttribute((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), "plainPassword", array()), "second", array()), 'widget', array("attr" => array("placeholder" => "Mot de Passe", "class" => "form-control"))); echo " </div> </div> </fieldset> "; // line 58 echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : $this->getContext($context, "form")), 'rest'); echo " <center><input type=\"submit\" class=\"btn btn-default\" /></center> </form>"; } public function getTemplateName() { return "PMUserBundle:Registration:register_content.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 139 => 58, 132 => 54, 127 => 52, 119 => 47, 114 => 45, 106 => 40, 101 => 38, 93 => 33, 88 => 31, 81 => 27, 75 => 24, 70 => 22, 63 => 17, 56 => 13, 52 => 12, 48 => 11, 44 => 10, 40 => 9, 36 => 8, 32 => 7, 28 => 5, 26 => 4, 22 => 3, 19 => 2,); } }
quentinl-c/Player_manager
app/cache/dev/twig/f6/e3/1e9e2fb72ad7021d9bf921bafcc5a9a3a5263216ec6875135a086381234f.php
PHP
mit
8,748
<?php class SmartWikiInitializeController { private $log; /** * Constructor */ function __construct() { # TODO: Do something or remove } /** * Do the initialize of SmartWiki * * @param boolean $showInMenu * * @return HTML output code */ public function execute($showInMenu = true) { global $wgOut, $wgUser; $sk = $wgUser->getSkin(); # Log handler $log = new SmartWikiLog(new SmartWikiString('initialize')); # HTML output $htmlOut = ''; # The initialize class $initializer = new SmartWikiInitialize(); # Call the functions to initialize everything, store the links $links_photo = $initializer->initializeFile($log); # Install the files $links_main = $initializer->initializeNamespace($log, NS_MAIN); # Install the SmartWiki main pages $links_help = $initializer->initializeNamespace($log, NS_HELP); # Install the SmartWiki help pages $links_property = $initializer->initializeNamespace($log, SMW_NS_PROPERTY); # Install the SmartWiki properties $links_template = $initializer->initializeNamespace($log, NS_TEMPLATE); # Install the SmartWiki templates $links_form = $initializer->initializeNamespace($log, SF_NS_FORM); # Install the SmartWiki forms $links_category = $initializer->initializeNamespace($log, NS_CATEGORY); # Install the SmartWiki categories $links_menu = $initializer->initializeMenu($log, $showInMenu, $links_category); # Output the initialize message and display all the links and a link to go back $htmlOut .= Xml::tags( 'h2', null, wfMsgForContent('smartwiki-initialize-title')); $htmlOut .= Xml::tags( 'p', null, wfMsgForContent('smartwiki-initialize-page')); $htmlOut .= Xml::tags( 'p', null, $log->output()); $htmlOut .= Xml::tags( 'p', null, $sk->link(Title::newFromText('SmartWiki', NS_SPECIAL), wfMsgForContent('smartwiki-back'))); # Output the HTML codes $wgOut->addHTML( $htmlOut ); } }
Mantix/SmartWiki
includes/controller/SmartWikiInitializeController.class.php
PHP
mit
1,968
package me.xwang1024.sifResExplorer.model; public class UnitSkill { }
xwang1024/SIF-Resource-Explorer
src/main/java/me/xwang1024/sifResExplorer/model/UnitSkill.java
Java
mit
77
import React from 'react'; import ReactDOM from 'react-dom'; import Layout from './layout.js'; document.addEventListener('DOMContentLoaded', () => { ReactDOM.render(<Layout />, document.getElementById('main')); });
gauravchl/react-simple-sidenav
demo/src/index.js
JavaScript
mit
218
$.fn.onEnterKey = function( closure ) { $(this).keypress( function( event ) { var code = event.keyCode ? event.keyCode : event.which; if (code == 13) { closure(); return false; } } ); } String.prototype.trunc = String.prototype.trunc || function(n){ return this.length>n ? this.substr(0,n-1)+'&hellip;' : this; };
junajan/YoutubeDownloader
public/libs/common.js
JavaScript
mit
466
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using ConverterContracts.ConversionElementsStyles; using FB2Library.Elements; using XHTMLClassLibrary.BaseElements; using XHTMLClassLibrary.BaseElements.InlineElements; using EPubLibrary.ReferenceUtils; using XHTMLClassLibrary.BaseElements.InlineElements.TextBasedElements; namespace FB2EPubConverter { internal class HRefManagerV2 { /// <summary> /// List of IDs /// </summary> private readonly Dictionary<string, IHTMLItem> _ids = new Dictionary<string, IHTMLItem>(); /// <summary> /// List of references /// </summary> private readonly Dictionary<string, List<Anchor>> _references = new Dictionary<string, List<Anchor>>(); /// <summary> /// List of references /// </summary> private readonly Dictionary<string, List<Image>> _images = new Dictionary<string, List<Image>>(); /// <summary> /// List of remapped attributes /// </summary> private readonly Dictionary<string, string> _attributesRemap = new Dictionary<string, string>(); /// <summary> /// Resets the manager to empty state, /// releases all references etc /// </summary> public void Reset() { _ids.Clear(); _references.Clear(); _attributesRemap.Clear(); _images.Clear(); } public string AddImageRefferenced(InlineImageItem item, Image img) { if (item == null) { return string.Empty; } string validName = MakeValidImageName(item.HRef); if (!_images.ContainsKey(validName)) { var entryList = new List<Image>(); _images.Add(validName, entryList); } _images[validName].Add(img); return ReferencesUtils.FormatImagePath(validName,FlatStructure); } public string AddImageRefferenced(ImageItem item, Image img) { if (item == null) { return string.Empty; } string validName = MakeValidImageName(item.HRef); if (!_images.ContainsKey(validName)) { var entryList = new List<Image>(); _images.Add(validName, entryList); } _images[validName].Add(img); return ReferencesUtils.FormatImagePath(validName, FlatStructure); } private static string MakeValidImageName(string id) { if (string.IsNullOrEmpty(id)) { return string.Empty; } string result = id; if (id.StartsWith("#") && id.Length > 1) { result = id.Substring(1); } return result; } /// <summary> /// Add used ID to the list /// </summary> /// <param name="id">Id to list as used</param> /// <param name="item">item that ID belong to</param> /// <returns>returns and registers the id if available, empty string if ID already exists</returns> public string AddIdUsed(string id,IHTMLItem item) { if (string.IsNullOrEmpty(id)) { return id; } string newid = EnsureGoodId(id); if (_ids.ContainsKey(newid)) { // we get here if in file same ID used twice // The assumption here that since the text located in FB2 main body we should not have same ID used more than once // otherwise we would not know how (and where to) go back Logger.Log.InfoFormat("item with ID {0} already defined, ignoring to avoid inconsistences", newid); return string.Empty; } _ids.Add(newid, item); return newid; } /// <summary> /// Checks if ID already used /// </summary> /// <param name="id">ID to check</param> /// <returns>true if used, false otherwise</returns> private bool IsIdUsed(string id) { if ( id.StartsWith("#") && (id.Length > 1)) { id = id.Substring(1); } if (_ids.ContainsKey(EnsureGoodId(id))) { return true; } return false; } /// <summary> /// Adds reference /// Used to add hyperlinks (anchors) from one part of the document to another /// </summary> /// <param name="reference">reference name (name of the link we going to "jump to" - href)</param> /// <param name="anchor">anchor element that contains the reference (place we "jump from")</param> public void AddReference(string reference, Anchor anchor) { if (!ReferencesUtils.IsExternalLink(reference)) // we count only "internal" references (no need for http://... ) { reference = EnsureGoodReference(reference); // make sure that reference name is valid according to HTML rules List<Anchor> list; if (!_references.ContainsKey(reference)) // if this a first time we see "jump" to this ID { list = new List<Anchor>(); //allocate new list of referenced objects _references.Add(reference, list); // add list to dictionary } else // if we already have at least one reference to this ID { list = _references[reference]; // find this ID in references dictionary } if (string.IsNullOrEmpty((string)anchor.GlobalAttributes.ID.Value)) // if anchor does not have ID already (FB2 link element does not have ID so this is just in case), we need this for backlinking { string backLink = string.Format("{0}_back", reference); // generate back link if (backLink.StartsWith("#")) // most references starts with # as part of the href linking, so we need to strip this character to get valid ID { backLink = backLink.Substring(1); } while (IsIdUsed(backLink)) { backLink += "x"; } anchor.GlobalAttributes.ID.Value = backLink; } anchor.GlobalAttributes.ID.Value = AddIdUsed((string)anchor.GlobalAttributes.ID.Value, anchor); list.Add(anchor); } } public void AddBackReference(string reference, Anchor anchor) { if (!ReferencesUtils.IsExternalLink(reference)) // we count only "internal" references (no need for http://... ) { reference = EnsureGoodReference(reference); // make sure that reference name is valid according to HTML rules List<Anchor> list; if (!_references.ContainsKey(reference)) // if this a first time we see "jump" to this ID { list = new List<Anchor>(); //allocate new list of referenced objects _references.Add(reference, list); // add list to dictionary } else // if we already have at least one reference to this ID { list = _references[reference]; // find this ID in references dictionarry } list.Add(anchor); } } /// <summary> /// Ensures that all IDs are valid /// This still require remapping the references to updated IDs /// </summary> /// <param name="id"></param> /// <returns></returns> public string EnsureGoodId(string id) { if (id == null) { return ""; } if (id.Length == 0) { return id; } if (_attributesRemap.Keys.Any(x => x == id)) { return _attributesRemap[id]; } bool remaped = false; var res = new StringBuilder(); var pattern = new Regex(@"[^a-zA-Z]"); if (pattern.IsMatch(id[0].ToString(CultureInfo.InvariantCulture))) { res.Append("ID"); remaped = true; } const string validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_"; foreach (var character in id) { if (validChars.Contains(character.ToString(CultureInfo.InvariantCulture))) { res.Append(character); } else { remaped = true; res.Append("_"); } } if (remaped) { while (_attributesRemap.Keys.Any(x => x == id)) { res.Append(new Random().Next(0, 9).ToString(CultureInfo.InvariantCulture)); } _attributesRemap.Add(id, res.ToString()); } return res.ToString(); } public string EnsureGoodReference(string reference) { if ((string.IsNullOrEmpty(reference)) || (reference[0] != '#') || (reference.Length < 2)) { return reference; } string subRef = reference.Substring(1); return string.Format("#{0}", EnsureGoodId(subRef)); } public void RemapAnchors(BookStructureManager structureManager) { var listToRemove = new List<string>(); foreach (var link in _references) { if (!ReferencesUtils.IsExternalLink(link.Key)) { if (IsIdUsed(link.Key)) { RemapInternalLink(structureManager, link); } else { listToRemove.Add(link.Key); RemoveInvalidAnchor(link); } } } // Remove the unused anchor (and their ID if they have one) // from the lists foreach (var toRemove in listToRemove) { _references.Remove(toRemove); } } /// <summary> /// Processes all the references and removes invalid anchors /// Invalid meaning pointing to non-existing IDs /// only "internal" anchors are removed /// </summary> private void RemoveInvalidAnchor(KeyValuePair<string, List<Anchor>> link) { // remove all references to this ID foreach (var element in _references[link.Key]) { // The Anchor element can't have empty reference so // we remove it and in case it has some meaningful content // replace with span that is meaningless non-block element // so contained text etc are kept if (element.SubElements().Count != 0) { var spanElement = new Span(element.HTMLStandard); foreach (var subElement in element.SubElements()) { spanElement.Add(subElement); } if (element.Parent != null) { int index = element.Parent.SubElements().IndexOf(element); if (index != -1) { spanElement.Parent = element.Parent; element.Parent.SubElements().Insert(index, spanElement); } } if (!string.IsNullOrEmpty((string)element.GlobalAttributes.ID.Value)) { spanElement.GlobalAttributes.ID.Value = element.GlobalAttributes.ID.Value; // Copy ID anyway - may be someone "jumps" here _ids[(string)element.GlobalAttributes.ID.Value] = spanElement; // and update the "pointer" to element } spanElement.GlobalAttributes.Class.Value = ElementStylesV2.BadExternalLink; } if (element.Parent != null) { element.Parent.Remove(element); } } } private void RemapInternalLink(BookStructureManager structureManager, KeyValuePair<string, List<Anchor>> link) { var linkRemaper = new LinkReMapperV2(link, _ids, structureManager); linkRemaper.Remap(); } public void RemoveInvalidImages(Dictionary<string, BinaryItem> dictionary) { foreach (var imageId in _images.Keys) { if (!dictionary.ContainsKey(imageId)) { foreach (var element in _images[imageId]) { if (element.Parent != null) { element.Parent.Remove(element); } } } } } public bool FlatStructure { get; set; } } }
LordKiRon/fb2converters
fb2epub/FB2EPubConverter/HRefManagerV2.cs
C#
mit
13,852
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _01.StringBuilderSubstring { public static class StringBuilderExtention { public static StringBuilder Substring(this StringBuilder input, int index, int length) { StringBuilder result = new StringBuilder(length); if (index < 0 || index > input.Length - 1) { throw new IndexOutOfRangeException("The index must be >0 and <" + (input.Length - 1)); } if (length < 0 || index + length > input.Length) { throw new ArgumentOutOfRangeException("The length must be >0 and <" + (input.Length - index)); } for (int i = index; i < index + length; i++) { result.Append(input[i]); } return result; } } }
zvet80/TelerikAcademyHomework
03.C# OOP/03.ExtensionMethodsDelegatesLambdaLINQ/01.StringBuilderSubstring/StringBuilder.cs
C#
mit
939
/* Sample code file for CPJ2e. All code has been pasted directly from the camera-ready copy, and then modified in the smallest possible way to ensure that it will compile -- adding import statements or full package qualifiers for some class names, adding stand-ins for classes and methods that are referred to but not listed, and supplying dummy arguments instead of "..."). They are presented in page-number order. */ import com.sun.corba.se.impl.orbutil.concurrent.CondVar; import com.sun.corba.se.impl.orbutil.concurrent.Sync; import java.applet.Applet; import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.InvocationTargetException; import java.net.ServerSocket; import java.net.Socket; import java.net.URL; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.Date; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Random; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.locks.ReadWriteLock; class Helper { // Dummy standin for referenced generic "Helper" classes void handle() {} void operation() {} } class Particle { protected int x; protected int y; protected final Random rng = new Random(); public Particle(int initialX, int initialY) { x = initialX; y = initialY; } public synchronized void move() { x += rng.nextInt(10) - 5; y += rng.nextInt(20) - 10; } public void draw(Graphics g) { int lx, ly; synchronized (this) { lx = x; ly = y; } g.drawRect(lx, ly, 10, 10); } } class ParticleCanvas extends Canvas { private Particle[] particles = new Particle[0]; ParticleCanvas(int size) { setSize(new Dimension(size, size)); } // Intended to be called by applet synchronized void setParticles(Particle[] ps) { if (ps == null) throw new IllegalArgumentException("Cannot set null"); particles = ps; } protected synchronized Particle[] getParticles() { return particles; } public void paint(Graphics g) { // override Canvas.paint Particle[] ps = getParticles(); for (int i = 0; i < ps.length; ++i) ps[i].draw(g); } } class ParticleApplet extends Applet { protected Thread[] threads; // null when not running protected final ParticleCanvas canvas = new ParticleCanvas(100); public void init() { add(canvas); } protected Thread makeThread(final Particle p) { // utility Runnable runloop = new Runnable() { public void run() { try { for(;;) { p.move(); canvas.repaint(); Thread.sleep(100); // 100msec is arbitrary } } catch (InterruptedException e) { return; } } }; return new Thread(runloop); } public synchronized void start() { int n = 10; // just for demo if (threads == null) { // bypass if already started Particle[] particles = new Particle[n]; for (int i = 0; i < n; ++i) particles[i] = new Particle(50, 50); canvas.setParticles(particles); threads = new Thread[n]; for (int i = 0; i < n; ++i) { threads[i] = makeThread(particles[i]); threads[i].start(); } } } public synchronized void stop() { if (threads != null) { // bypass if already stopped for (int i = 0; i < threads.length; ++i) threads[i].interrupt(); threads = null; } } } class AssertionError extends java.lang.Error { public AssertionError() { super(); } public AssertionError(String message) { super(message); } } interface Tank { float getCapacity(); float getVolume(); void transferWater(float amount) throws OverflowException, UnderflowException; } class OverflowException extends Exception {} class UnderflowException extends Exception {} class TankImpl { public float getCapacity() { return 1.0f; } public float getVolume() { return 1.0f; } public void transferWater(float amount) throws OverflowException, UnderflowException {} } class Performer { public void perform() {} } class AdaptedPerformer implements Runnable { private final Performer adaptee; public AdaptedPerformer(Performer p) { adaptee = p; } public void run() { adaptee.perform(); } } class AdaptedTank implements Tank { protected final Tank delegate; public AdaptedTank(Tank t) { delegate = t; } public float getCapacity() { return delegate.getCapacity(); } public float getVolume() { return delegate.getVolume(); } protected void checkVolumeInvariant() throws AssertionError { float v = getVolume(); float c = getCapacity(); if ( !(v >= 0.0 && v <= c) ) throw new AssertionError(); } public synchronized void transferWater(float amount) throws OverflowException, UnderflowException { checkVolumeInvariant(); // before-check try { delegate.transferWater(amount); } // postpone rethrows until after-check catch (OverflowException ex) { throw ex; } catch (UnderflowException ex) { throw ex; } finally { checkVolumeInvariant(); // after-check } } } abstract class AbstractTank implements Tank { protected void checkVolumeInvariant() throws AssertionError { // ... identical to AdaptedTank version ... } protected abstract void doTransferWater(float amount) throws OverflowException, UnderflowException; public synchronized void transferWater(float amount) throws OverflowException, UnderflowException { // identical to AdaptedTank version except for inner call: // ... try { doTransferWater(amount); } finally {} // ... } } class ConcreteTank extends AbstractTank { protected final float capacity = 10.f; protected float volume; // ... public float getVolume() { return volume; } public float getCapacity() { return capacity; } protected void doTransferWater(float amount) throws OverflowException, UnderflowException { // ... implementation code ... } } interface TankOp { void op() throws OverflowException, UnderflowException; } class TankWithMethodAdapter { // ... protected void checkVolumeInvariant() throws AssertionError { // ... identical to AdaptedTank version ... } protected void runWithinBeforeAfterChecks(TankOp cmd) throws OverflowException, UnderflowException { // identical to AdaptedTank.transferWater // except for inner call: // ... try { cmd.op(); } finally {} // ... } protected void doTransferWater(float amount) throws OverflowException, UnderflowException { // ... implementation code ... } public synchronized void transferWater(final float amount) throws OverflowException, UnderflowException { runWithinBeforeAfterChecks(new TankOp() { public void op() throws OverflowException, UnderflowException { doTransferWater(amount); } }); } } class StatelessAdder { public int add(int a, int b) { return a + b; } } class ImmutableAdder { private final int offset; public ImmutableAdder(int a) { offset = a; } public int addOffset(int b) { return offset + b; } } class Fraction { // Fragments protected final long numerator; protected final long denominator; public Fraction(long num, long den) { // normalize: boolean sameSign = (num >= 0) == (den >= 0); long n = (num >= 0)? num : -num; long d = (den >= 0)? den : -den; long g = gcd(n, d); numerator = (sameSign)? n / g : -n / g; denominator = d / g; } static long gcd(long a, long b) { // ... compute greatest common divisor ... return 1; } public Fraction plus(Fraction f) { return new Fraction(numerator * f.denominator + f.numerator * denominator, denominator * f.denominator); } public boolean equals(Object other) { // override default if (! (other instanceof Fraction) ) return false; Fraction f = (Fraction)(other); return numerator * f.denominator == denominator * f.numerator; } public int hashCode() { // override default return (int) (numerator ^ denominator); } } class Server { void doIt() {} } class Relay { protected final Server server; Relay(Server s) { server = s; } void doIt() { server.doIt(); } } class Even { // Do not use private int n = 0; public int next(){ // POST?: next is always even ++n; ++n; return n; } } class ExpandableArray { protected Object[] data; // the elements protected int size = 0; // the number of array slots used // INV: 0 <= size <= data.length public ExpandableArray(int cap) { data = new Object[cap]; } public synchronized int size() { return size; } public synchronized Object get(int i) // subscripted access throws NoSuchElementException { if (i < 0 || i >= size ) throw new NoSuchElementException(); return data[i]; } public synchronized void add(Object x) { // add at end if (size == data.length) { // need a bigger array Object[] olddata = data; data = new Object[3 * (size + 1) / 2]; System.arraycopy(olddata, 0, data, 0, olddata.length); } data[size++] = x; } public synchronized void removeLast() throws NoSuchElementException { if (size == 0) throw new NoSuchElementException(); data[--size] = null; } } interface Procedure { void apply(Object obj); } class ExpandableArrayWithApply extends ExpandableArray { public ExpandableArrayWithApply(int cap) { super(cap); } synchronized void applyToAll(Procedure p) { for (int i = 0; i < size; ++i) p.apply(data[i]); } } class ExpandableArrayWithIterator extends ExpandableArray { protected int version = 0; public ExpandableArrayWithIterator(int cap) { super(cap); } public synchronized void removeLast() throws NoSuchElementException { super.removeLast(); ++version; // advertise update } public synchronized void add(Object x) { super.add(x); ++version; } public synchronized Iterator iterator() { return new EAIterator(); } protected class EAIterator implements Iterator { protected final int currentVersion; protected int currentIndex = 0; EAIterator() { currentVersion = version; } public Object next() { synchronized(ExpandableArrayWithIterator.this) { if (currentVersion != version) throw new ConcurrentModificationException(); else if (currentIndex == size) throw new NoSuchElementException(); else return data[currentIndex++]; } } public boolean hasNext() { synchronized(ExpandableArrayWithIterator.this) { return (currentIndex < size); } } public void remove() { // similar } } } class LazySingletonCounter { private final long initial; private long count; private LazySingletonCounter() { initial = Math.abs(new java.util.Random().nextLong() / 2); count = initial; } private static LazySingletonCounter s = null; private static final Object classLock = LazySingletonCounter.class; public static LazySingletonCounter instance() { synchronized(classLock) { if (s == null) s = new LazySingletonCounter(); return s; } } public long next() { synchronized(classLock) { return count++; } } public void reset() { synchronized(classLock) { count = initial; } } } class EagerSingletonCounter { private final long initial; private long count; private EagerSingletonCounter() { initial = Math.abs(new java.util.Random().nextLong() / 2); count = initial; } private static final EagerSingletonCounter s = new EagerSingletonCounter(); public static EagerSingletonCounter instance() { return s; } public synchronized long next() { return count++; } public synchronized void reset() { count = initial; } } class StaticCounter { private static final long initial = Math.abs(new java.util.Random().nextLong() / 2); private static long count = initial; private StaticCounter() { } // disable instance construction public static synchronized long next() { return count++; } public static synchronized void reset() { count = initial; } } class Cell { // Do not use private long value; synchronized long getValue() { return value; } synchronized void setValue(long v) { value = v; } synchronized void swapValue(Cell other) { long t = getValue(); long v = other.getValue(); setValue(v); other.setValue(t); } } class Cell2 { // Do not use private long value; synchronized long getValue() { return value; } synchronized void setValue(long v) { value = v; } public void swapValue(Cell2 other) { if (other == this) // alias check return; else if (System.identityHashCode(this) < System.identityHashCode(other)) this.doSwapValue(other); else other.doSwapValue(this); } protected synchronized void doSwapValue(Cell2 other) { // same as original public version: long t = getValue(); long v = other.getValue(); setValue(v); other.setValue(t); } protected synchronized void doSwapValueV2(Cell2 other) { synchronized(other) { long t = value; value = other.value; other.value = t; } } } final class SetCheck { private int a = 0; private long b = 0; void set() { a = 1; b = -1; } boolean check() { return ((b == 0) || (b == -1 && a == 1)); } } final class VFloat { private float value; final synchronized void set(float f) { value = f; } final synchronized float get() { return value; } } class Plotter { // fragments // ... public void showNextPoint() { Point p = new Point(); p.x = computeX(); p.y = computeY(); display(p); } int computeX() { return 1; } int computeY() { return 1; } protected void display(Point p) { // somehow arrange to show p. } } class SessionBasedService { // Fragments // ... public void service() { OutputStream output = null; try { output = new FileOutputStream("..."); doService(output); } catch (IOException e) { handleIOFailure(); } finally { try { if (output != null) output.close(); } catch (IOException ignore) {} // ignore exception in close } } void handleIOFailure() {} void doService(OutputStream s) throws IOException { s.write(0); // ... possibly more handoffs ... } } class ThreadPerSessionBasedService { // fragments // ... public void service() { Runnable r = new Runnable() { public void run() { OutputStream output = null; try { output = new FileOutputStream("..."); doService(output); } catch (IOException e) { handleIOFailure(); } finally { try { if (output != null) output.close(); } catch (IOException ignore) {} } } }; new Thread(r).start(); } void handleIOFailure() {} void doService(OutputStream s) throws IOException { s.write(0); // ... possibly more hand-offs ... } } class ThreadWithOutputStream extends Thread { private OutputStream output; ThreadWithOutputStream(Runnable r, OutputStream s) { super(r); output = s; } static ThreadWithOutputStream current() throws ClassCastException { return (ThreadWithOutputStream) (currentThread()); } static OutputStream getOutput() { return current().output; } static void setOutput(OutputStream s) { current().output = s;} } class ServiceUsingThreadWithOutputStream { // Fragments // ... public void service() throws IOException { OutputStream output = new FileOutputStream("..."); Runnable r = new Runnable() { public void run() { try { doService(); } catch (IOException e) { } } }; new ThreadWithOutputStream(r, output).start(); } void doService() throws IOException { ThreadWithOutputStream.current().getOutput().write(0); } } class ServiceUsingThreadLocal { // Fragments static ThreadLocal output = new ThreadLocal(); public void service() { try { final OutputStream s = new FileOutputStream("..."); Runnable r = new Runnable() { public void run() { output.set(s); try { doService(); } catch (IOException e) { } finally { try { s.close(); } catch (IOException ignore) {} } } }; new Thread(r).start(); } catch (IOException e) {} } void doService() throws IOException { ((OutputStream)(output.get())).write(0); // ... } } class BarePoint { public double x; public double y; } class SynchedPoint { protected final BarePoint delegate = new BarePoint(); public synchronized double getX() { return delegate.x;} public synchronized double getY() { return delegate.y; } public synchronized void setX(double v) { delegate.x = v; } public synchronized void setY(double v) { delegate.y = v; } } class Address { // Fragments protected String street; protected String city; public String getStreet() { return street; } public void setStreet(String s) { street = s; } // ... public void printLabel(OutputStream s) { } } class SynchronizedAddress extends Address { // ... public synchronized String getStreet() { return super.getStreet(); } public synchronized void setStreet(String s) { super.setStreet(s); } public synchronized void printLabel(OutputStream s) { super.printLabel(s); } } class Printer { public void printDocument(byte[] doc) { /* ... */ } // ... } class PrintService { protected PrintService neighbor = null; // node to take from protected Printer printer = null; public synchronized void print(byte[] doc) { getPrinter().printDocument(doc); } protected Printer getPrinter() { // PRE: synch lock held if (printer == null) // need to take from neighbor printer = neighbor.takePrinter(); return printer; } synchronized Printer takePrinter() { // called from others if (printer != null) { Printer p = printer; // implement take protocol printer = null; return p; } else return neighbor.takePrinter(); // propagate } // initialization methods called only during start-up synchronized void setNeighbor(PrintService n) { neighbor = n; } synchronized void givePrinter(Printer p) { printer = p; } // Sample code to initialize a ring of new services public static void startUpServices(int nServices, Printer p) throws IllegalArgumentException { if (nServices <= 0 || p == null) throw new IllegalArgumentException(); PrintService first = new PrintService(); PrintService pred = first; for (int i = 1; i < nServices; ++i) { PrintService s = new PrintService(); s.setNeighbor(pred); pred = s; } first.setNeighbor(pred); first.givePrinter(p); } } class AnimationApplet extends Applet { // Fragments // ... int framesPerSecond; // default zero is illegal value void animate() { try { if (framesPerSecond == 0) { // the unsynchronized check synchronized(this) { if (framesPerSecond == 0) { // the double-check String param = getParameter("fps"); framesPerSecond = Integer.parseInt(param); } } } } catch (Exception e) {} // ... actions using framesPerSecond ... } } class ServerWithStateUpdate { private double state; private final Helper helper = new Helper(); public synchronized void service() { state = 2.0f; // ...; // set to some new value helper.operation(); } public synchronized double getState() { return state; } } class ServerWithOpenCall { private double state; private final Helper helper = new Helper(); private synchronized void updateState() { state = 2.0f; // ...; // set to some new value } public void service() { updateState(); helper.operation(); } public synchronized double getState() { return state; } } class ServerWithAssignableHelper { private double state; private Helper helper = new Helper(); synchronized void setHelper(Helper h) { helper = h; } public void service() { Helper h; synchronized(this) { state = 2.0f; // ... h = helper; } h.operation(); } public synchronized void synchedService() { // see below service(); } } class LinkedCell { protected int value; protected final LinkedCell next; public LinkedCell(int v, LinkedCell t) { value = v; next = t; } public synchronized int value() { return value; } public synchronized void setValue(int v) { value = v; } public int sum() { // add up all element values return (next == null) ? value() : value() + next.sum(); } public boolean includes(int x) { // search for x return (value() == x) ? true: (next == null)? false : next.includes(x); } } class Shape { // Incomplete protected double x = 0.0; protected double y = 0.0; protected double width = 0.0; protected double height = 0.0; public synchronized double x() { return x;} public synchronized double y() { return y; } public synchronized double width() { return width;} public synchronized double height() { return height; } public synchronized void adjustLocation() { x = 1; // longCalculation1(); y = 2; //longCalculation2(); } public synchronized void adjustDimensions() { width = 3; // longCalculation3(); height = 4; // longCalculation4(); } // ... } class PassThroughShape { protected final AdjustableLoc loc = new AdjustableLoc(0, 0); protected final AdjustableDim dim = new AdjustableDim(0, 0); public double x() { return loc.x(); } public double y() { return loc.y(); } public double width() { return dim.width(); } public double height() { return dim.height(); } public void adjustLocation() { loc.adjust(); } public void adjustDimensions() { dim.adjust(); } } class AdjustableLoc { protected double x; protected double y; public AdjustableLoc(double initX, double initY) { x = initX; y = initY; } public synchronized double x() { return x;} public synchronized double y() { return y; } public synchronized void adjust() { x = longCalculation1(); y = longCalculation2(); } protected double longCalculation1() { return 1; /* ... */ } protected double longCalculation2() { return 2; /* ... */ } } class AdjustableDim { protected double width; protected double height; public AdjustableDim(double initW, double initH) { width = initW; height = initH; } public synchronized double width() { return width;} public synchronized double height() { return height; } public synchronized void adjust() { width = longCalculation3(); height = longCalculation4(); } protected double longCalculation3() { return 3; /* ... */ } protected double longCalculation4() { return 4; /* ... */ } } class LockSplitShape { // Incomplete protected double x = 0.0; protected double y = 0.0; protected double width = 0.0; protected double height = 0.0; protected final Object locationLock = new Object(); protected final Object dimensionLock = new Object(); public double x() { synchronized(locationLock) { return x; } } public double y() { synchronized(locationLock) { return y; } } public void adjustLocation() { synchronized(locationLock) { x = 1; // longCalculation1(); y = 2; // longCalculation2(); } } // and so on } class SynchronizedInt { private int value; public SynchronizedInt(int v) { value = v; } public synchronized int get() { return value; } public synchronized int set(int v) { // returns previous value int oldValue = value; value = v; return oldValue; } public synchronized int increment() { return ++value; } // and so on } class Person { // Fragments // ... protected final SynchronizedInt age = new SynchronizedInt(0); protected final SynchronizedBoolean isMarried = new SynchronizedBoolean(false); protected final SynchronizedDouble income = new SynchronizedDouble(0.0); public int getAge() { return age.get(); } public void birthday() { age.increment(); } // ... } class LinkedQueue { protected Node head = new Node(null); protected Node last = head; protected final Object pollLock = new Object(); protected final Object putLock = new Object(); public void put(Object x) { Node node = new Node(x); synchronized (putLock) { // insert at end of list synchronized (last) { last.next = node; // extend list last = node; } } } public Object poll() { // returns null if empty synchronized (pollLock) { synchronized (head) { Object x = null; Node first = head.next; // get to first real node if (first != null) { x = first.object; first.object = null; // forget old object head = first; // first becomes new head } return x; } } } static class Node { // local node class for queue Object object; Node next = null; Node(Object x) { object = x; } } } class InsufficientFunds extends Exception {} interface Account { long balance(); } interface UpdatableAccount extends Account { void credit(long amount) throws InsufficientFunds; void debit(long amount) throws InsufficientFunds; } // Sample implementation of updatable version class UpdatableAccountImpl implements UpdatableAccount { private long currentBalance; public UpdatableAccountImpl(long initialBalance) { currentBalance = initialBalance; } public synchronized long balance() { return currentBalance; } public synchronized void credit(long amount) throws InsufficientFunds { if (amount >= 0 || currentBalance >= -amount) currentBalance += amount; else throw new InsufficientFunds(); } public synchronized void debit(long amount) throws InsufficientFunds { credit(-amount); } } final class ImmutableAccount implements Account { private Account delegate; public ImmutableAccount(long initialBalance) { delegate = new UpdatableAccountImpl(initialBalance); } ImmutableAccount(Account acct) { delegate = acct; } public long balance() { // forward the immutable method return delegate.balance(); } } class AccountRecorder { // A logging facility public void recordBalance(Account a) { System.out.println(a.balance()); // or record in file } } class AccountHolder { private UpdatableAccount acct = new UpdatableAccountImpl(0); private AccountRecorder recorder; public AccountHolder(AccountRecorder r) { recorder = r; } public synchronized void acceptMoney(long amount) { try { acct.credit(amount); recorder.recordBalance(new ImmutableAccount(acct));//(*) } catch (InsufficientFunds ex) { System.out.println("Cannot accept negative amount."); } } } class EvilAccountRecorder extends AccountRecorder { private long embezzlement; // ... public void recordBalance(Account a) { super.recordBalance(a); if (a instanceof UpdatableAccount) { UpdatableAccount u = (UpdatableAccount)a; try { u.debit(10); embezzlement += 10; } catch (InsufficientFunds quietlyignore) {} } } } class ImmutablePoint { private final int x; private final int y; public ImmutablePoint(int initX, int initY) { x = initX; y = initY; } public int x() { return x; } public int y() { return y; } } class Dot { protected ImmutablePoint loc; public Dot(int x, int y) { loc = new ImmutablePoint(x, y); } public synchronized ImmutablePoint location() { return loc; } protected synchronized void updateLoc(ImmutablePoint newLoc) { loc = newLoc; } public void moveTo(int x, int y) { updateLoc(new ImmutablePoint(x, y)); } public synchronized void shiftX(int delta) { updateLoc(new ImmutablePoint(loc.x() + delta, loc.y())); } } class CopyOnWriteArrayList { // Incomplete protected Object[] array = new Object[0]; protected synchronized Object[] getArray() { return array; } public synchronized void add(Object element) { int len = array.length; Object[] newArray = new Object[len+1]; System.arraycopy(array, 0, newArray, 0, len); newArray[len] = element; array = newArray; } public Iterator iterator() { return new Iterator() { protected final Object[] snapshot = getArray(); protected int cursor = 0; public boolean hasNext() { return cursor < snapshot.length; } public Object next() { try { return snapshot[cursor++]; } catch (IndexOutOfBoundsException ex) { throw new NoSuchElementException(); } } public void remove() {} }; } } class State {} class Optimistic { // Generic code sketch private State state; // reference to representation object private synchronized State getState() { return state; } private synchronized boolean commit(State assumed, State next) { if (state == assumed) { state = next; return true; } else return false; } } class OptimisticDot { protected ImmutablePoint loc; public OptimisticDot(int x, int y) { loc = new ImmutablePoint(x, y); } public synchronized ImmutablePoint location() { return loc; } protected synchronized boolean commit(ImmutablePoint assumed, ImmutablePoint next) { if (loc == assumed) { loc = next; return true; } else return false; } public synchronized void moveTo(int x, int y) { // bypass commit since unconditional loc = new ImmutablePoint(x, y); } public void shiftX(int delta) { boolean success = false; do { ImmutablePoint old = location(); ImmutablePoint next = new ImmutablePoint(old.x() + delta, old.y()); success = commit(old, next); } while (!success); } } class ParticleUsingMutex { protected int x; protected int y; protected final Random rng = new Random(); protected final Mutex mutex = new Mutex(); public ParticleUsingMutex(int initialX, int initialY) { x = initialX; y = initialY; } public void move() { try { mutex.acquire(); try { x += rng.nextInt(10) - 5; y += rng.nextInt(20) - 10; } finally { mutex.release(); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } public void draw(Graphics g) { int lx, ly; try { mutex.acquire(); try { lx = x; ly = y; } finally { mutex.release(); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; } g.drawRect(lx, ly, 10, 10); } } class WithMutex { private final Mutex mutex; public WithMutex(Mutex m) { mutex = m; } public void perform(Runnable r) throws InterruptedException { mutex.acquire(); try { r.run(); } finally { mutex.release(); } } } class ParticleUsingWrapper { // Incomplete protected int x; protected int y; protected final Random rng = new Random(); protected final WithMutex withMutex = new WithMutex(new Mutex()); protected void doMove() { x += rng.nextInt(10) - 5; y += rng.nextInt(20) - 10; } public void move() { try { withMutex.perform(new Runnable() { public void run() { doMove(); } }); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } // ... } class CellUsingBackoff { private long value; private final Mutex mutex = new Mutex(); void swapValue(CellUsingBackoff other) { if (this == other) return; // alias check required for (;;) { try { mutex.acquire(); try { if (other.mutex.attempt(0)) { try { long t = value; value = other.value; other.value = t; return; } finally { other.mutex.release(); } } } finally { mutex.release(); }; Thread.sleep(100); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); return; } } } } class CellUsingReorderedBackoff { private long value; private final Mutex mutex = new Mutex(); private static boolean trySwap(CellUsingReorderedBackoff a, CellUsingReorderedBackoff b) throws InterruptedException { boolean success = false; if (a.mutex.attempt(0)) { try { if (b.mutex.attempt(0)) { try { long t = a.value; a.value = b.value; b.value = t; success = true; } finally { b.mutex.release(); } } } finally { a.mutex.release(); } } return success; } void swapValue(CellUsingReorderedBackoff other) { if (this == other) return; // alias check required try { while (!trySwap(this, other) && !trySwap(other, this)) Thread.sleep(100); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } class ListUsingMutex { static class Node { Object item; Node next; Mutex lock = new Mutex(); // each node keeps its own lock Node(Object x, Node n) { item = x; next = n; } } protected Node head; // pointer to first node of list // Use plain synchronization to protect head field. // (We could instead use a Mutex here too but there is no // reason to do so.) protected synchronized Node getHead() { return head; } public synchronized void add(Object x) { // simple prepend // for simplicity here, do not allow null elements if (x == null) throw new IllegalArgumentException(); // The use of synchronized here protects only head field. // The method does not need to wait out other traversers // who have already made it past head node. head = new Node(x, head); } boolean search(Object x) throws InterruptedException { Node p = getHead(); if (p == null || x == null) return false; p.lock.acquire(); // Prime loop by acquiring first lock. // If above acquire fails due to interrupt, the method will // throw InterruptedException now, so there is no need for // further cleanup. for (;;) { Node nextp = null; boolean found; try { found = x.equals(p.item); if (!found) { nextp = p.next; if (nextp != null) { try { // Acquire next lock // while still holding current nextp.lock.acquire(); } catch (InterruptedException ie) { throw ie; // Note that finally clause will // execute before the throw } } } } finally { p.lock.release(); } if (found) return true; else if (nextp == null) return false; else p = nextp; } } // ... other similar traversal and update methods ... } class DataRepository { // code sketch protected final ReadWriteLock rw = new WriterPreferenceReadWriteLock(); public void access() throws InterruptedException { rw.readLock().acquire(); try { /* read data */ } finally { rw.readLock().release(); } } public void modify() throws InterruptedException { rw.writeLock().acquire(); try { /* write data */ } finally { rw.writeLock().release(); } } } class ClientUsingSocket { // Code sketch int portnumber = 1234; String server = "gee"; // ... Socket retryUntilConnected() throws InterruptedException { // first delay is randomly chosen between 5 and 10secs long delayTime = 5000 + (long)(Math.random() * 5000); for (;;) { try { return new Socket(server, portnumber); } catch (IOException ex) { Thread.sleep(delayTime); delayTime = delayTime * 3 / 2 + 1; // increase 50% } } } } class ServiceException extends Exception {} interface ServerWithException { void service() throws ServiceException; } interface ServiceExceptionHandler { void handle(ServiceException e); } class ServerImpl implements ServerWithException { public void service() throws ServiceException {} } class HandlerImpl implements ServiceExceptionHandler { public void handle(ServiceException e) {} } class HandledService implements ServerWithException { final ServerWithException server = new ServerImpl(); final ServiceExceptionHandler handler = new HandlerImpl(); public void service() { // no throw clause try { server.service(); } catch (ServiceException e) { handler.handle(e); } } } class ExceptionEvent extends java.util.EventObject { public final Throwable theException; public ExceptionEvent(Object src, Throwable ex) { super(src); theException = ex; } } class ExceptionEventListener { // Incomplete public void exceptionOccured(ExceptionEvent ee) { // ... respond to exception... } } class ServiceIssuingExceptionEvent { // Incomplete // ... private final CopyOnWriteArrayList handlers = new CopyOnWriteArrayList(); public void addHandler(ExceptionEventListener h) { handlers.add(h); } public void service() { // ... boolean failed = true; if (failed) { Throwable ex = new ServiceException(); ExceptionEvent ee = new ExceptionEvent(this, ex); for (Iterator it = handlers.iterator(); it.hasNext();) { ExceptionEventListener l = (ExceptionEventListener)(it.next()); l.exceptionOccured(ee); } } } } class CancellableReader { // Incomplete private Thread readerThread; // only one at a time supported private FileInputStream dataFile; public synchronized void startReaderThread() throws IllegalStateException, FileNotFoundException { if (readerThread != null) throw new IllegalStateException(); dataFile = new FileInputStream("data"); readerThread = new Thread(new Runnable() { public void run() { doRead(); } }); readerThread.start(); } protected synchronized void closeFile() { // utility method if (dataFile != null) { try { dataFile.close(); } catch (IOException ignore) {} dataFile = null; } } void process(int b) {} private void doRead() { try { while (!Thread.interrupted()) { try { int c = dataFile.read(); if (c == -1) break; else process(c); } catch (IOException ex) { break; // perhaps first do other cleanup } } } finally { closeFile(); synchronized(this) { readerThread = null; } } } public synchronized void cancelReaderThread() { if (readerThread != null) readerThread.interrupt(); closeFile(); } } class ReaderWithTimeout { // Generic code sketch // ... void process(int b) {} void attemptRead(InputStream stream, long timeout) throws Exception { long startTime = System.currentTimeMillis(); try { for (;;) { if (stream.available() > 0) { int c = stream.read(); if (c != -1) process(c); else break; // eof } else { try { Thread.sleep(100); // arbitrary back-off time } catch (InterruptedException ie) { /* ... quietly wrap up and return ... */ } long now = System.currentTimeMillis(); if (now - startTime >= timeout) { /* ... fail ...*/ } } } } catch (IOException ex) { /* ... fail ... */ } } } class C { // Fragments private int v; // invariant: v >= 0 synchronized void f() { v = -1 ; // temporarily set to illegal value as flag compute(); // possible stop point (*) v = 1; // set to legal value } synchronized void g() { while (v != 0) { --v; something(); } } void compute() {} void something() {} } class Terminator { // Try to kill; return true if known to be dead static boolean terminate(Thread t, long maxWaitToDie) { if (!t.isAlive()) return true; // already dead // phase 1 -- graceful cancellation t.interrupt(); try { t.join(maxWaitToDie); } catch(InterruptedException e){} // ignore if (!t.isAlive()) return true; // success // phase 2 -- trap all security checks // theSecurityMgr.denyAllChecksFor(t); // a made-up method try { t.join(maxWaitToDie); } catch(InterruptedException ex) {} if (!t.isAlive()) return true; // phase 3 -- minimize damage t.setPriority(Thread.MIN_PRIORITY); return false; } } interface BoundedCounter { static final long MIN = 0; // minimum allowed value static final long MAX = 10; // maximum allowed value long count(); // INV: MIN <= count() <= MAX // INIT: count() == MIN void inc(); // only allowed when count() < MAX void dec(); // only allowed when count() > MIN } class X { synchronized void w() throws InterruptedException { before(); wait(); after(); } synchronized void n() { notifyAll(); } void before() {} void after() {} } class GuardedClass { // Generic code sketch protected boolean cond = false; // PRE: lock held protected void awaitCond() throws InterruptedException{ while (!cond) wait(); } public synchronized void guardedAction() { try { awaitCond(); } catch (InterruptedException ie) { // fail } // actions } } class SimpleBoundedCounter { static final long MIN = 0; // minimum allowed value static final long MAX = 10; // maximum allowed value protected long count = MIN; public synchronized long count() { return count; } public synchronized void inc() throws InterruptedException { awaitUnderMax(); setCount(count + 1); } public synchronized void dec() throws InterruptedException { awaitOverMin(); setCount(count - 1); } protected void setCount(long newValue) { // PRE: lock held count = newValue; notifyAll(); // wake up any thread depending on new value } protected void awaitUnderMax() throws InterruptedException { while (count == MAX) wait(); } protected void awaitOverMin() throws InterruptedException { while (count == MIN) wait(); } } class GuardedClassUsingNotify { protected boolean cond = false; protected int nWaiting = 0; // count waiting threads protected synchronized void awaitCond() throws InterruptedException { while (!cond) { ++nWaiting; // record fact that a thread is waiting try { wait(); } catch (InterruptedException ie) { notify(); throw ie; } finally { --nWaiting; // no longer waiting } } } protected synchronized void signalCond() { if (cond) { // simulate notifyAll for (int i = nWaiting; i > 0; --i) { notify(); } } } } class GamePlayer implements Runnable { // Incomplete protected GamePlayer other; protected boolean myturn = false; protected synchronized void setOther(GamePlayer p) { other = p; } synchronized void giveTurn() { // called by other player myturn = true; notify(); // unblock thread } void releaseTurn() { GamePlayer p; synchronized(this) { myturn = false; p = other; } p.giveTurn(); // open call } synchronized void awaitTurn() throws InterruptedException { while (!myturn) wait(); } void move() { /*... perform one move ... */ } public void run() { try { for (;;) { awaitTurn(); move(); releaseTurn(); } } catch (InterruptedException ie) {} // die } public static void main(String[] args) { GamePlayer one = new GamePlayer(); GamePlayer two = new GamePlayer(); one.setOther(two); two.setOther(one); one.giveTurn(); new Thread(one).start(); new Thread(two).start(); } } //class TimeoutException extends InterruptedException { ... } class TimeOutBoundedCounter { static final long MIN = 0; // minimum allowed value static final long MAX = 10; // maximum allowed value protected long count = 0; protected long TIMEOUT = 5000; // for illustration // ... synchronized void inc() throws InterruptedException { if (count >= MAX) { long start = System.currentTimeMillis(); long waitTime = TIMEOUT; for (;;) { if (waitTime <= 0) throw new TimeoutException(TIMEOUT); else { try { wait(waitTime); } catch (InterruptedException ie) { throw ie; // coded this way just for emphasis } if (count < MAX) break; else { long now = System.currentTimeMillis(); waitTime = TIMEOUT - (now - start); } } } } ++count; notifyAll(); } synchronized void dec() throws InterruptedException { // ... similar ... } } class SpinLock { // Avoid needing to use this private volatile boolean busy = false; synchronized void release() { busy = false; } void acquire() throws InterruptedException { int itersBeforeYield = 100; // 100 is arbitrary int itersBeforeSleep = 200; // 200 is arbitrary long sleepTime = 1; // 1msec is arbitrary int iters = 0; for (;;) { if (!busy) { // test-and-test-and-set synchronized(this) { if (!busy) { busy = true; return; } } } if (iters < itersBeforeYield) { // spin phase ++iters; } else if (iters < itersBeforeSleep) { // yield phase ++iters; Thread.yield(); } else { // back-off phase Thread.sleep(sleepTime); sleepTime = 3 * sleepTime / 2 + 1; // 50% is arbitrary } } } } class BoundedBufferWithStateTracking { protected final Object[] array; // the elements protected int putPtr = 0; // circular indices protected int takePtr = 0; protected int usedSlots = 0; // the count public BoundedBufferWithStateTracking(int capacity) throws IllegalArgumentException { if (capacity <= 0) throw new IllegalArgumentException(); array = new Object[capacity]; } public synchronized int size() { return usedSlots; } public int capacity() { return array.length; } public synchronized void put(Object x) throws InterruptedException { while (usedSlots == array.length) // wait until not full wait(); array[putPtr] = x; putPtr = (putPtr + 1) % array.length; // cyclically inc if (usedSlots++ == 0) // signal if was empty notifyAll(); } public synchronized Object take() throws InterruptedException{ while (usedSlots == 0) // wait until not empty wait(); Object x = array[takePtr]; array[takePtr] = null; takePtr = (takePtr + 1) % array.length; if (usedSlots-- == array.length) // signal if was full notifyAll(); return x; } } class BoundedCounterWithStateVariable { static final long MIN = 0; // minimum allowed value static final long MAX = 10; // maximum allowed value static final int BOTTOM = 0, MIDDLE = 1, TOP = 2; protected int state = BOTTOM; // the state variable protected long count = MIN; protected void updateState() { // PRE: synch lock held int oldState = state; if (count == MIN) state = BOTTOM; else if (count == MAX) state = TOP; else state = MIDDLE; if (state != oldState && oldState != MIDDLE) notifyAll(); // notify on transition } public synchronized long count() { return count; } public synchronized void inc() throws InterruptedException { while (state == TOP) wait(); ++count; updateState(); } public synchronized void dec() throws InterruptedException { while (state == BOTTOM) wait(); --count; updateState(); } } class Inventory { protected final Hashtable items = new Hashtable(); protected final Hashtable suppliers = new Hashtable(); // execution state tracking variables: protected int storing = 0; // number of in-progress stores protected int retrieving = 0; // number of retrieves // ground actions: protected void doStore(String description, Object item, String supplier) { items.put(description, item); suppliers.put(supplier, description); } protected Object doRetrieve(String description) { Object x = items.get(description); if (x != null) items.remove(description); return x; } public void store(String description, Object item, String supplier) throws InterruptedException { synchronized(this) { // Before-action while (retrieving != 0) // don't overlap with retrieves wait(); ++storing; // record exec state } try { doStore(description, item, supplier); // Ground action } finally { // After-action synchronized(this) { // signal retrieves if (--storing == 0) // only necessary when hit zero notifyAll(); } } } public Object retrieve(String description) throws InterruptedException { synchronized(this) { // Before-action // wait until no stores or retrieves while (storing != 0 || retrieving != 0) wait(); ++retrieving; } try { return doRetrieve(description); // ground action } finally { synchronized(this) { // After-action if (--retrieving == 0) notifyAll(); } } } } abstract class ReadWrite { protected int activeReaders = 0; // threads executing read protected int activeWriters = 0; // always zero or one protected int waitingReaders = 0; // threads not yet in read protected int waitingWriters = 0; // same for write protected abstract void doRead(); // implement in subclasses protected abstract void doWrite(); public void read() throws InterruptedException { beforeRead(); try { doRead(); } finally { afterRead(); } } public void write() throws InterruptedException { beforeWrite(); try { doWrite(); } finally { afterWrite(); } } protected boolean allowReader() { return waitingWriters == 0 && activeWriters == 0; } protected boolean allowWriter() { return activeReaders == 0 && activeWriters == 0; } protected synchronized void beforeRead() throws InterruptedException { ++waitingReaders; while (!allowReader()) { try { wait(); } catch (InterruptedException ie) { --waitingReaders; // roll back state throw ie; } } --waitingReaders; ++activeReaders; } protected synchronized void afterRead() { --activeReaders; notifyAll(); } protected synchronized void beforeWrite() throws InterruptedException { ++waitingWriters; while (!allowWriter()) { try { wait(); } catch (InterruptedException ie) { --waitingWriters; throw ie; } } --waitingWriters; ++activeWriters; } protected synchronized void afterWrite() { --activeWriters; notifyAll(); } } class RWLock extends ReadWrite implements ReadWriteLock { // Incomplete class RLock implements Sync { public void acquire() throws InterruptedException { beforeRead(); } public void release() { afterRead(); } public boolean attempt(long msecs) throws InterruptedException{ return beforeRead(msecs); } } class WLock implements Sync { public void acquire() throws InterruptedException { beforeWrite(); } public void release() { afterWrite(); } public boolean attempt(long msecs) throws InterruptedException{ return beforeWrite(msecs); } } protected final RLock rlock = new RLock(); protected final WLock wlock = new WLock(); public Sync readLock() { return rlock; } public Sync writeLock() { return wlock; } public boolean beforeRead(long msecs) throws InterruptedException { return true; // ... time-out version of beforeRead ... } public boolean beforeWrite(long msecs) throws InterruptedException { return true; // ... time-out version of beforeWrite ... } protected void doRead() {} protected void doWrite() {} } class StackEmptyException extends Exception { } class Stack { // Fragments public synchronized boolean isEmpty() { return false; /* ... */ } public synchronized void push(Object x) { /* ... */ } public synchronized Object pop() throws StackEmptyException { if (isEmpty()) throw new StackEmptyException(); else return null; } } class WaitingStack extends Stack { public synchronized void push(Object x) { super.push(x); notifyAll(); } public synchronized Object waitingPop() throws InterruptedException { while (isEmpty()) { wait(); } try { return super.pop(); } catch (StackEmptyException cannothappen) { // only possible if pop contains a programming error throw new Error("Internal implementation error"); } } } class PartWithGuard { protected boolean cond = false; synchronized void await() throws InterruptedException { while (!cond) wait(); // any other code } synchronized void signal(boolean c) { cond = c; notifyAll(); } } class Host { protected final PartWithGuard part = new PartWithGuard(); synchronized void rely() throws InterruptedException { part.await(); } synchronized void set(boolean c) { part.signal(c); } } class OwnedPartWithGuard { // Code sketch protected boolean cond = false; final Object lock; OwnedPartWithGuard(Object owner) { lock = owner; } void await() throws InterruptedException { synchronized(lock) { while (!cond) lock.wait(); // ... } } void signal(boolean c) { synchronized(lock) { cond = c; lock.notifyAll(); } } } class Pool { // Incomplete protected java.util.ArrayList items = new ArrayList(); protected java.util.HashSet busy = new HashSet(); protected final Semaphore available; public Pool(int n) { available = new Semaphore(n); initializeItems(n); } public Object getItem() throws InterruptedException { available.acquire(); return doGet(); } public void returnItem(Object x) { if (doReturn(x)) available.release(); } protected synchronized Object doGet() { Object x = items.remove(items.size()-1); busy.add(x); // put in set to check returns return x; } protected synchronized boolean doReturn(Object x) { if (busy.remove(x)) { items.add(x); // put back into available item list return true; } else return false; } protected void initializeItems(int n) { // Somehow create the resource objects // and place them in items list. } } class BufferArray { protected final Object[] array; // the elements protected int putPtr = 0; // circular indices protected int takePtr = 0; BufferArray(int n) { array = new Object[n]; } synchronized void insert(Object x) { // put mechanics array[putPtr] = x; putPtr = (putPtr + 1) % array.length; } synchronized Object extract() { // take mechanics Object x = array[takePtr]; array[takePtr] = null; takePtr = (takePtr + 1) % array.length; return x; } } class BoundedBufferWithSemaphores { protected final BufferArray buff; protected final Semaphore putPermits; protected final Semaphore takePermits; public BoundedBufferWithSemaphores(int capacity) throws IllegalArgumentException { if (capacity <= 0) throw new IllegalArgumentException(); buff = new BufferArray(capacity); putPermits = new Semaphore(capacity); takePermits = new Semaphore(0); } public void put(Object x) throws InterruptedException { putPermits.acquire(); buff.insert(x); takePermits.release(); } public Object take() throws InterruptedException { takePermits.acquire(); Object x = buff.extract(); putPermits.release(); return x; } public Object poll(long msecs) throws InterruptedException { if (!takePermits.attempt(msecs)) return null; Object x = buff.extract(); putPermits.release(); return x; } public boolean offer(Object x, long msecs) throws InterruptedException { if (!putPermits.attempt(msecs)) return false; buff.insert(x); takePermits.release(); return true; } } class SynchronousChannel /* implements Channel */ { protected Object item = null; // to hold while in transit protected final Semaphore putPermit; protected final Semaphore takePermit; protected final Semaphore taken; public SynchronousChannel() { putPermit = new Semaphore(1); takePermit = new Semaphore(0); taken = new Semaphore(0); } public void put(Object x) throws InterruptedException { putPermit.acquire(); item = x; takePermit.release(); // Must wait until signalled by taker InterruptedException caught = null; for (;;) { try { taken.acquire(); break; } catch(InterruptedException ie) { caught = ie; } } if (caught != null) throw caught; // can now rethrow } public Object take() throws InterruptedException { takePermit.acquire(); Object x = item; item = null; putPermit.release(); taken.release(); return x; } } class Player implements Runnable { // Code sketch // ... protected final Latch startSignal; Player(Latch l) { startSignal = l; } public void run() { try { startSignal.acquire(); play(); } catch(InterruptedException ie) { return; } } void play() {} // ... } class Game { // ... void begin(int nplayers) { Latch startSignal = new Latch(); for (int i = 0; i < nplayers; ++i) new Thread(new Player(startSignal)).start(); startSignal.release(); } } class LatchingThermometer { // Seldom useful private volatile boolean ready; // latching private volatile float temperature; public double getReading() { while (!ready) Thread.yield(); return temperature; } void sense(float t) { // called from sensor temperature = t; ready = true; } } class FillAndEmpty { // Incomplete static final int SIZE = 1024; // buffer size, for demo protected Rendezvous exchanger = new Rendezvous(2); protected byte readByte() { return 1; /* ... */; } protected void useByte(byte b) { /* ... */ } public void start() { new Thread(new FillingLoop()).start(); new Thread(new EmptyingLoop()).start(); } class FillingLoop implements Runnable { // inner class public void run() { byte[] buffer = new byte[SIZE]; int position = 0; try { for (;;) { if (position == SIZE) { buffer = (byte[])(exchanger.rendezvous(buffer)); position = 0; } buffer[position++] = readByte(); } } catch (BrokenBarrierException ex) {} // die catch (InterruptedException ie) {} // die } } class EmptyingLoop implements Runnable { // inner class public void run() { byte[] buffer = new byte[SIZE]; int position = SIZE; // force exchange first time through try { for (;;) { if (position == SIZE) { buffer = (byte[])(exchanger.rendezvous(buffer)); position = 0; } useByte(buffer[position++]); } } catch (BrokenBarrierException ex) {} // die catch (InterruptedException ex) {} // die } } } class PThreadsStyleBuffer { private final Mutex mutex = new Mutex(); private final CondVar notFull = new CondVar(mutex); private final CondVar notEmpty = new CondVar(mutex); private int count = 0; private int takePtr = 0; private int putPtr = 0; private final Object[] array; public PThreadsStyleBuffer(int capacity) { array = new Object[capacity]; } public void put(Object x) throws InterruptedException { mutex.acquire(); try { while (count == array.length) notFull.await(); array[putPtr] = x; putPtr = (putPtr + 1) % array.length; ++count; notEmpty.signal(); } finally { mutex.release(); } } public Object take() throws InterruptedException { Object x = null; mutex.acquire(); try { while (count == 0) notEmpty.await(); x = array[takePtr]; array[takePtr] = null; takePtr = (takePtr + 1) % array.length; --count; notFull.signal(); } finally { mutex.release(); } return x; } } class BankAccount { protected long balance = 0; public synchronized long balance() { return balance; } public synchronized void deposit(long amount) throws InsufficientFunds { if (balance + amount < 0) throw new InsufficientFunds(); else balance += amount; } public void withdraw(long amount) throws InsufficientFunds { deposit(-amount); } } class TSBoolean { private boolean value = false; // set to true; return old value public synchronized boolean testAndSet() { boolean oldValue = value; value = true; return oldValue; } public synchronized void clear() { value = false; } } class ATCheckingAccount extends BankAccount { protected ATSavingsAccount savings; protected long threshold; protected TSBoolean transferInProgress = new TSBoolean(); public ATCheckingAccount(long t) { threshold = t; } // called only upon initialization synchronized void initSavings(ATSavingsAccount s) { savings = s; } protected boolean shouldTry() { return balance < threshold; } void tryTransfer() { // called internally or from savings if (!transferInProgress.testAndSet()) { // if not busy ... try { synchronized(this) { if (shouldTry()) balance += savings.transferOut(); } } finally { transferInProgress.clear(); } } } public synchronized void deposit(long amount) throws InsufficientFunds { if (balance + amount < 0) throw new InsufficientFunds(); else { balance += amount; tryTransfer(); } } } class ATSavingsAccount extends BankAccount { protected ATCheckingAccount checking; protected long maxTransfer; public ATSavingsAccount(long max) { maxTransfer = max; } // called only upon initialization synchronized void initChecking(ATCheckingAccount c) { checking = c; } synchronized long transferOut() { // called only from checking long amount = balance; if (amount > maxTransfer) amount = maxTransfer; if (amount >= 0) balance -= amount; return amount; } public synchronized void deposit(long amount) throws InsufficientFunds { if (balance + amount < 0) throw new InsufficientFunds(); else { balance += amount; checking.tryTransfer(); } } } class Subject { protected double val = 0.0; // modeled state protected final EDU.oswego.cs.dl.util.concurrent.CopyOnWriteArrayList observers = new EDU.oswego.cs.dl.util.concurrent.CopyOnWriteArrayList(); public synchronized double getValue() { return val; } protected synchronized void setValue(double d) { val = d; } public void attach(Observer o) { observers.add(o); } public void detach(Observer o) { observers.remove(o); } public void changeValue(double newstate) { setValue(newstate); for (Iterator it = observers.iterator(); it.hasNext();) ((Observer)(it.next())).changed(this); } } class Observer { protected double cachedState; // last known state protected final Subject subj; // only one allowed here Observer(Subject s) { subj = s; cachedState = s.getValue(); display(); } synchronized void changed(Subject s){ if (s != subj) return; // only one subject double oldState = cachedState; cachedState = subj.getValue(); // probe if (oldState != cachedState) display(); } protected void display() { // somehow display subject state; for example just: System.out.println(cachedState); } } class Failure extends Exception {} interface Transactor { // Enter a new transaction and return true, if can do so public boolean join(Transaction t); // Return true if this transaction can be committed public boolean canCommit(Transaction t); // Update state to reflect current transaction public void commit(Transaction t) throws Failure; // Roll back state (No exception; ignore if inapplicable) public void abort(Transaction t); } class Transaction { // add anything you want here } interface TransBankAccount extends Transactor { public long balance(Transaction t) throws Failure; public void deposit(Transaction t, long amount) throws InsufficientFunds, Failure; public void withdraw(Transaction t, long amount) throws InsufficientFunds, Failure; } class SimpleTransBankAccount implements TransBankAccount { protected long balance = 0; protected long workingBalance = 0; // single shadow copy protected Transaction currentTx = null; // single transaction public synchronized long balance(Transaction t) throws Failure { if (t != currentTx) throw new Failure(); return workingBalance; } public synchronized void deposit(Transaction t, long amount) throws InsufficientFunds, Failure { if (t != currentTx) throw new Failure(); if (workingBalance < -amount) throw new InsufficientFunds(); workingBalance += amount; } public synchronized void withdraw(Transaction t, long amount) throws InsufficientFunds, Failure { deposit(t, -amount); } public synchronized boolean join(Transaction t) { if (currentTx != null) return false; currentTx = t; workingBalance = balance; return true; } public synchronized boolean canCommit(Transaction t) { return (t == currentTx); } public synchronized void abort(Transaction t) { if (t == currentTx) currentTx = null; } public synchronized void commit(Transaction t) throws Failure{ if (t != currentTx) throw new Failure(); balance = workingBalance; currentTx = null; } } class ProxyAccount /* implements TransBankAccount */ { private TransBankAccount delegate; public boolean join(Transaction t) { return delegate.join(t); } public long balance(Transaction t) throws Failure { return delegate.balance(t); } // and so on... } class FailedTransferException extends Exception {} class RetryableTransferException extends Exception {} class TransactionLogger { void cancelLogEntry(Transaction t, long amount, TransBankAccount src, TransBankAccount dst) {} void logTransfer(Transaction t, long amount, TransBankAccount src, TransBankAccount dst) {} void logCompletedTransfer(Transaction t, long amount, TransBankAccount src, TransBankAccount dst) {} } class AccountUser { TransactionLogger log; // a made-up class // helper method called on any failure void rollback(Transaction t, long amount, TransBankAccount src, TransBankAccount dst) { log.cancelLogEntry(t, amount, src, dst); src.abort(t); dst.abort(t); } public boolean transfer(long amount, TransBankAccount src, TransBankAccount dst) throws FailedTransferException, RetryableTransferException { if (src == null || dst == null) // screen arguments throw new IllegalArgumentException(); if (src == dst) return true; // avoid aliasing Transaction t = new Transaction(); log.logTransfer(t, amount, src, dst); // record if (!src.join(t) || !dst.join(t)) { // cannot join rollback(t, amount, src, dst); throw new RetryableTransferException(); } try { src.withdraw(t, amount); dst.deposit(t, amount); } catch (InsufficientFunds ex) { // semantic failure rollback(t, amount, src, dst); return false; } catch (Failure k) { // transaction error rollback(t, amount, src, dst); throw new RetryableTransferException(); } if (!src.canCommit(t) || !dst.canCommit(t)) { // interference rollback(t, amount, src, dst); throw new RetryableTransferException(); } try { src.commit(t); dst.commit(t); log.logCompletedTransfer(t, amount, src, dst); return true; } catch(Failure k) { // commitment failure rollback(t, amount, src, dst); throw new FailedTransferException(); } } } class ColoredThing { protected Color myColor = Color.red; // the sample property protected boolean changePending; // vetoable listeners: protected final VetoableChangeMulticaster vetoers = new VetoableChangeMulticaster(this); // also some ordinary listeners: protected final PropertyChangeMulticaster listeners = new PropertyChangeMulticaster(this); // registration methods, including: void addVetoer(VetoableChangeListener l) { vetoers.addVetoableChangeListener(l); } public synchronized Color getColor() { // property accessor return myColor; } // internal helper methods protected synchronized void commitColor(Color newColor) { myColor = newColor; changePending = false; } protected synchronized void abortSetColor() { changePending = false; } public void setColor(Color newColor) throws PropertyVetoException { Color oldColor = null; boolean completed = false; synchronized (this) { if (changePending) { // allow only one transaction at a time throw new PropertyVetoException( "Concurrent modification", null); } else if (newColor == null) { // Argument screening throw new PropertyVetoException( "Cannot change color to Null", null); } else { changePending = true; oldColor = myColor; } } try { vetoers.fireVetoableChange("color", oldColor, newColor); // fall through if no exception: commitColor(newColor); completed = true; // notify other listeners that change is committed listeners.firePropertyChange("color", oldColor, newColor); } catch(PropertyVetoException ex) { // abort on veto abortSetColor(); completed = true; throw ex; } finally { // trap any unchecked exception if (!completed) abortSetColor(); } } } class Semaphore implements Sync { protected long permits; // current number of available permits public Semaphore(long initialPermits) { permits = initialPermits; } public synchronized void release() { ++permits; notify(); } public void acquire() throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); synchronized(this) { try { while (permits <= 0) wait(); --permits; } catch (InterruptedException ie) { notify(); throw ie; } } } public boolean attempt(long msecs)throws InterruptedException{ if (Thread.interrupted()) throw new InterruptedException(); synchronized(this) { if (permits > 0) { // Same as acquire but messier --permits; return true; } else if (msecs <= 0) // avoid timed wait if not needed return false; else { try { long startTime = System.currentTimeMillis(); long waitTime = msecs; for (;;) { wait(waitTime); if (permits > 0) { --permits; return true; } else { // Check for time-out long now = System.currentTimeMillis(); waitTime = msecs - (now - startTime); if (waitTime <= 0) return false; } } } catch(InterruptedException ie) { notify(); throw ie; } } } } } final class BoundedBufferWithDelegates { private Object[] array; private Exchanger putter; private Exchanger taker; public BoundedBufferWithDelegates(int capacity) throws IllegalArgumentException { if (capacity <= 0) throw new IllegalArgumentException(); array = new Object[capacity]; putter = new Exchanger(capacity); taker = new Exchanger(0); } public void put(Object x) throws InterruptedException { putter.exchange(x); } public Object take() throws InterruptedException { return taker.exchange(null); } void removedSlotNotification(Exchanger h) { // relay if (h == putter) taker.addedSlotNotification(); else putter.addedSlotNotification(); } protected class Exchanger { // Inner class protected int ptr = 0; // circular index protected int slots; // number of usable slots protected int waiting = 0; // number of waiting threads Exchanger(int n) { slots = n; } synchronized void addedSlotNotification() { ++slots; if (waiting > 0) // unblock a single waiting thread notify(); } Object exchange(Object x) throws InterruptedException { Object old = null; // return value synchronized(this) { while (slots <= 0) { // wait for slot ++waiting; try { wait(); } catch(InterruptedException ie) { notify(); throw ie; } finally { --waiting; } } --slots; // use slot old = array[ptr]; array[ptr] = x; ptr = (ptr + 1) % array.length; // advance position } removedSlotNotification(this); // notify of change return old; } } } final class BoundedBufferWithMonitorObjects { private final Object[] array; // the elements private int putPtr = 0; // circular indices private int takePtr = 0; private int emptySlots; // slot counts private int usedSlots = 0; private int waitingPuts = 0; // counts of waiting threads private int waitingTakes = 0; private final Object putMonitor = new Object(); private final Object takeMonitor = new Object(); public BoundedBufferWithMonitorObjects(int capacity) throws IllegalArgumentException { if (capacity <= 0) throw new IllegalArgumentException(); array = new Object[capacity]; emptySlots = capacity; } public void put(Object x) throws InterruptedException { synchronized(putMonitor) { while (emptySlots <= 0) { ++waitingPuts; try { putMonitor.wait(); } catch(InterruptedException ie) { putMonitor.notify(); throw ie; } finally { --waitingPuts; } } --emptySlots; array[putPtr] = x; putPtr = (putPtr + 1) % array.length; } synchronized(takeMonitor) { // directly notify ++usedSlots; if (waitingTakes > 0) takeMonitor.notify(); } } public Object take() throws InterruptedException { Object old = null; synchronized(takeMonitor) { while (usedSlots <= 0) { ++waitingTakes; try { takeMonitor.wait(); } catch(InterruptedException ie) { takeMonitor.notify(); throw ie; } finally { --waitingTakes; } } --usedSlots; old = array[takePtr]; array[takePtr] = null; takePtr = (takePtr + 1) % array.length; } synchronized(putMonitor) { ++emptySlots; if (waitingPuts > 0) putMonitor.notify(); } return old; } } class FIFOSemaphore extends Semaphore { protected final WaitQueue queue = new WaitQueue(); public FIFOSemaphore(long initialPermits) { super(initialPermits); } public void acquire() throws InterruptedException { if (Thread.interrupted()) throw new InterruptedException(); WaitNode node = null; synchronized(this) { if (permits > 0) { // no need to queue --permits; return; } else { node = new WaitNode(); queue.enq(node); } } // must release lock before node wait node.doWait(); } public synchronized void release() { for (;;) { // retry until success WaitNode node = queue.deq(); if (node == null) { // queue is empty ++permits; return; } else if (node.doNotify()) return; // else node was already released due to // interruption or time-out, so must retry } } // Queue node class. Each node serves as a monitor. protected static class WaitNode { boolean released = false; WaitNode next = null; synchronized void doWait() throws InterruptedException { try { while (!released) wait(); } catch (InterruptedException ie) { if (!released) { // Interrupted before notified // Suppress future notifications: released = true; throw ie; } else { // Interrupted after notified // Ignore exception but propagate status: Thread.currentThread().interrupt(); } } } synchronized boolean doNotify() { // return true if notified if (released) // was interrupted or timed out return false; else { released = true; notify(); return true; } } synchronized boolean doTimedWait(long msecs) throws InterruptedException { return true; // similar } } // Standard linked queue class. // Used only when holding Semaphore lock. protected static class WaitQueue { protected WaitNode head = null; protected WaitNode last = null; protected void enq(WaitNode node) { if (last == null) head = last = node; else { last.next = node; last = node; } } protected WaitNode deq() { WaitNode node = head; if (node != null) { head = node.next; if (head == null) last = null; node.next = null; } return node; } } } class WebService implements Runnable { static final int PORT = 1040; // just for demo Handler handler = new Handler(); public void run() { try { ServerSocket socket = new ServerSocket(PORT); for (;;) { final Socket connection = socket.accept(); new Thread(new Runnable() { public void run() { handler.process(connection); }}).start(); } } catch(Exception e) { } // die } public static void main(String[] args) { new Thread(new WebService()).start(); } } class Handler { void process(Socket s) { DataInputStream in = null; DataOutputStream out = null; try { in = new DataInputStream(s.getInputStream()); out = new DataOutputStream(s.getOutputStream()); int request = in.readInt(); int result = -request; // return negation to client out.writeInt(result); } catch(IOException ex) {} // fall through finally { // clean up try { if (in != null) in.close(); } catch (IOException ignore) {} try { if (out != null) out.close(); } catch (IOException ignore) {} try { s.close(); } catch (IOException ignore) {} } } } class OpenCallHost { // Generic code sketch protected long localState; protected final Helper helper = new Helper(); protected synchronized void updateState() { localState = 2; // ...; } public void req() { updateState(); helper.handle(); } } class ThreadPerMessageHost { // Generic code sketch protected long localState; protected final Helper helper = new Helper(); protected synchronized void updateState() { localState = 2; // ...; } public void req() { updateState(); new Thread(new Runnable() { public void run() { helper.handle(); } }).start(); } } interface Executor { void execute(Runnable r); } class HostWithExecutor { // Generic code sketch protected long localState; protected final Helper helper = new Helper(); protected final Executor executor; public HostWithExecutor(Executor e) { executor = e; } protected synchronized void updateState() { localState = 2; // ...; } public void req() { updateState(); executor.execute(new Runnable() { public void run() { helper.handle(); } }); } } class PlainWorkerPool implements Executor { protected final Channel workQueue; public void execute(Runnable r) { try { workQueue.put(r); } catch (InterruptedException ie) { // postpone response Thread.currentThread().interrupt(); } } public PlainWorkerPool(Channel ch, int nworkers) { workQueue = ch; for (int i = 0; i < nworkers; ++i) activate(); } protected void activate() { Runnable runLoop = new Runnable() { public void run() { try { for (;;) { Runnable r = (Runnable)(workQueue.take()); r.run(); } } catch (InterruptedException ie) {} // die } }; new Thread(runLoop).start(); } } class TimerDaemon { // Fragments static class TimerTask implements Comparable { final Runnable command; final long execTime; // time to run at public int compareTo(Object x) { long otherExecTime = ((TimerTask)(x)).execTime; return (execTime < otherExecTime) ? -1 : (execTime == otherExecTime)? 0 : 1; } TimerTask(Runnable r, long t) { command = r; execTime = t; } } // a heap or list with methods that preserve // ordering with respect to TimerTask.compareTo static class PriorityQueue { void put(TimerTask t) {} TimerTask least() { return null; } void removeLeast() {} boolean isEmpty() { return true; } } protected final PriorityQueue pq = new PriorityQueue(); public synchronized void executeAfterDelay(Runnable r,long t){ pq.put(new TimerTask(r, t + System.currentTimeMillis())); notifyAll(); } public synchronized void executeAt(Runnable r, Date time) { pq.put(new TimerTask(r, time.getTime())); notifyAll(); } // wait for and then return next task to run protected synchronized Runnable take() throws InterruptedException { for (;;) { while (pq.isEmpty()) wait(); TimerTask t = pq.least(); long now = System.currentTimeMillis(); long waitTime = now - t.execTime; if (waitTime <= 0) { pq.removeLeast(); return t.command; } else wait(waitTime); } } public TimerDaemon() { activate(); } // only one void activate() { // same as PlainWorkerThread except using above take method } } class SessionTask implements Runnable { // generic code sketch static final int BUFFSIZE = 1024; protected final Socket socket; protected final InputStream input; SessionTask(Socket s) throws IOException { socket = s; input = socket.getInputStream(); } void processCommand(byte[] b, int n) {} void cleanup() {} public void run() { // Normally run in a new thread byte[] commandBuffer = new byte[BUFFSIZE]; try { for (;;) { int bytes = input.read(commandBuffer, 0, BUFFSIZE); if (bytes != BUFFSIZE) break; processCommand(commandBuffer, bytes); } } catch (IOException ex) { cleanup(); } finally { try { input.close(); socket.close(); } catch(IOException ignore) {} } } } class IOEventTask implements Runnable { // generic code sketch static final int BUFFSIZE = 1024; protected final Socket socket; protected final InputStream input; protected volatile boolean done = false; // latches true IOEventTask(Socket s) throws IOException { socket = s; input = socket.getInputStream(); } void processCommand(byte[] b, int n) {} void cleanup() {} public void run() { // trigger only when input available if (done) return; byte[] commandBuffer = new byte[BUFFSIZE]; try { int bytes = input.read(commandBuffer, 0, BUFFSIZE); if (bytes != BUFFSIZE) done = true; else processCommand(commandBuffer, bytes); } catch (IOException ex) { cleanup(); done = true; } finally { if (!done) return; try { input.close(); socket.close(); } catch(IOException ignore) {} } } // Accessor methods needed by triggering agent: boolean done() { return done; } InputStream input() { return input; } } class PollingWorker implements Runnable { // Incomplete private java.util.List tasks = new LinkedList(); // ...; private long sleepTime = 100; // ...; void register(IOEventTask t) { tasks.add(t); } void deregister(IOEventTask t) { tasks.remove(t); } public void run() { try { for (;;) { for (Iterator it = tasks.iterator(); it.hasNext();) { IOEventTask t = (IOEventTask)(it.next()); if (t.done()) deregister(t); else { boolean trigger; try { trigger = t.input().available() > 0; } catch (IOException ex) { trigger = true; // trigger if exception on check } if (trigger) t.run(); } } Thread.sleep(sleepTime); } } catch (InterruptedException ie) {} } } abstract class Box { protected Color color = Color.white; public synchronized Color getColor() { return color; } public synchronized void setColor(Color c) { color = c; } public abstract java.awt.Dimension size(); public abstract Box duplicate(); // clone public abstract void show(Graphics g, Point origin);// display } class BasicBox extends Box { protected Dimension size; public BasicBox(int xdim, int ydim) { size = new Dimension(xdim, ydim); } public synchronized Dimension size() { return size; } public void show(Graphics g, Point origin) { g.setColor(getColor()); g.fillRect(origin.x, origin.y, size.width, size.height); } public synchronized Box duplicate() { Box p = new BasicBox(size.width, size.height); p.setColor(getColor()); return p; } } abstract class JoinedPair extends Box { protected Box fst; // one of the boxes protected Box snd; // the other one protected JoinedPair(Box a, Box b) { fst = a; snd = b; } public synchronized void flip() { // swap fst/snd Box tmp = fst; fst = snd; snd = tmp; } public void show(Graphics g, Point p) {} public Dimension size() { return new Dimension(0,0); } public Box duplicate() { return null; } // other internal helper methods } class HorizontallyJoinedPair extends JoinedPair { public HorizontallyJoinedPair(Box l, Box r) { super(l, r); } public synchronized Box duplicate() { HorizontallyJoinedPair p = new HorizontallyJoinedPair(fst.duplicate(), snd.duplicate()); p.setColor(getColor()); return p; } // ... other implementations of abstract Box methods } class VerticallyJoinedPair extends JoinedPair { public VerticallyJoinedPair(Box l, Box r) { super(l, r); } // similar } class WrappedBox extends Box { protected Dimension wrapperSize; protected Box inner; public WrappedBox(Box innerBox, Dimension size) { inner = innerBox; wrapperSize = size; } public void show(Graphics g, Point p) {} public Dimension size() { return new Dimension(0,0); } public Box duplicate() { return null; } // ... other implementations of abstract Box methods } interface PushSource { void start(); } interface PushStage { void putA(Box p); } interface DualInputPushStage extends PushStage { void putB(Box p); } class DualInputAdapter implements PushStage { protected final DualInputPushStage stage; public DualInputAdapter(DualInputPushStage s) { stage = s; } public void putA(Box p) { stage.putB(p); } } class DevNull implements PushStage { public void putA(Box p) { } } class SingleOutputPushStage { private PushStage next1 = null; protected synchronized PushStage next1() { return next1; } public synchronized void attach1(PushStage s) { next1 = s; } } class DualOutputPushStage extends SingleOutputPushStage { private PushStage next2 = null; protected synchronized PushStage next2() { return next2; } public synchronized void attach2(PushStage s) { next2 = s; } }class Painter extends SingleOutputPushStage implements PushStage { protected final Color color; // the color to paint things public Painter(Color c) { color = c; } public void putA(Box p) { p.setColor(color); next1().putA(p); } } class Wrapper extends SingleOutputPushStage implements PushStage { protected final int thickness; public Wrapper(int t) { thickness = t; } public void putA(Box p) { Dimension d = new Dimension(thickness, thickness); next1().putA(new WrappedBox(p, d)); } } class Flipper extends SingleOutputPushStage implements PushStage { public void putA(Box p) { if (p instanceof JoinedPair) ((JoinedPair) p).flip(); next1().putA(p); } } abstract class Joiner extends SingleOutputPushStage implements DualInputPushStage { protected Box a = null; // incoming from putA protected Box b = null; // incoming from putB protected abstract Box join(Box p, Box q); protected synchronized Box joinFromA(Box p) { while (a != null) // wait until last consumed try { wait(); } catch (InterruptedException e) { return null; } a = p; return tryJoin(); } protected synchronized Box joinFromB(Box p) { // symmetrical while (b != null) try { wait(); } catch (InterruptedException ie) { return null; } b = p; return tryJoin(); } protected synchronized Box tryJoin() { if (a == null || b == null) return null; // cannot join Box joined = join(a, b); // make combined box a = b = null; // forget old boxes notifyAll(); // allow new puts return joined; } public void putA(Box p) { Box j = joinFromA(p); if (j != null) next1().putA(j); } public void putB(Box p) { Box j = joinFromB(p); if (j != null) next1().putA(j); } } class HorizontalJoiner extends Joiner { protected Box join(Box p, Box q) { return new HorizontallyJoinedPair(p, q); } } class VerticalJoiner extends Joiner { protected Box join(Box p, Box q) { return new VerticallyJoinedPair(p, q); } } class Collector extends SingleOutputPushStage implements DualInputPushStage { public void putA(Box p) { next1().putA(p);} public void putB(Box p) { next1().putA(p); } } class Alternator extends DualOutputPushStage implements PushStage { protected boolean outTo2 = false; // control alternation protected synchronized boolean testAndInvert() { boolean b = outTo2; outTo2 = !outTo2; return b; } public void putA(final Box p) { if (testAndInvert()) next1().putA(p); else { new Thread(new Runnable() { public void run() { next2().putA(p); } }).start(); } } } class Cloner extends DualOutputPushStage implements PushStage { public void putA(Box p) { final Box p2 = p.duplicate(); next1().putA(p); new Thread(new Runnable() { public void run() { next2().putA(p2); } }).start(); } } interface BoxPredicate { boolean test(Box p); } class MaxSizePredicate implements BoxPredicate { protected final int max; // max size to let through public MaxSizePredicate(int maximum) { max = maximum; } public boolean test(Box p) { return p.size().height <= max && p.size().width <= max; } } class Screener extends DualOutputPushStage implements PushStage { protected final BoxPredicate predicate; public Screener(BoxPredicate p) { predicate = p; } public void putA(final Box p) { if (predicate.test(p)) { new Thread(new Runnable() { public void run() { next1().putA(p); } }).start(); } else next2().putA(p); } } class BasicBoxSource extends SingleOutputPushStage implements PushSource, Runnable { protected final Dimension size; // maximum sizes protected final int productionTime; // simulated delay public BasicBoxSource(Dimension s, int delay) { size = s; productionTime = delay; } protected Box produce() { return new BasicBox((int)(Math.random() * size.width) + 1, (int)(Math.random() * size.height) + 1); } public void start() { next1().putA(produce()); } public void run() { try { for (;;) { start(); Thread.sleep((int)(Math.random() * 2* productionTime)); } } catch (InterruptedException ie) { } // die } } interface FileReader { void read(String filename, FileReaderClient client); } interface FileReaderClient { void readCompleted(String filename, byte[] data); void readFailed(String filename, IOException ex); } class FileReaderApp implements FileReaderClient { // Fragments protected FileReader reader = new AFileReader(); public void readCompleted(String filename, byte[] data) { // ... use data ... } public void readFailed(String filename, IOException ex){ // ... deal with failure ... } public void actionRequiringFile() { reader.read("AppFile", this); } public void actionNotRequiringFile() { } } class AFileReader implements FileReader { public void read(final String fn, final FileReaderClient c) { new Thread(new Runnable() { public void run() { doRead(fn, c); } }).start(); } protected void doRead(String fn, FileReaderClient client) { byte[] buffer = new byte[1024]; // just for illustration try { FileInputStream s = new FileInputStream(fn); s.read(buffer); if (client != null) client.readCompleted(fn, buffer); } catch (IOException ex) { if (client != null) client.readFailed(fn, ex); } } } class FileApplication implements FileReaderClient { private String[] filenames; private int currentCompletion; // index of ready file public synchronized void readCompleted(String fn, byte[] d) { // wait until ready to process this callback while (!fn.equals(filenames[currentCompletion])) { try { wait(); } catch(InterruptedException ex) { return; } } // ... process data... // wake up any other thread waiting on this condition: ++currentCompletion; notifyAll(); } public synchronized void readFailed(String fn, IOException e){ // similar... } public synchronized void readfiles() { AFileReader reader = new AFileReader(); currentCompletion = 0; for (int i = 0; i < filenames.length; ++i) reader.read(filenames[i],this); } } interface Pic { byte[] getImage(); } interface Renderer { Pic render(URL src); } class StandardRenderer implements Renderer { public Pic render(URL src) { return null ; } } class PictureApp { // Code sketch // ... private final Renderer renderer = new StandardRenderer(); void displayBorders() {} void displayCaption() {} void displayImage(byte[] b) {} void cleanup() {} public void show(final URL imageSource) { class Waiter implements Runnable { private Pic result = null; Pic getResult() { return result; } public void run() { result = renderer.render(imageSource); } }; Waiter waiter = new Waiter(); Thread t = new Thread(waiter); t.start(); displayBorders(); // do other things displayCaption(); // while rendering try { t.join(); } catch(InterruptedException e) { cleanup(); return; } Pic pic = waiter.getResult(); if (pic != null) displayImage(pic.getImage()); else {} // ... deal with assumed rendering failure } } class AsynchRenderer implements Renderer { private final Renderer renderer = new StandardRenderer(); static class FuturePic implements Pic { // inner class private Pic pic = null; private boolean ready = false; synchronized void setPic(Pic p) { pic = p; ready = true; notifyAll(); } public synchronized byte[] getImage() { while (!ready) try { wait(); } catch (InterruptedException e) { return null; } return pic.getImage(); } } public Pic render(final URL src) { final FuturePic p = new FuturePic(); new Thread(new Runnable() { public void run() { p.setPic(renderer.render(src)); } }).start(); return p; } } class PicturAppWithFuture { // Code sketch private final Renderer renderer = new AsynchRenderer(); void displayBorders() {} void displayCaption() {} void displayImage(byte[] b) {} void cleanup() {} public void show(final URL imageSource) { Pic pic = renderer.render(imageSource); displayBorders(); // do other things ... displayCaption(); byte[] im = pic.getImage(); if (im != null) displayImage(im); else {} // deal with assumed rendering failure } } class FutureResult { // Fragments protected Object value = null; protected boolean ready = false; protected InvocationTargetException exception = null; public synchronized Object get() throws InterruptedException, InvocationTargetException { while (!ready) wait(); if (exception != null) throw exception; else return value; } public Runnable setter(final Callable function) { return new Runnable() { public void run() { try { set(function.call()); } catch(Throwable e) { setException(e); } } }; } synchronized void set(Object result) { value = result; ready = true; notifyAll(); } synchronized void setException(Throwable e) { exception = new InvocationTargetException(e); ready = true; notifyAll(); } // ... other auxiliary and convenience methods ... } class PictureDisplayWithFutureResult { // Code sketch void displayBorders() {} void displayCaption() {} void displayImage(byte[] b) {} void cleanup() {} private final Renderer renderer = new StandardRenderer(); // ... public void show(final URL imageSource) { try { FutureResult futurePic = new FutureResult(); Runnable command = futurePic.setter(new Callable() { public Object call() { return renderer.render(imageSource); } }); new Thread(command).start(); displayBorders(); displayCaption(); displayImage(((Pic)(futurePic.get())).getImage()); } catch (InterruptedException ex) { cleanup(); return; } catch (InvocationTargetException ex) { cleanup(); return; } } } interface Disk { void read(int cylinderNumber, byte[] buffer) throws Failure; void write(int cylinderNumber, byte[] buffer) throws Failure; } abstract class DiskTask implements Runnable { protected final int cylinder; // read/write parameters protected final byte[] buffer; protected Failure exception = null; // to relay out protected DiskTask next = null; // for use in queue protected final Latch done = new Latch(); // status indicator DiskTask(int c, byte[] b) { cylinder = c; buffer = b; } abstract void access() throws Failure; // read or write public void run() { try { access(); } catch (Failure ex) { setException(ex); } finally { done.release(); } } void awaitCompletion() throws InterruptedException { done.acquire(); } synchronized Failure getException() { return exception; } synchronized void setException(Failure f) { exception = f; } } class DiskReadTask extends DiskTask { DiskReadTask(int c, byte[] b) { super(c, b); } void access() throws Failure { /* ... raw read ... */ } } class DiskWriteTask extends DiskTask { DiskWriteTask(int c, byte[] b) { super(c, b); } void access() throws Failure { /* ... raw write ... */ } } class ScheduledDisk implements Disk { protected final DiskTaskQueue tasks = new DiskTaskQueue(); public void read(int c, byte[] b) throws Failure { readOrWrite(new DiskReadTask(c, b)); } public void write(int c, byte[] b) throws Failure { readOrWrite(new DiskWriteTask(c, b)); } protected void readOrWrite(DiskTask t) throws Failure { tasks.put(t); try { t.awaitCompletion(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); // propagate throw new Failure(); // convert to failure exception } Failure f = t.getException(); if (f != null) throw f; } public ScheduledDisk() { // construct worker thread new Thread(new Runnable() { public void run() { try { for (;;) { tasks.take().run(); } } catch (InterruptedException ex) {} // die } }).start(); } } class DiskTaskQueue { protected DiskTask thisSweep = null; protected DiskTask nextSweep = null; protected int currentCylinder = 0; protected final Semaphore available = new Semaphore(0); void put(DiskTask t) { insert(t); available.release(); } DiskTask take() throws InterruptedException { available.acquire(); return extract(); } synchronized void insert(DiskTask t) { DiskTask q; if (t.cylinder >= currentCylinder) { // determine queue q = thisSweep; if (q == null) { thisSweep = t; return; } } else { q = nextSweep; if (q == null) { nextSweep = t; return; } } DiskTask trail = q; // ordered linked list insert q = trail.next; for (;;) { if (q == null || t.cylinder < q.cylinder) { trail.next = t; t.next = q; return; } else { trail = q; q = q.next; } } } synchronized DiskTask extract() { // PRE: not empty if (thisSweep == null) { // possibly swap queues thisSweep = nextSweep; nextSweep = null; } DiskTask t = thisSweep; thisSweep = t.next; currentCylinder = t.cylinder; return t; } } class Fib extends FJTask { static final int sequentialThreshold = 13; // for tuning volatile int number; // argument/result Fib(int n) { number = n; } int seqFib(int n) { if (n <= 1) return n; else return seqFib(n-1) + seqFib(n-2); } int getAnswer() { if (!isDone()) throw new IllegalStateException("Not yet computed"); return number; } public void run() { int n = number; if (n <= sequentialThreshold) // base case number = seqFib(n); else { Fib f1 = new Fib(n - 1); // create subtasks Fib f2 = new Fib(n - 2); coInvoke(f1, f2); // fork then join both number = f1.number + f2.number; // combine results } } public static void main(String[] args) { // sample driver try { int groupSize = 2; // 2 worker threads int num = 35; // compute fib(35) FJTaskRunnerGroup group = new FJTaskRunnerGroup(groupSize); Fib f = new Fib(num); group.invoke(f); int result = f.getAnswer(); System.out.println("Answer: " + result); } catch (InterruptedException ex) {} // die } } class FibVL extends FJTask { static final int sequentialThreshold = 13; // for tuning volatile int number; // as before final FibVL next; // embedded linked list of sibling tasks FibVL(int n, FibVL list) { number = n; next = list; } int seqFib(int n) { if (n <= 1) return n; else return seqFib(n-1) + seqFib(n-2); } public void run() { int n = number; if (n <= sequentialThreshold) number = seqFib(n); else { FibVL forked = null; // list of subtasks forked = new FibVL(n - 1, forked); // prepends to list forked.fork(); forked = new FibVL(n - 2, forked); forked.fork(); number = accumulate(forked); } } // Traverse list, joining each subtask and adding to result int accumulate(FibVL list) { int r = 0; for (FibVL f = list; f != null; f = f.next) { f.join(); r += f.number; } return r; } } class FibVCB extends FJTask { static final int sequentialThreshold = 13; // for tuning // ... volatile int number = 0; // as before final FibVCB parent; // Is null for outermost call int callbacksExpected = 0; volatile int callbacksReceived = 0; FibVCB(int n, FibVCB p) { number = n; parent = p; } int seqFib(int n) { if (n <= 1) return n; else return seqFib(n-1) + seqFib(n-2); } // Callback method invoked by subtasks upon completion synchronized void addToResult(int n) { number += n; ++callbacksReceived; } public void run() { // same structure as join-based version int n = number; if (n <= sequentialThreshold) number = seqFib(n); else { // clear number so subtasks can fill in number = 0; // establish number of callbacks expected callbacksExpected = 2; new FibVCB(n - 1, this).fork(); new FibVCB(n - 2, this).fork(); // Wait for callbacks from children while (callbacksReceived < callbacksExpected) yield(); } // Call back parent if (parent != null) parent.addToResult(number); } } class NQueens extends FJTask { static int boardSize; // fixed after initialization in main // Boards are arrays where each cell represents a row, // and holds the column number of the queen in that row static class Result { // holder for ultimate result private int[] board = null; // non-null when solved synchronized boolean solved() { return board != null; } synchronized void set(int[] b) { // Support use by non-Tasks if (board == null) { board = b; notifyAll(); } } synchronized int[] await() throws InterruptedException { while (board == null) wait(); return board; } } static final Result result = new Result(); public static void main(String[] args) { try { boardSize = 8; // ...; FJTaskRunnerGroup tasks = new FJTaskRunnerGroup(4); int[] initialBoard = new int[0]; // start with empty board tasks.execute(new NQueens(initialBoard)); int[] board = result.await(); } catch (InterruptedException ie) {} // ... } final int[] sofar; // initial configuration NQueens(int[] board) { this.sofar = board; } public void run() { if (!result.solved()) { // skip if already solved int row = sofar.length; if (row >= boardSize) // done result.set(sofar); else { // try all expansions for (int q = 0; q < boardSize; ++q) { // Check if queen can be placed in column q of next row boolean attacked = false; for (int i = 0; i < row; ++i) { int p = sofar[i]; if (q == p || q == p - (row-i) || q == p + (row-i)) { attacked = true; break; } } // If so, fork to explore moves from new configuration if (!attacked) { // build extended board representation int[] next = new int[row+1]; for (int k = 0; k < row; ++k) next[k] = sofar[k]; next[row] = q; new NQueens(next).fork(); } } } } } } abstract class JTree extends FJTask { volatile double maxDiff; // for convergence check } class Interior extends JTree { private final JTree[] quads; Interior(JTree q1, JTree q2, JTree q3, JTree q4) { quads = new JTree[] { q1, q2, q3, q4 }; } public void run() { coInvoke(quads); double md = 0.0; for (int i = 0; i < quads.length; ++i) { md = Math.max(md,quads[i].maxDiff); quads[i].reset(); } maxDiff = md; } } class Leaf extends JTree { private final double[][] A; private final double[][] B; private final int loRow; private final int hiRow; private final int loCol; private final int hiCol; private int steps = 0; Leaf(double[][] A, double[][] B, int loRow, int hiRow, int loCol, int hiCol) { this.A = A; this.B = B; this.loRow = loRow; this.hiRow = hiRow; this.loCol = loCol; this.hiCol = hiCol; } public synchronized void run() { boolean AtoB = (steps++ % 2) == 0; double[][] a = (AtoB)? A : B; double[][] b = (AtoB)? B : A; double md = 0.0; for (int i = loRow; i <= hiRow; ++i) { for (int j = loCol; j <= hiCol; ++j) { b[i][j] = 0.25 * (a[i-1][j] + a[i][j-1] + a[i+1][j] + a[i][j+1]); md = Math.max(md, Math.abs(b[i][j] - a[i][j])); } } maxDiff = md; } } class Jacobi extends FJTask { static final double EPSILON = 0.001; // convergence criterion final JTree root; final int maxSteps; Jacobi(double[][] A, double[][] B, int firstRow, int lastRow, int firstCol, int lastCol, int maxSteps, int leafCells) { this.maxSteps = maxSteps; root = build(A, B, firstRow, lastRow, firstCol, lastCol, leafCells); } public void run() { for (int i = 0; i < maxSteps; ++i) { invoke(root); if (root.maxDiff < EPSILON) { System.out.println("Converged"); return; } else root.reset(); } } static JTree build(double[][] a, double[][] b, int lr, int hr, int lc, int hc, int size) { if ((hr - lr + 1) * (hc - lc + 1) <= size) return new Leaf(a, b, lr, hr, lc, hc); int mr = (lr + hr) / 2; // midpoints int mc = (lc + hc) / 2; return new Interior(build(a, b, lr, mr, lc, mc, size), build(a, b, lr, mr, mc+1, hc, size), build(a, b, mr+1, hr, lc, mc, size), build(a, b, mr+1, hr, mc+1, hc, size)); } } class CyclicBarrier { protected final int parties; protected int count; // parties currently being waited for protected int resets = 0; // times barrier has been tripped CyclicBarrier(int c) { count = parties = c; } synchronized int barrier() throws InterruptedException { int index = --count; if (index > 0) { // not yet tripped int r = resets; // wait until next reset do { wait(); } while (resets == r); } else { // trip count = parties; // reset count for next time ++resets; notifyAll(); // cause all other parties to resume } return index; } } class Segment implements Runnable { // Code sketch final CyclicBarrier bar; // shared by all segments Segment(CyclicBarrier b) { bar = b; } void update() { } public void run() { // ... try { for (int i = 0; i < 10 /* iterations */; ++i) { update(); bar.barrier(); } } catch (InterruptedException ie) {} // ... } } class Problem { int size; } class Driver { // ... int granularity = 1; void compute(Problem problem) throws Exception { int n = problem.size / granularity; CyclicBarrier barrier = new CyclicBarrier(n); Thread[] threads = new Thread[n]; // create for (int i = 0; i < n; ++i) threads[i] = new Thread(new Segment(barrier)); // trigger for (int i = 0; i < n; ++i) threads[i].start(); // await termination for (int i = 0; i < n; ++i) threads[i].join(); } } class JacobiSegment implements Runnable { // Incomplete // These are same as in Leaf class version: static final double EPSILON = 0.001; double[][] A; double[][] B; final int firstRow; final int lastRow; final int firstCol; final int lastCol; volatile double maxDiff; int steps = 0; void update() { /* Nearly same as Leaf.run */ } final CyclicBarrier bar; final JacobiSegment[] allSegments; // needed for convergence check volatile boolean converged = false; JacobiSegment(double[][] A, double[][] B, int firstRow, int lastRow, int firstCol, int lastCol, CyclicBarrier b, JacobiSegment[] allSegments) { this.A = A; this.B = B; this.firstRow = firstRow; this.lastRow = lastRow; this.firstCol = firstCol; this.lastCol = lastCol; this.bar = b; this.allSegments = allSegments; } public void run() { try { while (!converged) { update(); int myIndex = bar.barrier(); // wait for all to update if (myIndex == 0) convergenceCheck(); bar.barrier(); // wait for convergence check } } catch(Exception ex) { // clean up ... } } void convergenceCheck() { for (int i = 0; i < allSegments.length; ++i) if (allSegments[i].maxDiff > EPSILON) return; for (int i = 0; i < allSegments.length; ++i) allSegments[i].converged = true; } } class ActiveRunnableExecutor extends Thread { Channel me = null; // ... // used for all incoming messages public void run() { try { for (;;) { ((Runnable)(me.take())).run(); } } catch (InterruptedException ie) {} // die } } //import jcsp.lang.*; class Fork implements jcsp.lang.CSProcess { private final jcsp.lang.AltingChannelInput[] fromPhil; Fork(jcsp.lang.AltingChannelInput l, jcsp.lang.AltingChannelInput r) { fromPhil = new jcsp.lang.AltingChannelInput[] { l, r }; } public void run() { jcsp.lang.Alternative alt = new jcsp.lang.Alternative(fromPhil); for (;;) { int i = alt.select(); // await message from either fromPhil[i].read(); // pick up fromPhil[i].read(); // put down } } } class Butler implements jcsp.lang.CSProcess { private final jcsp.lang.AltingChannelInput[] enters; private final jcsp.lang.AltingChannelInput[] exits; Butler(jcsp.lang.AltingChannelInput[] e, jcsp.lang.AltingChannelInput[] x) { enters = e; exits = x; } public void run() { int seats = enters.length; int nseated = 0; // set up arrays for select jcsp.lang.AltingChannelInput[] chans = new jcsp.lang.AltingChannelInput[2*seats]; for (int i = 0; i < seats; ++i) { chans[i] = exits[i]; chans[seats + i] = enters[i]; } jcsp.lang.Alternative either = new jcsp.lang.Alternative(chans); jcsp.lang.Alternative exit = new jcsp.lang.Alternative(exits); for (;;) { // if max number are seated, only allow exits jcsp.lang.Alternative alt = (nseated < seats-1)? either : exit; int i = alt.fairSelect(); chans[i].read(); // if i is in first half of array, it is an exit message if (i < seats) --nseated; else ++nseated; } } } class Philosopher implements jcsp.lang.CSProcess { private final jcsp.lang.ChannelOutput leftFork; private final jcsp.lang.ChannelOutput rightFork; private final jcsp.lang.ChannelOutput enter; private final jcsp.lang.ChannelOutput exit; Philosopher(jcsp.lang.ChannelOutput l, jcsp.lang.ChannelOutput r, jcsp.lang.ChannelOutput e, jcsp.lang.ChannelOutput x) { leftFork = l; rightFork = r; enter = e; exit = x; } public void run() { for (;;) { think(); enter.write(null); // get seat leftFork.write(null); // pick up left rightFork.write(null); // pick up right eat(); leftFork.write(null); // put down left rightFork.write(null); // put down right exit.write(null); // leave seat } } private void eat() {} private void think() {} } class College implements jcsp.lang.CSProcess { final static int N = 5; private final jcsp.lang.CSProcess action; College() { jcsp.lang.One2OneChannel[] lefts = jcsp.lang.One2OneChannel.create(N); jcsp.lang.One2OneChannel[] rights = jcsp.lang.One2OneChannel.create(N); jcsp.lang.One2OneChannel[] enters = jcsp.lang.One2OneChannel.create(N); jcsp.lang.One2OneChannel[] exits = jcsp.lang.One2OneChannel.create(N); Butler butler = new Butler(enters, exits); Philosopher[] phils = new Philosopher[N]; for (int i = 0; i < N; ++i) phils[i] = new Philosopher(lefts[i], rights[i], enters[i], exits[i]); Fork[] forks = new Fork[N]; for (int i = 0; i < N; ++i) forks[i] = new Fork(rights[(i + 1) % N], lefts[i]); action = new jcsp.lang.Parallel( new jcsp.lang.CSProcess[] { butler, new jcsp.lang.Parallel(phils), new jcsp.lang.Parallel(forks) }); } public void run() { action.run(); } public static void main(String[] args) { new College().run(); } }
Ericliu001/BigBangJava
src/main/resources/DougLea.java
Java
mit
121,587
/** * Pipedrive API v1 * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. * */ import ApiClient from '../ApiClient'; /** * The UpdateFileRequest model module. * @module model/UpdateFileRequest * @version 1.0.0 */ class UpdateFileRequest { /** * Constructs a new <code>UpdateFileRequest</code>. * @alias module:model/UpdateFileRequest */ constructor() { UpdateFileRequest.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>UpdateFileRequest</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/UpdateFileRequest} obj Optional instance to populate. * @return {module:model/UpdateFileRequest} The populated <code>UpdateFileRequest</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new UpdateFileRequest(); if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); delete data['name']; } if (data.hasOwnProperty('description')) { obj['description'] = ApiClient.convertToType(data['description'], 'String'); delete data['description']; } if (Object.keys(data).length > 0) { obj['extra'] = data; } } return obj; } } /** * Visible name of the file * @member {String} name */ UpdateFileRequest.prototype['name'] = undefined; /** * Description of the file * @member {String} description */ UpdateFileRequest.prototype['description'] = undefined; export default UpdateFileRequest;
pipedrive/client-nodejs
src/model/UpdateFileRequest.js
JavaScript
mit
2,415
""" Example ------- class SystemSetting(KVModel): pass setting = SystemSetting.create(key='foo', value=100) loaded_setting = SystemSetting.get_by_key('foo') """ from django.db import models from .fields import SerializableField class KVModel(models.Model): """ An Abstract model that has key and value fields key -- Unique CharField of max_length 255 value -- SerializableField by default could be used to store bool, int, float, str, list, dict and date """ key = models.CharField(max_length=255, unique=True) value = SerializableField(blank=True, null=True) def __unicode__(self): return 'KVModel instance: ' + self.key + ' = ' + unicode(self.value) @classmethod def get_by_key(cls, key): """ A static method that returns a KVModel instance. key -- unique key that is used for the search. this method will throw a DoesNotExist exception if an object with the key provided is not found. """ return cls.objects.get(key=key) class Meta: abstract = True
amdorra/django-kvmodel
kvmodel/models.py
Python
mit
1,100
<?php return array ( 'id' => 'opwv_sdk_ver1_sub40wpk010149', 'fallback' => 'uptext_generic', 'capabilities' => array ( ), );
cuckata23/wurfl-data
data/opwv_sdk_ver1_sub40wpk010149.php
PHP
mit
136
<?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $this->call(UsersTableSeeder::class); $this->call(CoursesTableSeeder::class); //$this->call(RepositoryTableSeeder::class); } }
guelph-code-ninjas/core
database/seeds/DatabaseSeeder.php
PHP
mit
339
<?php namespace Chebur\SphinxBundle\Sphinx\Connection; use Foolz\SphinxQL\Drivers\Mysqli\Connection as FoolzMysqliConnection; class MysqliConnection extends FoolzMysqliConnection implements ConnectionInterface { /** * потому что Exception лучше error * @var bool */ protected $silence_connection_warning = true; }
vchebotarev/sphinx-bundle
Sphinx/Connection/MysqliConnection.php
PHP
mit
355
export default class ContestType { constructor(options) { let _id = null; let _name = null; let _berryFlavor = null; let _color = null; Object.defineProperty(this, 'id', { enumarable: true, get() { return _id; } }); Object.defineProperty(this, 'name', { enumarable: true, get() { return _name; } }); Object.defineProperty(this, 'berryFlavor', { enumerable: true, get() { return _berryFlavor; } }); Object.defineProperty(this, 'color', { enumerable: true, get() { return _color; } }); _id = parseInt(options.id) || null; _name = options.name || "No name"; _berryFlavor = options.berryFlavor || "No flavor"; _color = options.color || "No color"; Object.seal(this); } }
milk-shake/electron-pokemon
app/js/entities/contestType.js
JavaScript
mit
850
<?php /** * */ class M_login extends CI_Model{ public function login_authen($username, $password){ $this->db->select('*'); $this->db->where('username', $username); $this->db->where('password', $password); $this->db->from('user'); $query = $this->db->get(); if ($query->num_rows() == 1) { return true; } else{ return false; } } }
ericsrizal/kopiganes
application/models/M_login.php
PHP
mit
441
#include <map> #include <assert.h> #include <exception> #include "pf/base/string.h" #include "pf/file/database.h" namespace pf_file { Database::Database(uint32_t id) { __ENTER_FUNCTION id_ = id; string_buffer_ = NULL; index_column_ = -1; record_number_ = 0; __LEAVE_FUNCTION } Database::~Database() { __ENTER_FUNCTION SAFE_DELETE_ARRAY(string_buffer_); __LEAVE_FUNCTION } bool Database::open_from_txt(const char *filename) { __ENTER_FUNCTION assert(filename); FILE* fp = fopen(filename, "rb"); if (NULL == fp) return false; fseek(fp, 0, SEEK_END); int32_t filesize = ftell(fp); fseek(fp, 0, SEEK_SET); //read in memory char *memory = new char[filesize + 1]; memset(memory, 0, filesize + 1); //use memset to memory pointer fread(memory, 1, filesize, fp); fclose(fp); memory[filesize] = '\0'; bool result = open_from_memory(memory, memory + filesize + 1, filename); SAFE_DELETE_ARRAY(memory); return result; __LEAVE_FUNCTION return false; } bool Database::open_from_memory(const char *memory, const char *end, const char *filename) { __ENTER_FUNCTION bool result = true; if (end - memory >= static_cast<int32_t>(sizeof(file_head_t)) && *((uint32_t*)memory) == FILE_DATABASE_INDENTIFY) { result = open_from_memory_binary(memory, end, filename); } else { result = open_from_memory_text(memory, end, filename); } return result; __LEAVE_FUNCTION return false; } const Database::field_data* Database::search_index_equal(int32_t index) const { __ENTER_FUNCTION field_hashmap::const_iterator it_find = hash_index_.find(index); if (it_find == hash_index_.end()) return NULL; return it_find->second; __LEAVE_FUNCTION return NULL; } const char *Database::get_fieldname(int32_t index) { __ENTER_FUNCTION const char *name = NULL; Assert(index >= 0 && index <= field_number_); name = fieldnames_[index].c_str(); return name; __LEAVE_FUNCTION return NULL; } int32_t Database::get_fieldindex(const char *name) { __ENTER_FUNCTION int32_t result = -1; uint32_t i; for (i = 0; i < fieldnames_.size(); ++i) { if (0 == strcmp(name, fieldnames_[i].c_str())) { result = i; break; } } return result; __LEAVE_FUNCTION return -1; } uint8_t Database::get_fieldtype(int32_t index) { __ENTER_FUNCTION Assert(index >= 0 && index <= field_number_); uint8_t result = static_cast<uint8_t>(type_[index]); return result; __LEAVE_FUNCTION return kTypeString; } const Database::field_data *Database::search_position(int32_t line, int32_t column) const { __ENTER_FUNCTION int32_t position = line * get_field_number() + column; if (line < 0 || position > static_cast<int32_t>(data_buffer_.size())) { char temp[256]; memset(temp, '\0', sizeof(temp)); snprintf(temp, sizeof(temp) - 1, "pf_file::Database::search_position is failed," " position out for range[line:%d, column:%d] position:%d", line, column, position); #ifdef _PF_THROW_EXCEPTION_AS_STD_STRING throw std::string(temp); #else AssertEx(false, temp); #endif return NULL; } return &(data_buffer_[position]); __LEAVE_FUNCTION return NULL; } const Database::field_data* Database::search_first_column_equal( int32_t column, const field_data &value) const { __ENTER_FUNCTION if (column < 0 || column > field_number_) return NULL; field_type_enum type = type_[column]; register int32_t i; for (i = 0; i < record_number_; ++i) { const field_data &_field_data = data_buffer_[(field_number_ * i) + column]; bool result; if (kTypeInt == type) { result = field_equal(kTypeInt, _field_data, value); } else if (kTypeFloat == type) { result = field_equal(kTypeFloat, _field_data, value); } else { result = field_equal(kTypeString, _field_data, value); } if (result) { return &(data_buffer_[field_number_ * i]); } } return NULL; __LEAVE_FUNCTION return NULL; } uint32_t Database::get_id() const { __ENTER_FUNCTION return id_; __LEAVE_FUNCTION return 0; } int32_t Database::get_field_number() const { __ENTER_FUNCTION return field_number_; __LEAVE_FUNCTION return -1; } int32_t Database::get_record_number() const { __ENTER_FUNCTION return record_number_; __LEAVE_FUNCTION return -1; } void Database::create_index(int32_t column, const char *filename) { __ENTER_FUNCTION if (column < 0 || column > field_number_ || index_column_ == column) return; hash_index_.clear(); int32_t i; for (i = 0; i < record_number_; ++i) { field_data* _field_data = &(data_buffer_[i * field_number_]); field_hashmap::iterator it_find = hash_index_.find(_field_data->int_value); if (it_find != hash_index_.end()) { char temp[256]; memset(temp, '\0', sizeof(temp)); snprintf(temp, sizeof(temp) - 1, "[%s]multi index at line: %d(smae value: %d)", filename, i + 1, _field_data->int_value); #ifdef _PF_THROW_EXCEPTION_AS_STD_STRING throw std::string(temp); #else AssertEx(false, temp); #endif } hash_index_.insert(std::make_pair(_field_data->int_value, _field_data)); } __LEAVE_FUNCTION } const char *Database::get_line_from_memory(char *str, int32_t size, const char *memory, const char *end) { __ENTER_FUNCTION register const char *_memory = memory; if (_memory >= end || 0 == *_memory) return NULL; while (_memory < end && _memory - memory + 1 < size && *_memory != 0 && *_memory != '\n' && *_memory != '\r') { *(str++) = *(_memory++); } *str = 0; while (_memory < end && *_memory != 0 && (*_memory == '\r' || *_memory == '\n')) ++_memory; return _memory; __LEAVE_FUNCTION return NULL; } bool Database::field_equal(field_type_enum type, const field_data &a, const field_data &b) { __ENTER_FUNCTION bool result = false; if (kTypeInt == type) { result = a.int_value == b.int_value; } else if (kTypeFloat == type) { result = a.float_value == b.float_value; } else { try { result = 0 == strcmp(a.string_value, b.string_value); } catch(...) { //do nothing } } return result; __LEAVE_FUNCTION return false; } bool Database::open_from_memory_text(const char *memory, const char *end, const char *filename) { __ENTER_FUNCTION using namespace pf_base; char line[(1024 * 10) + 1]; //long string memset(line, '\0', sizeof(line)); register const char *_memory = memory; _memory = get_line_from_memory(line, sizeof(line) - 1, _memory, end); if (!_memory) return false; std::vector<std::string> result; string::explode(line, result, "\t", true, true); if (result.empty()) return false; field_type _field_type; _field_type.resize(result.size()); int32_t i; uint32_t result_size = static_cast<uint32_t>(result.size()); for (i = 0; i < static_cast<int32_t>(result_size); ++i) { if ("INT" == result[i]) { _field_type[i] = kTypeInt; } else if("FLOAT" == result[i]) { _field_type[i] = kTypeFloat; } else if("STRING" == result[i]) { _field_type[i] = kTypeString; } else { return false; } } //init int32_t record_number = 0; int32_t field_number = static_cast<int32_t>(_field_type.size()); std::vector<std::pair<std::string, int32_t> > string_buffer; std::map<std::string, int32_t> map_string_buffer; _memory = get_line_from_memory(line, sizeof(line) - 1, _memory, end); //第二行为列名(相当于数据库的字段名),应尽量使用英文 string::explode(line, fieldnames_, "\t", true, true); if (!_memory) return false; int32_t string_buffer_size = 0; bool loop = true; do { //以行读取数据 _memory = get_line_from_memory(line, sizeof(line) - 1, _memory, end); if (!_memory) break; if ('#' == line[0]) continue; //注释行 string::explode(line, result, "\t", true, false); if (result.empty()) continue; //空行 if (static_cast<int32_t>(result.size()) != field_number) { //列数不对 int32_t left_number = field_number - static_cast<int32_t>(result.size()); for (i = 0; i < left_number; ++i) { result.push_back(""); } } if (result[0].empty()) continue; for (i = 0; i < field_number; ++i) { field_data _field_data; switch(_field_type[i]) { case kTypeInt: { _field_data.int_value = atoi(result[i].c_str()); data_buffer_.push_back(_field_data); break; } case kTypeFloat: { _field_data.float_value = static_cast<float>(atof(result[i].c_str())); data_buffer_.push_back(_field_data); break; } case kTypeString: { #ifdef FILE_DATABASE_CONVERT_GBK_TO_UTF8 const char *value = result[i].c_str(); //convert charset //utf8 -> gbk 1.5multiple length int32_t convert_strlength = static_cast<int32_t>(strlen(value) * 2); char *convert_str = new char[convert_strlength]; memset(convert_str, 0, convert_strlength); int32_t convert_result = string::charset_convert("GBK", "UTF-8", convert_str, convert_strlength, value, static_cast<int32_t>(strlen(value))); if (convert_result > 0) { value = convert_str; result[i] = convert_str; } SAFE_DELETE_ARRAY(convert_str); #endif std::map<std::string, int32_t>::iterator it = map_string_buffer.find(result[i]); if (it == map_string_buffer.end()) { string_buffer.push_back( std::make_pair(result[i], string_buffer_size)); map_string_buffer.insert( std::make_pair(result[i], static_cast<int32_t>(string_buffer.size()) - 1)); _field_data.int_value = string_buffer_size + 1; string_buffer_size += static_cast<int32_t>(strlen(result[i].c_str())) + 1; } else { _field_data.int_value = string_buffer[it->second].second + 1; } data_buffer_.push_back(_field_data); break; } default: { return false; } } } ++record_number; } while (loop); //database init record_number_ = record_number; field_number_ = field_number; string_buffer_size_ = string_buffer_size + 1; string_buffer_ = new char[string_buffer_size_]; type_ = _field_type; unsigned char blank = '\0'; USE_PARAM(blank); string_buffer_[0] = '\0'; register char *temp = string_buffer_ + 1; for (i = 0; i < static_cast<int32_t>(string_buffer.size()); ++i) { memcpy(temp, string_buffer[i].first.c_str(), string_buffer[i].first.size()); temp += string_buffer[i].first.size(); *(temp++) = '\0'; } //relocate string block register uint16_t m, n; for (m = 0; m < field_number; ++m) { if (type_[m] != kTypeString) continue; for (n = 0; n < record_number; ++n) { field_data &_field_data1 = data_buffer_[(n * field_number) + m]; _field_data1.string_value = string_buffer_ + _field_data1.int_value; } } create_index(0, filename); return true; __LEAVE_FUNCTION return false; } bool Database::open_from_memory_binary(const char *memory, const char *end, const char *filename) { __ENTER_FUNCTION register const char *_memory = memory; file_head_t file_head; memcpy(&file_head, _memory, sizeof(file_head_t)); if (file_head.identify != FILE_DATABASE_INDENTIFY) return false; //check memory size if (sizeof(file_head) + sizeof(uint32_t) * file_head.field_number + sizeof(field_data) * file_head.record_number * file_head.field_number + + file_head.string_block_size > static_cast<uint64_t>(end - memory)) { return false; } _memory += sizeof(file_head); //init record_number_ = file_head.record_number; field_number_ = file_head.field_number; string_buffer_size_= file_head.string_block_size; //create string blok string_buffer_ = new char[string_buffer_size_]; if (!string_buffer_) return false; std::vector<uint32_t> field_type; field_type.resize(field_number_); memcpy(&(field_type[0]), _memory, sizeof(uint32_t) * field_number_); //check it type_.resize(field_number_); int32_t i; for (i = 0; i < field_number_; ++i) { switch(field_type[i]) { case kTypeInt: { //do nothing } case kTypeFloat: { //do nothing } case kTypeString: { type_[i] = static_cast<field_type_enum>(field_type[i]); break; } default: { SAFE_DELETE_ARRAY(string_buffer_); return false; } } } //read all field data_buffer_.resize(field_number_ * record_number_); memcpy(&(data_buffer_[0]), _memory, sizeof(field_data) * field_number_ * record_number_); _memory += sizeof(field_data) * field_number_ * record_number_; memcpy(string_buffer_, _memory, string_buffer_size_); string_buffer_[string_buffer_size_ - 1] = '\0'; //runtime address for (i = 0; i < field_number_; ++i) { if (field_type[i] != kTypeString) continue; std::string str; int32_t j; for (j = 0; j < record_number_; ++j) { data_buffer_[i + field_number_ + j].string_value += reinterpret_cast<uint64_t>(string_buffer_); } } create_index(0, filename); __LEAVE_FUNCTION return false; } bool Database::save_tobinary(const char *filename) { __ENTER_FUNCTION file_head_t filehead; filehead.field_number = field_number_; filehead.record_number = record_number_; filehead.string_block_size = string_buffer_size_; FILE *fp = fopen(filename, "wb"); if (NULL == fp) return false; fwrite(&filehead, sizeof(filehead), 1, fp); fwrite(&(type_[0]), sizeof(field_type_enum) *filehead.field_number, 1, fp); fwrite(&(data_buffer_[0]), filehead.field_number * filehead.record_number, 1, fp); fwrite(string_buffer_, filehead.string_block_size, 1, fp); fclose(fp); return true; __LEAVE_FUNCTION return false; } bool Database::save_totext(const char *filename) { __ENTER_FUNCTION FILE *fp = fopen(filename, "wb"); if (NULL == fp) return false; for(int i=0; i< static_cast<int>(type_.size()); ++i){ if(type_[i] == kTypeInt){ char temp[64] = {0}; snprintf(temp, sizeof(temp) - 1, "INT"); fwrite(temp, strlen(temp), 1, fp); } else if(type_[i] == kTypeFloat){ char temp[64] = {0}; snprintf(temp, sizeof(temp) - 1, "FLOAT"); fwrite(temp, strlen(temp), 1, fp); } else if(type_[i] == kTypeString){ char temp[64] = {0}; snprintf(temp, sizeof(temp) - 1, "STRING"); fwrite(temp, strlen(temp), 1, fp); } if(i == static_cast<int>(type_.size()-1)){ fwrite("\n", 1, 1, fp); } else{ fwrite("\t", 1, 1, fp); } } for(int i=0; i<static_cast<int>(fieldnames_.size()); ++i){ char temp[64] = {0}; snprintf(temp, sizeof(temp) - 1, fieldnames_[i].c_str()); fwrite(temp, strlen(temp), 1, fp); if(i == static_cast<int>(fieldnames_.size()-1)){ fwrite("\n", 1, 1, fp); } else{ fwrite("\t", 1, 1, fp); } } for (int32_t line = 0; line < record_number_; ++line) { for (int32_t column = 0; column < field_number_; ++column) { const field_data *_field_data = search_position(line, column); switch (type_[column]) { case kTypeInt: { char temp[64] = {0}; snprintf(temp, sizeof(temp) - 1, "%d", _field_data->int_value); fwrite(temp, strlen(temp), 1, fp); break; } case kTypeFloat: { char temp[64] = {0}; snprintf(temp, sizeof(temp) - 1, "%.3f", _field_data->float_value); fwrite(temp, strlen(temp), 1, fp); break; } case kTypeString: { fwrite(_field_data->string_value, strlen(_field_data->string_value), 1, fp); break; } default: break; } fwrite("\t", 1, 1, fp); } //for fwrite(LF, strlen(LF), 1, fp); } //for fclose(fp); return true; __LEAVE_FUNCTION return false; } const Database::field_data *Database::get_fielddata(int32_t line, const char *name) { __ENTER_FUNCTION const field_data *_field_data = NULL; int32_t column = get_fieldindex(name); _field_data = search_position(line, column); return _field_data; __LEAVE_FUNCTION return NULL; } bool Database::save_totext_line(std::vector<std::string> _data){ __ENTER_FUNCTION if(static_cast<int32_t>(_data.size()) != field_number_) return false; for(int32_t column = 0; column < field_number_; ++column){ switch (type_[column]) { case kTypeInt: { break; } case kTypeFloat: { break; } case kTypeString: { break; } default: break; } } return true; __LEAVE_FUNCTION return false; } } //namespace pf_file
viticm/plainframework1
pf/core/src/file/database.cc
C++
mit
18,796
(function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; }()); (function() { Event.observe(window, 'load', main); var WIDTH = 400; var HEIGHT = 200; var canvas = null; var context = null; var groundCanvas = null; var groundContext = null; var groundImage = null; var scaleCanvas = null; var scaleContext = null; // Physics Variables var lastTime = null; var dt = null; var av = 0; var lv = 0; var px = 953; var py = 792; var pa = 0; // Viewport Settings var omega = 120 * Math.PI/180; var theta = 60 * Math.PI/180; var alpha = 30 * Math.PI/180; var h = 15; var H = 180; var LH = 1; var modes = []; // Input Settings var codeOffset = 37; var LEFT = 0; var UP = 1; var RIGHT = 2; var DOWN = 3; var downKeys = [false, false, false, false]; MAX_VELOCITY = 100/1000; ANGULAR_VELOCITY = Math.PI/(4 * 1000); var images = { 'img/mariocircuit.png': null }; function main() { canvas = new Element('canvas', { 'width': WIDTH, 'height': HEIGHT}); context = canvas.getContext("2d"); $$('body')[0].insert(canvas); Event.observe(window, 'keydown', handleKeydown); Event.observe(window, 'keyup', handleKeyup); canvas.observe('mousedown', handleMousedown); canvas.observe('mouseup', handleMouseup); canvas.observe('mouseover', function() { Event.observe(document, 'touchmove', function(e){ e.preventDefault(); }); }); loadImages(); } function loadImages() { for(var key in images) { console.log(key); if(images[key] == null) { var img = new Image(); img.addEventListener("load", handleLoadImageSuccess.bindAsEventListener(this, key), false); img.addEventListener("error", handleLoadImageFailure.bindAsEventListener(this), false); img.src = key; return; } } handleLoadComplete(); } function handleLoadImageSuccess(event, key) { images[key] = event.target; loadImages(); } function handleLoadImageFailure(event) { loadImages(); } function handleLoadComplete() { window.requestAnimationFrame(update.bind(this)); groundImage = images['img/mariocircuit.png']; var max = Math.max(groundImage.width, groundImage.height); groundCanvas = new Element('canvas', { 'width': max, 'height': max, 'style': 'width:' + max/2 + 'px;height:' + max/2 + 'px'}); groundContext = groundCanvas.getContext("2d"); //$$('body')[0].insert(groundCanvas); /* scaleCanvas = new Element('canvas', { 'width': max, 'height': max, 'style': 'width:' + max/2 + 'px;height:' + max/2 + 'px'}); scaleContext = scaleCanvas.getContext("2d"); $$('body')[0].insert(scaleCanvas); */ // MODES var sx, sy, sw, sh, dx, dw; var w = 0, w1 = 0, w2 = 0, d1 = 0, d2 = 0; for(var L = 1; L <= H; L++) { modes[L] = null; w1 = 2 * h * Math.tan( (Math.PI - theta)/2 + alpha*(L - 1)/H ) / Math.tan(omega/2); w2 = 2 * h * Math.tan( (Math.PI - theta)/2 + alpha*L/H ) / Math.tan(omega/2); d1 = h * Math.tan( (Math.PI - theta)/2 + alpha*(L - 1)/H ); d2 = h * Math.tan( (Math.PI - theta)/2 + alpha*L/H ); //w = w1 + (w2-w1)/2; w = w1; //if(d2 > groundCanvas.height) continue; sx = (groundCanvas.width - w)/2; sy = groundCanvas.height - d1; sw = w; sh = d2 - d1; dw = WIDTH; dx = 0; if(w > groundCanvas.width) { sx = 0; sw = groundCanvas.width; dw = WIDTH * (sw/w); dx = (WIDTH - dw) / 2; } /* context.drawImage( groundCanvas, sx, sy, sw, sh, dx, HEIGHT - L, dw, 1 ); */ modes[L] = { 'sx': sx, 'sy': sy, 'sw': sw, 'sh': sh, 'dx': dx, 'dw': dw }; } } function update(t) { window.requestAnimationFrame(update.bind(this)); if(lastTime == null) lastTime = t; dt = t - lastTime; lastTime = t; lv = 0; av = 0; //if(lv < 0.05 * MAX_VELOCITY) lv = 0; //if(av < 0.05 * ANGULAR_VELOCITY) av = 0; if(downKeys[LEFT] || downKeys[RIGHT] || downKeys[UP] || downKeys[DOWN]) { lv = MAX_VELOCITY * ((0+downKeys[DOWN]) + (0+downKeys[UP])*-1); if(lv == -1) lv *= 0.5; av = ANGULAR_VELOCITY * ((0+downKeys[LEFT]) + (0+downKeys[RIGHT])*-1); } pa += (dt * av); px += (dt * lv) * Math.sin(pa); py += (dt * lv) * Math.cos(pa); // Clear the canvas groundCanvas.width = groundCanvas.width; //scaleCanvas.width = scaleCanvas.width; canvas.width = canvas.width; var dx = (groundCanvas.width/2 - px); var dy = (groundCanvas.height - py); groundContext.save(); groundContext.translate(dx + px, dy + py); groundContext.rotate(pa); groundContext.translate((dx + px)*-1, (dy + py)*-1); groundContext.drawImage(groundImage, dx, dy); groundContext.restore(); for(var L = 1; L <= H; L++) { var val = modes[L]; if(val == undefined) continue; context.drawImage( groundCanvas, val.sx, val.sy, val.sw, val.sh, val.dx, HEIGHT - (L*LH), val.dw, LH ); /* scaleContext.drawImage( groundCanvas, val.sx, val.sy, val.sw, val.sh, val.dx, val.sy, val.dw, val.sh ); */ } } function handleKeydown(event) { var code = event.keyCode - codeOffset; //console.log('keydown: ' + code); switch(code) { case UP: case DOWN: case LEFT: case RIGHT: downKeys[code] = true; break; } } function handleKeyup(event) { var code = event.keyCode - codeOffset; //console.log('keyup: ' + code); switch(code) { case UP: case DOWN: case LEFT: case RIGHT: downKeys[code] = false; break; } } function handleMousedown(event) { if(event.layerY < HEIGHT / 3) { downKeys[UP] = true; } else if(event.layerY < HEIGHT * 2 / 3) { if(event.layerX < WIDTH/2) { downKeys[LEFT] = true; } else { downKeys[RIGHT] = true; } } else { downKeys[DOWN] = true; } } function handleMouseup(event) { downKeys[UP] = false; downKeys[DOWN] = false; downKeys[LEFT] = false; downKeys[RIGHT] = false; } }());
randuhmm/html5-prototype-mode7
js/main.js
JavaScript
mit
6,851
package query import ( "context" "errors" "fmt" "os" "runtime/debug" "strconv" "sync" "sync/atomic" "time" "github.com/influxdata/influxdb/models" "github.com/influxdata/influxql" "go.uber.org/zap" ) var ( // ErrInvalidQuery is returned when executing an unknown query type. ErrInvalidQuery = errors.New("invalid query") // ErrNotExecuted is returned when a statement is not executed in a query. // This can occur when a previous statement in the same query has errored. ErrNotExecuted = errors.New("not executed") // ErrQueryInterrupted is an error returned when the query is interrupted. ErrQueryInterrupted = errors.New("query interrupted") // ErrQueryAborted is an error returned when the query is aborted. ErrQueryAborted = errors.New("query aborted") // ErrQueryEngineShutdown is an error sent when the query cannot be // created because the query engine was shutdown. ErrQueryEngineShutdown = errors.New("query engine shutdown") // ErrQueryTimeoutLimitExceeded is an error when a query hits the max time allowed to run. ErrQueryTimeoutLimitExceeded = errors.New("query-timeout limit exceeded") // ErrAlreadyKilled is returned when attempting to kill a query that has already been killed. ErrAlreadyKilled = errors.New("already killed") ) // Statistics for the QueryExecutor const ( statQueriesActive = "queriesActive" // Number of queries currently being executed. statQueriesExecuted = "queriesExecuted" // Number of queries that have been executed (started). statQueriesFinished = "queriesFinished" // Number of queries that have finished. statQueryExecutionDuration = "queryDurationNs" // Total (wall) time spent executing queries. statRecoveredPanics = "recoveredPanics" // Number of panics recovered by Query Executor. // PanicCrashEnv is the environment variable that, when set, will prevent // the handler from recovering any panics. PanicCrashEnv = "INFLUXDB_PANIC_CRASH" ) // ErrDatabaseNotFound returns a database not found error for the given database name. func ErrDatabaseNotFound(name string) error { return fmt.Errorf("database not found: %s", name) } // ErrMaxSelectPointsLimitExceeded is an error when a query hits the maximum number of points. func ErrMaxSelectPointsLimitExceeded(n, limit int) error { return fmt.Errorf("max-select-point limit exceeed: (%d/%d)", n, limit) } // ErrMaxConcurrentQueriesLimitExceeded is an error when a query cannot be run // because the maximum number of queries has been reached. func ErrMaxConcurrentQueriesLimitExceeded(n, limit int) error { return fmt.Errorf("max-concurrent-queries limit exceeded(%d, %d)", n, limit) } // Authorizer reports whether certain operations are authorized. type Authorizer interface { // AuthorizeDatabase indicates whether the given Privilege is authorized on the database with the given name. AuthorizeDatabase(p influxql.Privilege, name string) bool // AuthorizeQuery returns an error if the query cannot be executed AuthorizeQuery(database string, query *influxql.Query) error // AuthorizeSeriesRead determines if a series is authorized for reading AuthorizeSeriesRead(database string, measurement []byte, tags models.Tags) bool // AuthorizeSeriesWrite determines if a series is authorized for writing AuthorizeSeriesWrite(database string, measurement []byte, tags models.Tags) bool } // OpenAuthorizer is the Authorizer used when authorization is disabled. // It allows all operations. type OpenAuthorizer struct{} var _ Authorizer = OpenAuthorizer{} // AuthorizeDatabase returns true to allow any operation on a database. func (_ OpenAuthorizer) AuthorizeDatabase(influxql.Privilege, string) bool { return true } func (_ OpenAuthorizer) AuthorizeSeriesRead(database string, measurement []byte, tags models.Tags) bool { return true } func (_ OpenAuthorizer) AuthorizeSeriesWrite(database string, measurement []byte, tags models.Tags) bool { return true } func (_ OpenAuthorizer) AuthorizeQuery(_ string, _ *influxql.Query) error { return nil } // ExecutionOptions contains the options for executing a query. type ExecutionOptions struct { // The database the query is running against. Database string // How to determine whether the query is allowed to execute, // what resources can be returned in SHOW queries, etc. Authorizer Authorizer // The requested maximum number of points to return in each result. ChunkSize int // If this query is being executed in a read-only context. ReadOnly bool // Node to execute on. NodeID uint64 // Quiet suppresses non-essential output from the query executor. Quiet bool // AbortCh is a channel that signals when results are no longer desired by the caller. AbortCh <-chan struct{} } // ExecutionContext contains state that the query is currently executing with. type ExecutionContext struct { // The statement ID of the executing query. StatementID int // The query ID of the executing query. QueryID uint64 // The query task information available to the StatementExecutor. Query *QueryTask // Output channel where results and errors should be sent. Results chan *Result // A channel that is closed when the query is interrupted. InterruptCh <-chan struct{} // Options used to start this query. ExecutionOptions } // send sends a Result to the Results channel and will exit if the query has // been aborted. func (ctx *ExecutionContext) send(result *Result) error { select { case <-ctx.AbortCh: return ErrQueryAborted case ctx.Results <- result: } return nil } // Send sends a Result to the Results channel and will exit if the query has // been interrupted or aborted. func (ctx *ExecutionContext) Send(result *Result) error { select { case <-ctx.InterruptCh: return ErrQueryInterrupted case <-ctx.AbortCh: return ErrQueryAborted case ctx.Results <- result: } return nil } type contextKey int const ( iteratorsContextKey contextKey = iota ) // NewContextWithIterators returns a new context.Context with the *Iterators slice added. // The query planner will add instances of AuxIterator to the Iterators slice. func NewContextWithIterators(ctx context.Context, itr *Iterators) context.Context { return context.WithValue(ctx, iteratorsContextKey, itr) } // tryAddAuxIteratorToContext will capture itr in the *Iterators slice, when configured // with a call to NewContextWithIterators. func tryAddAuxIteratorToContext(ctx context.Context, itr AuxIterator) { if v, ok := ctx.Value(iteratorsContextKey).(*Iterators); ok { *v = append(*v, itr) } } // StatementExecutor executes a statement within the QueryExecutor. type StatementExecutor interface { // ExecuteStatement executes a statement. Results should be sent to the // results channel in the ExecutionContext. ExecuteStatement(stmt influxql.Statement, ctx ExecutionContext) error } // StatementNormalizer normalizes a statement before it is executed. type StatementNormalizer interface { // NormalizeStatement adds a default database and policy to the // measurements in the statement. NormalizeStatement(stmt influxql.Statement, database string) error } // QueryExecutor executes every statement in an Query. type QueryExecutor struct { // Used for executing a statement in the query. StatementExecutor StatementExecutor // Used for tracking running queries. TaskManager *TaskManager // Logger to use for all logging. // Defaults to discarding all log output. Logger *zap.Logger // expvar-based stats. stats *QueryStatistics } // NewQueryExecutor returns a new instance of QueryExecutor. func NewQueryExecutor() *QueryExecutor { return &QueryExecutor{ TaskManager: NewTaskManager(), Logger: zap.NewNop(), stats: &QueryStatistics{}, } } // QueryStatistics keeps statistics related to the QueryExecutor. type QueryStatistics struct { ActiveQueries int64 ExecutedQueries int64 FinishedQueries int64 QueryExecutionDuration int64 RecoveredPanics int64 } // Statistics returns statistics for periodic monitoring. func (e *QueryExecutor) Statistics(tags map[string]string) []models.Statistic { return []models.Statistic{{ Name: "queryExecutor", Tags: tags, Values: map[string]interface{}{ statQueriesActive: atomic.LoadInt64(&e.stats.ActiveQueries), statQueriesExecuted: atomic.LoadInt64(&e.stats.ExecutedQueries), statQueriesFinished: atomic.LoadInt64(&e.stats.FinishedQueries), statQueryExecutionDuration: atomic.LoadInt64(&e.stats.QueryExecutionDuration), statRecoveredPanics: atomic.LoadInt64(&e.stats.RecoveredPanics), }, }} } // Close kills all running queries and prevents new queries from being attached. func (e *QueryExecutor) Close() error { return e.TaskManager.Close() } // SetLogOutput sets the writer to which all logs are written. It must not be // called after Open is called. func (e *QueryExecutor) WithLogger(log *zap.Logger) { e.Logger = log.With(zap.String("service", "query")) e.TaskManager.Logger = e.Logger } // ExecuteQuery executes each statement within a query. func (e *QueryExecutor) ExecuteQuery(query *influxql.Query, opt ExecutionOptions, closing chan struct{}) <-chan *Result { results := make(chan *Result) go e.executeQuery(query, opt, closing, results) return results } func (e *QueryExecutor) executeQuery(query *influxql.Query, opt ExecutionOptions, closing <-chan struct{}, results chan *Result) { defer close(results) defer e.recover(query, results) atomic.AddInt64(&e.stats.ActiveQueries, 1) atomic.AddInt64(&e.stats.ExecutedQueries, 1) defer func(start time.Time) { atomic.AddInt64(&e.stats.ActiveQueries, -1) atomic.AddInt64(&e.stats.FinishedQueries, 1) atomic.AddInt64(&e.stats.QueryExecutionDuration, time.Since(start).Nanoseconds()) }(time.Now()) qid, task, err := e.TaskManager.AttachQuery(query, opt.Database, closing) if err != nil { select { case results <- &Result{Err: err}: case <-opt.AbortCh: } return } defer e.TaskManager.DetachQuery(qid) // Setup the execution context that will be used when executing statements. ctx := ExecutionContext{ QueryID: qid, Query: task, Results: results, InterruptCh: task.closing, ExecutionOptions: opt, } var i int LOOP: for ; i < len(query.Statements); i++ { ctx.StatementID = i stmt := query.Statements[i] // If a default database wasn't passed in by the caller, check the statement. defaultDB := opt.Database if defaultDB == "" { if s, ok := stmt.(influxql.HasDefaultDatabase); ok { defaultDB = s.DefaultDatabase() } } // Do not let queries manually use the system measurements. If we find // one, return an error. This prevents a person from using the // measurement incorrectly and causing a panic. if stmt, ok := stmt.(*influxql.SelectStatement); ok { for _, s := range stmt.Sources { switch s := s.(type) { case *influxql.Measurement: if influxql.IsSystemName(s.Name) { command := "the appropriate meta command" switch s.Name { case "_fieldKeys": command = "SHOW FIELD KEYS" case "_measurements": command = "SHOW MEASUREMENTS" case "_series": command = "SHOW SERIES" case "_tagKeys": command = "SHOW TAG KEYS" case "_tags": command = "SHOW TAG VALUES" } results <- &Result{ Err: fmt.Errorf("unable to use system source '%s': use %s instead", s.Name, command), } break LOOP } } } } // Rewrite statements, if necessary. // This can occur on meta read statements which convert to SELECT statements. newStmt, err := RewriteStatement(stmt) if err != nil { results <- &Result{Err: err} break } stmt = newStmt // Normalize each statement if possible. if normalizer, ok := e.StatementExecutor.(StatementNormalizer); ok { if err := normalizer.NormalizeStatement(stmt, defaultDB); err != nil { if err := ctx.send(&Result{Err: err}); err == ErrQueryAborted { return } break } } // Log each normalized statement. if !ctx.Quiet { e.Logger.Info(stmt.String()) } // Send any other statements to the underlying statement executor. err = e.StatementExecutor.ExecuteStatement(stmt, ctx) if err == ErrQueryInterrupted { // Query was interrupted so retrieve the real interrupt error from // the query task if there is one. if qerr := task.Error(); qerr != nil { err = qerr } } // Send an error for this result if it failed for some reason. if err != nil { if err := ctx.send(&Result{ StatementID: i, Err: err, }); err == ErrQueryAborted { return } // Stop after the first error. break } // Check if the query was interrupted during an uninterruptible statement. interrupted := false if ctx.InterruptCh != nil { select { case <-ctx.InterruptCh: interrupted = true default: // Query has not been interrupted. } } if interrupted { break } } // Send error results for any statements which were not executed. for ; i < len(query.Statements)-1; i++ { if err := ctx.send(&Result{ StatementID: i, Err: ErrNotExecuted, }); err == ErrQueryAborted { return } } } // Determines if the QueryExecutor will recover any panics or let them crash // the server. var willCrash bool func init() { var err error if willCrash, err = strconv.ParseBool(os.Getenv(PanicCrashEnv)); err != nil { willCrash = false } } func (e *QueryExecutor) recover(query *influxql.Query, results chan *Result) { if err := recover(); err != nil { atomic.AddInt64(&e.stats.RecoveredPanics, 1) // Capture the panic in _internal stats. e.Logger.Error(fmt.Sprintf("%s [panic:%s] %s", query.String(), err, debug.Stack())) results <- &Result{ StatementID: -1, Err: fmt.Errorf("%s [panic:%s]", query.String(), err), } if willCrash { e.Logger.Error(fmt.Sprintf("\n\n=====\nAll goroutines now follow:")) buf := debug.Stack() e.Logger.Error(fmt.Sprintf("%s", buf)) os.Exit(1) } } } // QueryMonitorFunc is a function that will be called to check if a query // is currently healthy. If the query needs to be interrupted for some reason, // the error should be returned by this function. type QueryMonitorFunc func(<-chan struct{}) error // QueryTask is the internal data structure for managing queries. // For the public use data structure that gets returned, see QueryTask. type QueryTask struct { query string database string status TaskStatus startTime time.Time closing chan struct{} monitorCh chan error err error mu sync.Mutex } // Monitor starts a new goroutine that will monitor a query. The function // will be passed in a channel to signal when the query has been finished // normally. If the function returns with an error and the query is still // running, the query will be terminated. func (q *QueryTask) Monitor(fn QueryMonitorFunc) { go q.monitor(fn) } // Error returns any asynchronous error that may have occured while executing // the query. func (q *QueryTask) Error() error { q.mu.Lock() defer q.mu.Unlock() return q.err } func (q *QueryTask) setError(err error) { q.mu.Lock() q.err = err q.mu.Unlock() } func (q *QueryTask) monitor(fn QueryMonitorFunc) { if err := fn(q.closing); err != nil { select { case <-q.closing: case q.monitorCh <- err: } } } // close closes the query task closing channel if the query hasn't been previously killed. func (q *QueryTask) close() { q.mu.Lock() if q.status != KilledTask { close(q.closing) } q.mu.Unlock() } func (q *QueryTask) kill() error { q.mu.Lock() if q.status == KilledTask { q.mu.Unlock() return ErrAlreadyKilled } q.status = KilledTask close(q.closing) q.mu.Unlock() return nil }
vladlopes/influxdb
query/query_executor.go
GO
mit
15,829
using System.Data.Entity; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace TwitterBot.Models { // You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more. public class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } } public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } } }
b1thunt3r/sixdegree
TwitterBot/Models/IdentityModels.cs
C#
mit
1,209
require 'spec_helper' describe ActionView::Helpers::FormHelper do before do helper.form_for(FakeModel.new, :url => "myurl", :builder => Manageable::Helpers::FormBuilder) do |f| @text_field = f.text_field(:name) @password_field = f.password_field(:name) @telephone_field = f.telephone_field(:name) @url_field = f.url_field(:name) @email_field = f.email_field(:name) @number_field = f.number_field(:name, :size => nil) @range_field = f.range_field(:name, :size => nil) @file_field = f.file_field(:name) @text_area = f.text_area(:name) @check_box = f.check_box(:name) @radio_button = f.radio_button(:name, "Yes") @group = f.group { "thegroup" } @button = f.button("Save", :name => "Save", :type => :submit) end end it "should print labeled text_field" do @text_field.should == '<div class="group"><div class="fieldWithErrors"><label class="label" for="fake_model_name">Name</label>&nbsp<span class="error">is required</span></div><input class="text_field" id="fake_model_name" name="fake_model[name]" size="30" type="text" /></div>' end it "should print labeled password_field" do @password_field.should == '<div class="group"><div class="fieldWithErrors"><label class="label" for="fake_model_name">Name</label>&nbsp<span class="error">is required</span></div><input class="text_field" id="fake_model_name" name="fake_model[name]" size="30" type="password" /></div>' end it "should print labeled telephone_field" do @telephone_field.should == '<div class="group"><div class="fieldWithErrors"><label class="label" for="fake_model_name">Name</label>&nbsp<span class="error">is required</span></div><input class="text_field" id="fake_model_name" name="fake_model[name]" size="30" type="tel" /></div>' end it "should print labeled url_field" do @url_field.should == '<div class="group"><div class="fieldWithErrors"><label class="label" for="fake_model_name">Name</label>&nbsp<span class="error">is required</span></div><input class="text_field" id="fake_model_name" name="fake_model[name]" size="30" type="url" /></div>' end it "should print labeled email_field" do @email_field.should == '<div class="group"><div class="fieldWithErrors"><label class="label" for="fake_model_name">Name</label>&nbsp<span class="error">is required</span></div><input class="text_field" id="fake_model_name" name="fake_model[name]" size="30" type="email" /></div>' end it "should print labeled number_field" do @number_field.should == '<div class="group"><div class="fieldWithErrors"><label class="label" for="fake_model_name">Name</label>&nbsp<span class="error">is required</span></div><input class="text_field" id="fake_model_name" name="fake_model[name]" type="number" /></div>' end it "should print labeled range_field" do @range_field.should == '<div class="group"><div class="fieldWithErrors"><label class="label" for="fake_model_name">Name</label>&nbsp<span class="error">is required</span></div><input class="text_field" id="fake_model_name" name="fake_model[name]" type="range" /></div>' end it "should print labeled file_field" do @file_field.should == '<div class="group"><div class="fieldWithErrors"><label class="label" for="fake_model_name">Name</label>&nbsp<span class="error">is required</span></div><input class="text_field" id="fake_model_name" name="fake_model[name]" type="file" /></div>' end it "should print labeled text_area" do @text_area.should match(/#{Regexp.escape('<div class="group"><div class="fieldWithErrors"><label class="label" for="fake_model_name">Name</label>&nbsp<span class="error">is required</span></div>')}.+textarea.+/) end it "should print labeled check_box" do @check_box.should == '<div><input name="fake_model[name]" type="hidden" value="0" /><input class="checkbox" id="fake_model_name" name="fake_model[name]" type="checkbox" value="1" /><div class="fieldWithErrors"><label class="checkbox" for="fake_model_name">Name</label>&nbsp<span class="error">is required</span></div></div>' end it "should print labeled radio_button" do @radio_button.should == '<div><input class="radio" id="fake_model_name_yes" name="fake_model[name]" type="radio" value="Yes" /><div class="fieldWithErrors"><label class="radio" for="fake_model_name_yes">Yes</label>&nbsp<span class="error">is required</span></div></div>' end it "should print group" do @group.should == '<div class="group">thegroup</div>' end it "should print button" do @button.should == '<button class="button" name="Save" type="submit"><img alt="Save" src="/assets/manageable/icons/tick.png" />&nbsp;Save</button>' end end
fabiokr/manageable
spec/helpers/form_builder_spec.rb
Ruby
mit
4,704
<?php /* @Debug/Profiler/dump.html.twig */ class __TwigTemplate_87214dbb795c597762c22e04f33cdac6be858641b8887823b0d50282e4b88981 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("@WebProfiler/Profiler/layout.html.twig", "@Debug/Profiler/dump.html.twig", 1); $this->blocks = array( 'toolbar' => array($this, 'block_toolbar'), 'menu' => array($this, 'block_menu'), 'panel' => array($this, 'block_panel'), ); } protected function doGetParent(array $context) { return "@WebProfiler/Profiler/layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $__internal_169054fa1935b109834145e55bb854d21d9577bc1d359e1889e9ba5a2ff4d159 = $this->env->getExtension("native_profiler"); $__internal_169054fa1935b109834145e55bb854d21d9577bc1d359e1889e9ba5a2ff4d159->enter($__internal_169054fa1935b109834145e55bb854d21d9577bc1d359e1889e9ba5a2ff4d159_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "@Debug/Profiler/dump.html.twig")); $this->parent->display($context, array_merge($this->blocks, $blocks)); $__internal_169054fa1935b109834145e55bb854d21d9577bc1d359e1889e9ba5a2ff4d159->leave($__internal_169054fa1935b109834145e55bb854d21d9577bc1d359e1889e9ba5a2ff4d159_prof); } // line 3 public function block_toolbar($context, array $blocks = array()) { $__internal_2c1075fdded32af21f4ab8c4e0c8f093c872bf051b1c9af18801ba095fe42c59 = $this->env->getExtension("native_profiler"); $__internal_2c1075fdded32af21f4ab8c4e0c8f093c872bf051b1c9af18801ba095fe42c59->enter($__internal_2c1075fdded32af21f4ab8c4e0c8f093c872bf051b1c9af18801ba095fe42c59_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "toolbar")); // line 4 echo " "; if ($this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "dumpsCount", array())) { // line 5 echo " "; ob_start(); // line 6 echo " "; echo twig_include($this->env, $context, "@Debug/Profiler/icon.svg"); echo " <span class=\"sf-toolbar-value\">"; // line 7 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "dumpsCount", array()), "html", null, true); echo "</span> "; $context["icon"] = ('' === $tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset()); // line 9 echo " "; // line 10 ob_start(); // line 11 echo " "; $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "getDumps", array(0 => "html"), "method")); foreach ($context['_seq'] as $context["_key"] => $context["dump"]) { // line 12 echo " <div class=\"sf-toolbar-info-piece\"> <span> "; // line 14 if ($this->getAttribute($context["dump"], "file", array())) { // line 15 echo " "; $context["link"] = $this->env->getExtension('code')->getFileLink($this->getAttribute($context["dump"], "file", array()), $this->getAttribute($context["dump"], "line", array())); // line 16 echo " "; if ((isset($context["link"]) ? $context["link"] : $this->getContext($context, "link"))) { // line 17 echo " <a href=\""; echo twig_escape_filter($this->env, (isset($context["link"]) ? $context["link"] : $this->getContext($context, "link")), "html", null, true); echo "\" title=\""; echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "file", array()), "html", null, true); echo "\">"; echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "name", array()), "html", null, true); echo "</a> "; } else { // line 19 echo " <abbr title=\""; echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "file", array()), "html", null, true); echo "\">"; echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "name", array()), "html", null, true); echo "</abbr> "; } // line 21 echo " "; } else { // line 22 echo " "; echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "name", array()), "html", null, true); echo " "; } // line 24 echo " </span> <span class=\"sf-toolbar-file-line\">line "; // line 25 echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "line", array()), "html", null, true); echo "</span> "; // line 27 echo $this->getAttribute($context["dump"], "data", array()); echo " </div> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['dump'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 30 echo " <img src=\"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\" onload=\"var h = this.parentNode.innerHTML, rx=/<script>(.*?)<\\/script>/g, s; while (s = rx.exec(h)) {eval(s[1]);};\" /> "; $context["text"] = ('' === $tmp = ob_get_clean()) ? '' : new Twig_Markup($tmp, $this->env->getCharset()); // line 32 echo " "; // line 33 echo twig_include($this->env, $context, "@WebProfiler/Profiler/toolbar_item.html.twig", array("link" => true)); echo " "; } $__internal_2c1075fdded32af21f4ab8c4e0c8f093c872bf051b1c9af18801ba095fe42c59->leave($__internal_2c1075fdded32af21f4ab8c4e0c8f093c872bf051b1c9af18801ba095fe42c59_prof); } // line 37 public function block_menu($context, array $blocks = array()) { $__internal_2e5ee981176180a51f5116ed4f504257abdd56013c92700cd5e349028728cdba = $this->env->getExtension("native_profiler"); $__internal_2e5ee981176180a51f5116ed4f504257abdd56013c92700cd5e349028728cdba->enter($__internal_2e5ee981176180a51f5116ed4f504257abdd56013c92700cd5e349028728cdba_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "menu")); // line 38 echo " <span class=\"label "; echo ((($this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "dumpsCount", array()) == 0)) ? ("disabled") : ("")); echo "\"> <span class=\"icon\">"; // line 39 echo twig_include($this->env, $context, "@Debug/Profiler/icon.svg"); echo "</span> <strong>Debug</strong> </span> "; $__internal_2e5ee981176180a51f5116ed4f504257abdd56013c92700cd5e349028728cdba->leave($__internal_2e5ee981176180a51f5116ed4f504257abdd56013c92700cd5e349028728cdba_prof); } // line 44 public function block_panel($context, array $blocks = array()) { $__internal_d5d1256dc1219a88a660202ab93946adbe9d1075e1f232a2ee0848bbfc17988b = $this->env->getExtension("native_profiler"); $__internal_d5d1256dc1219a88a660202ab93946adbe9d1075e1f232a2ee0848bbfc17988b->enter($__internal_d5d1256dc1219a88a660202ab93946adbe9d1075e1f232a2ee0848bbfc17988b_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "panel")); // line 45 echo " <h2>Dumped Contents</h2> "; // line 47 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable($this->getAttribute((isset($context["collector"]) ? $context["collector"] : $this->getContext($context, "collector")), "getDumps", array(0 => "html"), "method")); $context['_iterated'] = false; $context['loop'] = array( 'parent' => $context['_parent'], 'index0' => 0, 'index' => 1, 'first' => true, ); if (is_array($context['_seq']) || (is_object($context['_seq']) && $context['_seq'] instanceof Countable)) { $length = count($context['_seq']); $context['loop']['revindex0'] = $length - 1; $context['loop']['revindex'] = $length; $context['loop']['length'] = $length; $context['loop']['last'] = 1 === $length; } foreach ($context['_seq'] as $context["_key"] => $context["dump"]) { // line 48 echo " <div class=\"sf-dump sf-reset\"> <h3>In "; // line 50 if ($this->getAttribute($context["dump"], "line", array())) { // line 51 echo " "; $context["link"] = $this->env->getExtension('code')->getFileLink($this->getAttribute($context["dump"], "file", array()), $this->getAttribute($context["dump"], "line", array())); // line 52 echo " "; if ((isset($context["link"]) ? $context["link"] : $this->getContext($context, "link"))) { // line 53 echo " <a href=\""; echo twig_escape_filter($this->env, (isset($context["link"]) ? $context["link"] : $this->getContext($context, "link")), "html", null, true); echo "\" title=\""; echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "file", array()), "html", null, true); echo "\">"; echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "name", array()), "html", null, true); echo "</a> "; } else { // line 55 echo " <abbr title=\""; echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "file", array()), "html", null, true); echo "\">"; echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "name", array()), "html", null, true); echo "</abbr> "; } // line 57 echo " "; } else { // line 58 echo " "; echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "name", array()), "html", null, true); echo " "; } // line 60 echo " <small>line "; echo twig_escape_filter($this->env, $this->getAttribute($context["dump"], "line", array()), "html", null, true); echo "</small> <a class=\"text-small sf-toggle\" data-toggle-selector=\"#sf-trace-"; // line 62 echo twig_escape_filter($this->env, $this->getAttribute($context["loop"], "index0", array()), "html", null, true); echo "\" data-toggle-alt-content=\"Hide code\">Show code</a> </h3> <div class=\"sf-dump-compact hidden\" id=\"sf-trace-"; // line 65 echo twig_escape_filter($this->env, $this->getAttribute($context["loop"], "index0", array()), "html", null, true); echo "\"> <div class=\"trace\"> "; // line 67 echo (($this->getAttribute($context["dump"], "fileExcerpt", array())) ? ($this->getAttribute($context["dump"], "fileExcerpt", array())) : ($this->env->getExtension('code')->fileExcerpt($this->getAttribute($context["dump"], "file", array()), $this->getAttribute($context["dump"], "line", array())))); echo " </div> </div> "; // line 71 echo $this->getAttribute($context["dump"], "data", array()); echo " </div> "; $context['_iterated'] = true; ++$context['loop']['index0']; ++$context['loop']['index']; $context['loop']['first'] = false; if (isset($context['loop']['length'])) { --$context['loop']['revindex0']; --$context['loop']['revindex']; $context['loop']['last'] = 0 === $context['loop']['revindex0']; } } if (!$context['_iterated']) { // line 74 echo " <div class=\"empty\"> <p>No content was dumped.</p> </div> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['dump'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; $__internal_d5d1256dc1219a88a660202ab93946adbe9d1075e1f232a2ee0848bbfc17988b->leave($__internal_d5d1256dc1219a88a660202ab93946adbe9d1075e1f232a2ee0848bbfc17988b_prof); } public function getTemplateName() { return "@Debug/Profiler/dump.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 270 => 74, 254 => 71, 247 => 67, 242 => 65, 236 => 62, 230 => 60, 224 => 58, 221 => 57, 213 => 55, 203 => 53, 200 => 52, 197 => 51, 195 => 50, 191 => 48, 173 => 47, 169 => 45, 163 => 44, 152 => 39, 147 => 38, 141 => 37, 131 => 33, 128 => 32, 124 => 30, 115 => 27, 110 => 25, 107 => 24, 101 => 22, 98 => 21, 90 => 19, 80 => 17, 77 => 16, 74 => 15, 72 => 14, 68 => 12, 63 => 11, 61 => 10, 58 => 9, 53 => 7, 48 => 6, 45 => 5, 42 => 4, 36 => 3, 11 => 1,); } } /* {% extends '@WebProfiler/Profiler/layout.html.twig' %}*/ /* */ /* {% block toolbar %}*/ /* {% if collector.dumpsCount %}*/ /* {% set icon %}*/ /* {{ include('@Debug/Profiler/icon.svg') }}*/ /* <span class="sf-toolbar-value">{{ collector.dumpsCount }}</span>*/ /* {% endset %}*/ /* */ /* {% set text %}*/ /* {% for dump in collector.getDumps('html') %}*/ /* <div class="sf-toolbar-info-piece">*/ /* <span>*/ /* {% if dump.file %}*/ /* {% set link = dump.file|file_link(dump.line) %}*/ /* {% if link %}*/ /* <a href="{{ link }}" title="{{ dump.file }}">{{ dump.name }}</a>*/ /* {% else %}*/ /* <abbr title="{{ dump.file }}">{{ dump.name }}</abbr>*/ /* {% endif %}*/ /* {% else %}*/ /* {{ dump.name }}*/ /* {% endif %}*/ /* </span>*/ /* <span class="sf-toolbar-file-line">line {{ dump.line }}</span>*/ /* */ /* {{ dump.data|raw }}*/ /* </div>*/ /* {% endfor %}*/ /* <img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" onload="var h = this.parentNode.innerHTML, rx=/<script>(.*?)<\/script>/g, s; while (s = rx.exec(h)) {eval(s[1]);};" />*/ /* {% endset %}*/ /* */ /* {{ include('@WebProfiler/Profiler/toolbar_item.html.twig', { 'link': true }) }}*/ /* {% endif %}*/ /* {% endblock %}*/ /* */ /* {% block menu %}*/ /* <span class="label {{ collector.dumpsCount == 0 ? 'disabled' }}">*/ /* <span class="icon">{{ include('@Debug/Profiler/icon.svg') }}</span>*/ /* <strong>Debug</strong>*/ /* </span>*/ /* {% endblock %}*/ /* */ /* {% block panel %}*/ /* <h2>Dumped Contents</h2>*/ /* */ /* {% for dump in collector.getDumps('html') %}*/ /* <div class="sf-dump sf-reset">*/ /* <h3>In*/ /* {% if dump.line %}*/ /* {% set link = dump.file|file_link(dump.line) %}*/ /* {% if link %}*/ /* <a href="{{ link }}" title="{{ dump.file }}">{{ dump.name }}</a>*/ /* {% else %}*/ /* <abbr title="{{ dump.file }}">{{ dump.name }}</abbr>*/ /* {% endif %}*/ /* {% else %}*/ /* {{ dump.name }}*/ /* {% endif %}*/ /* <small>line {{ dump.line }}</small>*/ /* */ /* <a class="text-small sf-toggle" data-toggle-selector="#sf-trace-{{ loop.index0 }}" data-toggle-alt-content="Hide code">Show code</a>*/ /* </h3>*/ /* */ /* <div class="sf-dump-compact hidden" id="sf-trace-{{ loop.index0 }}">*/ /* <div class="trace">*/ /* {{ dump.fileExcerpt ? dump.fileExcerpt|raw : dump.file|file_excerpt(dump.line) }}*/ /* </div>*/ /* </div>*/ /* */ /* {{ dump.data|raw }}*/ /* </div>*/ /* {% else %}*/ /* <div class="empty">*/ /* <p>No content was dumped.</p>*/ /* </div>*/ /* {% endfor %}*/ /* {% endblock %}*/ /* */
rince1990/photocool
app/cache/dev/twig/6b/6b71bb18f4add4f495b2075399e972f2b6c75277cfc00146f5f2f88109075914.php
PHP
mit
18,596
package armored.g12matrickapp.Activities; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.ResolveInfo; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.support.design.widget.AppBarLayout; import android.support.design.widget.NavigationView; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewPager; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.NestedScrollView; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatDelegate; import android.support.v7.widget.AppCompatImageView; import android.support.v7.widget.Toolbar; import android.text.Html; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import armored.g12matrickapp.Adapters.ChooserArrayAdapter; import armored.g12matrickapp.Fragments.Choose_Subject_Fragment; import armored.g12matrickapp.Fragments.Quizzi_Fragment; import armored.g12matrickapp.R; import armored.g12matrickapp.Utils.Functions; import armored.g12matrickapp.Widgets.ExpandableGridView; import static android.view.View.GONE; public class Subject_Choose extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { /** * The {@link android.support.v4.view.PagerAdapter} that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * {@link android.support.v4.app.FragmentStatePagerAdapter}. */ /** * The {@link ViewPager} that will host the section contents. */ private View navHeader; private AppCompatImageView imgNavProfile , imgNavBackground; private TextView txtName , txtWebsite; private int navItemIndex = 0; private NavigationView navigationView; private Toolbar primaryToolbar; private Toolbar secondaryToolbar; private TextView detailsToolbarTextView; private NestedScrollView container_one; private NestedScrollView container_two; private Handler mHandler; private String[] activityTitles; private static final String TAG_CHANGE_SUBJECT = "chsub"; private static final String TAG_QUIZZI = "quizzi"; private static final String TAG_MY_PROGRESS = "mprogress"; private static final String TAG_CHALLENGES = "challenge"; private static final String TAG_EUEE_RESULT = "eueer"; public static String CURRENT_TAG = TAG_CHANGE_SUBJECT; ExpandableGridView catGrid; View fragment; void loadNavHeader(){ txtName.setText("Brook Mezgebu"); txtWebsite.setText("Bole Kale Hiwot School"); try{ Drawable drawable = ContextCompat.getDrawable(this , R.drawable.male); Bitmap b = Functions.getHexagonShape(Functions.drawableToBitmap(drawable)); ByteArrayOutputStream stream = new ByteArrayOutputStream(); b.compress(Bitmap.CompressFormat.PNG , 100 , stream); byte[] bitmapdata = stream.toByteArray(); Glide.with(this) .load(bitmapdata) .crossFade() .override(150 , 150) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imgNavProfile); Glide.with(this) .load(R.drawable.lib_background) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(imgNavBackground); } catch (Exception a){ a.printStackTrace(); } } private FragmentManager.OnBackStackChangedListener getListener(){ FragmentManager.OnBackStackChangedListener result = new FragmentManager.OnBackStackChangedListener() { @Override public void onBackStackChanged() { FragmentManager manager = getSupportFragmentManager(); if(manager != null){ int backstackentrycount = manager.getBackStackEntryCount(); if(backstackentrycount == 0){ finish(); } else{ Fragment frag = manager.getFragments().get(backstackentrycount - 1); frag.onResume(); } } } }; return result; } public void hide_container_one(){ container_one.setVisibility(GONE); container_two.setVisibility(View.VISIBLE); } public void hide_container_two(){ container_one.setVisibility(View.VISIBLE); container_two.setVisibility(View.GONE); } public void hide_second_toolbar(){ secondaryToolbar.setVisibility(GONE); AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams)secondaryToolbar.getLayoutParams(); AppBarLayout.LayoutParams paramsp = (AppBarLayout.LayoutParams)primaryToolbar.getLayoutParams(); params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP); paramsp.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP); primaryToolbar.setLayoutParams(paramsp); secondaryToolbar.setLayoutParams(params); } public void show_second_toolbar(){ secondaryToolbar.setVisibility(View.VISIBLE); AppBarLayout.LayoutParams params = (AppBarLayout.LayoutParams)secondaryToolbar.getLayoutParams(); AppBarLayout.LayoutParams paramsp = (AppBarLayout.LayoutParams)primaryToolbar.getLayoutParams(); params.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SNAP); paramsp.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS); primaryToolbar.setLayoutParams(paramsp); secondaryToolbar.setLayoutParams(params); } int alsoGoTo = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_to_be_removed); primaryToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(primaryToolbar); AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); mHandler = new Handler(); getSupportFragmentManager().addOnBackStackChangedListener(getListener()); secondaryToolbar = (Toolbar) findViewById(R.id.secondaryTab); drawer = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, primaryToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.setDrawerListener(toggle); toggle.syncState(); activityTitles = getResources().getStringArray(R.array.nav_item_activity_titles); navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); detailsToolbarTextView = (TextView) findViewById(R.id.detailToolbarTextView); detailsToolbarTextView.setText("Subjects"); navHeader = navigationView.getHeaderView(0); txtName = (TextView) navHeader.findViewById(R.id.userName); txtWebsite = (TextView) navHeader.findViewById(R.id.userSchool); imgNavProfile = (AppCompatImageView) navHeader.findViewById(R.id.profilePic); imgNavBackground = (AppCompatImageView) navHeader. findViewById(R.id.libBackgroundNav); fragment = (View) findViewById(R.id.fragment); loadNavHeader(); try { alsoGoTo = getIntent().getExtras().getInt("alsoGoTo" , 0); } catch (Exception e){ alsoGoTo = 0; e.printStackTrace(); } if(alsoGoTo == 0) { navItemIndex = 0; CURRENT_TAG = TAG_CHANGE_SUBJECT; navigationView.getMenu().getItem(0).setChecked(true); loadChoosedFragment(); } else { navItemIndex = alsoGoTo; CURRENT_TAG = getTagFromIndex(alsoGoTo); navigationView.getMenu().getItem(alsoGoTo).setChecked(true); loadChoosedFragment(); } container_one = (NestedScrollView) findViewById(R.id.container_one); container_two = (NestedScrollView) findViewById(R.id.container_two); } DrawerLayout drawer; public void SetTitleFromFragment(String title){ getSupportActionBar().setTitle(title); } private String getTagFromIndex(int index){ switch (index){ case 0: return TAG_CHANGE_SUBJECT; case 1: return TAG_QUIZZI; case 2: return TAG_MY_PROGRESS; case 3: return TAG_CHALLENGES; case 4: return TAG_EUEE_RESULT; default: return TAG_CHANGE_SUBJECT; } } public void SetSubTitleFromFragment(String title){ getSupportActionBar().setSubtitle(title); } public void SetTitleOfDetailFromFragment(String title){ detailsToolbarTextView.setText(title);} @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_subject__choose, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } private void loadChoosedFragment(){ selectNavMenu(); setToolbarTitle(); if(getSupportFragmentManager().findFragmentByTag(CURRENT_TAG) != null){ drawer.closeDrawers(); return; } Runnable mPendingRunnable = new Runnable() { @Override public void run() { Fragment fragment = getHomeFragment(); FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction(); try{ if(getSupportFragmentManager().findFragmentById(R.id.fragment) != null) fragmentTransaction.remove(getSupportFragmentManager().findFragmentById(R.id.fragment)); if(getSupportFragmentManager().findFragmentById(R.id.fragment2) != null) fragmentTransaction.remove(getSupportFragmentManager().findFragmentById(R.id.fragment2)); } catch (NullPointerException a){ a.printStackTrace(); } fragmentTransaction.replace(R.id.fragment, fragment, CURRENT_TAG); fragmentTransaction.commitAllowingStateLoss(); } }; if(mPendingRunnable != null){ mHandler.postDelayed(mPendingRunnable , 250); } drawer.closeDrawers(); invalidateOptionsMenu(); } private Fragment getHomeFragment(){ switch (navItemIndex){ case 0: show_second_toolbar(); return new Choose_Subject_Fragment(); case 1: hide_second_toolbar(); return new Quizzi_Fragment(); /* case 2: return new GraphsFragment(); case 3: return new WhatsHotFragment();*/ default: return new Fragment(); } } //This will be used inside onbackpressed to go back from years to subjects on mainPage boolean amOnYearsPart = false; //This will be used inside onbackpressed to go back from chapters to subjects on quizzi boolean amOnChaptersPart = false; private void setToolbarTitle(){ getSupportActionBar().setTitle(activityTitles[navItemIndex]); } public void setAmOnYearsPart(boolean b) { amOnYearsPart = b; } public void setAmOnChaptersPart(boolean b) { amOnChaptersPart = b; } private void selectNavMenu(){ navigationView.getMenu().getItem(navItemIndex).setChecked(true); } boolean isDOubleTOuched = false; @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START); } else { if(getSupportFragmentManager().findFragmentById(R.id.fragment) != null) { if(getSupportFragmentManager().findFragmentById(R.id.fragment).getTag().equals(TAG_CHANGE_SUBJECT)){ if (!isDOubleTOuched) { isDOubleTOuched = true; Snackbar snackbar = Snackbar.make(secondaryToolbar, "Press Again To Exit", Snackbar.LENGTH_SHORT) .setAction("EXIT NOW", new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); snackbar.getView().setBackgroundColor(ContextCompat.getColor(Subject_Choose.this, R.color.colorPrimary)); snackbar.show(); new Handler().postDelayed(new Runnable() { @Override public void run() { isDOubleTOuched = false; } }, 1500); snackbar.show(); } else { finish(); } } else if(getSupportFragmentManager().findFragmentById(R.id.fragment).getTag().equals(TAG_QUIZZI)) { if(amOnChaptersPart){ Quizzi_Fragment tempFrag = (Quizzi_Fragment) getSupportFragmentManager().findFragmentById(R.id.fragment); tempFrag.performBackButtonClick(); } else { navItemIndex = 0; CURRENT_TAG = TAG_CHANGE_SUBJECT; navigationView.getMenu().getItem(0).setChecked(true); loadChoosedFragment(); } } else { if(amOnYearsPart){ navItemIndex = 0; CURRENT_TAG = TAG_CHANGE_SUBJECT; navigationView.getMenu().getItem(0).setChecked(true); loadChoosedFragment(); }else { AlertDialog.Builder exitQ = new AlertDialog.Builder(this); exitQ.setTitle("Are you sure?"); exitQ.setMessage("Are you sure you want to exit to the homepage? All your progress will be lost."); exitQ.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { navItemIndex = 0; CURRENT_TAG = TAG_CHANGE_SUBJECT; navigationView.getMenu().getItem(0).setChecked(true); loadChoosedFragment(); } }).setNegativeButton("No", null); exitQ.show(); } } } } } public void deselectNavMenu(){ int i = navigationView.getMenu().size(); for(int x = 0; x < i; x++){ navigationView.getMenu().getItem(x).setChecked(false); } } public void shareDialog() { final List<String> packages = new ArrayList<String>(); Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.setType("text/plain"); final List<ResolveInfo> resInfosNew = new ArrayList<ResolveInfo>(); final List<ResolveInfo> resInfos = getPackageManager().queryIntentActivities(shareIntent, 0); resInfosNew.addAll(resInfos); if (!resInfos.isEmpty()) { System.out.println("Have package"); int count = 0; for (ResolveInfo resInfo : resInfos) { String packageName = resInfo.activityInfo.packageName; if (packageName.contains("com.facebook.katana")) { resInfosNew.remove(count); } else packages.add(packageName); count++; } } if (packages.size() > 1) { ArrayAdapter<String> adapter = new ChooserArrayAdapter(this, android.R.layout.select_dialog_item, android.R.id.text1, packages); String title = "<b>Share via...</b>"; new AlertDialog.Builder(this) .setTitle(Html.fromHtml(title)) .setAdapter(adapter, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { invokeApplication(packages.get(item), resInfosNew.get(item)); } }) .show(); } else if (packages.size() == 1) { invokeApplication(packages.get(0), resInfos.get(0)); } } private void invokeApplication(String packageName, ResolveInfo resolveInfo) { // if(packageName.contains("com.twitter.android") || packageName.contains("com.facebook.katana") || packageName.contains("com.kakao.story")) { Intent intent = new Intent(); intent.setComponent(new ComponentName(packageName, resolveInfo.activityInfo.name)); intent.setAction(Intent.ACTION_SEND); intent.setType("text/plain"); String sharetxt = "Practice makes perfect. Exercise previous grade 12 matrick questions to do your best.\n Download our app from [zufanapps.tk/g12matrick] and Thank you."; intent.putExtra(Intent.EXTRA_TEXT, sharetxt); intent.putExtra(Intent.EXTRA_SUBJECT, "Share G12"); intent.setPackage(packageName); startActivity(intent); // } } @SuppressWarnings("StatementWithEmptyBody") @Override public boolean onNavigationItemSelected(MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_change_sub) { navItemIndex = 0; CURRENT_TAG = TAG_CHANGE_SUBJECT; if(item.isChecked()){ item.setChecked(false); } else{ item.setChecked(true); } item.setChecked(true); loadChoosedFragment(); return true; } else if (id == R.id.nav_quizzi) { navItemIndex = 1; CURRENT_TAG = TAG_QUIZZI; if(item.isChecked()){ item.setChecked(false); } else{ item.setChecked(true); } item.setChecked(true); loadChoosedFragment(); return true; } else if (id == R.id.nav_my_progress) { } else if (id == R.id.nav_challenge) { } else if (id == R.id.euee_result) { } else if(id == R.id.settings) { } else if (id == R.id.nav_share) { shareDialog(); } else if (id == R.id.nav_send) { } else if(id == R.id.rate_us){ } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } }
RhinoSoftware/G12Matric
app/src/main/java/armored/g12matrickapp/Activities/subject_Choose.java
Java
mit
21,736
//! //! @author Wang Weixu 13114633, Xiufeng Zhang 06197620, Boxi Zhang, 12238967 //! @date 12.12.2014 //! //! @brief This code implemented Big Number using linked list as underlying //! data structure. //! //! Assignment 4, 159.201,s3,2014 //! #include <iostream> #include <fstream> #include <string> namespace ads { /** * @brief Section A : The List class */ template<typename T> class List { struct Node{ T value_; Node* prev_; Node* next_; }; public: using SizeType = std::size_t; void push_front(T const& new_value) { if(empty()) { head_ = tail_ = new Node{new_value, nullptr, nullptr}; } else { head_ = new Node{new_value, nullptr, head_}; head_->next_->prev_ = head_; } ++size_; } bool empty()const { return !head_ and !tail_; } SizeType size() const { return size_; } ~List() { if(not empty()) for(Node* ptr = head_, *tmp; (tmp=ptr); ptr=ptr->next_) delete tmp; head_ = tail_ = nullptr; } protected: Node* head_{}; Node* tail_{}; private: SizeType size_{0}; }; template<typename T> struct BigNumber; template<typename T> BigNumber<T> operator+(BigNumber<T> const& lhs, BigNumber<T> const& rhs); /** * @brief Section B : The BigNumber struct */ template<typename T> struct BigNumber : private List<T> { friend BigNumber operator+ <T>(BigNumber const&, BigNumber const&); using List<T>::push_front; BigNumber() = default; explicit BigNumber(std::string const& num) { for(auto c = num.crbegin(); c != num.crend(); ++c) if(std::isdigit(*c)) push_front(*c - 48); } std::ostream& print() const { for(auto ptr = this->head_; ptr; ptr = ptr->next_) std::cout << ptr->value_; return std::cout << std::endl; } }; /** * @brief Section C : operator + * @param lhs * @param rhs * @return the sum */ template<typename T> BigNumber<T> operator+(BigNumber<T> const& lhs, BigNumber<T> const& rhs) { BigNumber<T> sum; int carry = 0; auto l = lhs.tail_, r = rhs.tail_; for(; l and r; l = l->prev_, r = r->prev_) //add two numbers. { auto digit_sum = carry + l->value_ + r->value_ ; sum.push_front(digit_sum%10); carry = digit_sum/10; } for(auto rest = l?l:r; rest; rest = rest->prev_) //when either one exhausted. { auto digit_sum = carry + rest->value_; sum.push_front(digit_sum%10); carry = digit_sum/10; } if(carry) //for the last carry,if any. sum.push_front(carry); return sum; } }//namespace int main(int argc, char ** argv) { if(argc!=2) { std::cout<< "cannot read the file " << argv[1] << std::endl; exit(0); } std::string l,r; { std::ifstream ifs{argv[1]}; std::getline(ifs,l); std::getline(ifs,r); } ads::BigNumber<int> lhs{l}, rhs{r}; lhs.print() << "+\n"; rhs.print() << "=\n"; (lhs+rhs).print(); return 0; }
Mooophy/159201
assignment4/as4/assignment04_159201_final_version.cpp
C++
mit
3,226
using System; using System.Collections.Generic; using System.Linq; using System.Text; using EspaceClient.FrontOffice.Infrastructure.Services.Translation; using EspaceClient.FrontOffice.Web.ViewModels.Pages.Module.StaticModel; using EspaceClient.FrontOffice.Domaine.Results; namespace EspaceClient.FrontOffice.Web.ViewModels.Pages.Document { public class DocumentsAuditViewModel : StaticBlocViewModel { public IEnumerable<GetBlocDocumentResultDto> Documents { get; set; } public DocumentsAuditViewModel(Context context, ITranslator translatorService) : base(context, translatorService) { } } }
apo-j/Projects_Working
EC/espace-client-dot-net/EspaceClient.FrontOffice.Web.ViewModels/Pages/Document/DocumentsAuditViewModel.cs
C#
mit
655
version https://git-lfs.github.com/spec/v1 oid sha256:0f088644576fe6fee42bb3ce7f1d056f5db1079bf284c312f2acb895c5510851 size 11112
yogeshsaroya/new-cdnjs
ajax/libs/angular-strap/2.1.5/modules/select.js
JavaScript
mit
130
import re from datetime import datetime from flask import current_app as app from flask_jwt import current_identity from flask_restplus import Namespace, Resource, fields, reqparse from sqlalchemy.exc import IntegrityError from packr.models import Message api = Namespace('contact', description='Operations related to the contact form') message = api.model('Contact', { 'email': fields.String(required=True, description='Contact email'), 'content': fields.String(required=True, description='Message'), }) message_id = api.model('ContactCompletion', { 'id': fields.Integer(required=True, description='id') }) @api.route('/') class MessageItem(Resource): @api.expect(message) @api.response(204, 'Message successfully received.') def post(self): req_parse = reqparse.RequestParser(bundle_errors=True) req_parse.add_argument('email', type=str, required=True, help='No email provided', location='json') req_parse.add_argument('content', type=str, required=True, help='No message provided', location='json') args = req_parse.parse_args() email = args.get('email') content = args.get('content') if email == '': return {'message': {'email': 'No email provided'}}, 400 elif not re.match(r"^[A-Za-z0-9.+_-]+@[A-Za-z0-9._-]+\.[a-zA-Z]*$", email): return {'message': {'email': 'Invalid email provided'}}, 400 if content == '': return {'message': {'content': 'No content provided'}}, 400 new_message = Message(email=email, content=content, time=datetime.now()) try: new_message.save() except IntegrityError as e: print(e) return { 'description': 'Failed to send message.' }, 409 except Exception as e: print(e) return {'description': 'Server encountered an error.'}, 500 return {'email': new_message.email}, 201 def get(self): if not current_identity and not app.config.get('TESTING'): return {'message': 'User not authenticated'}, 401 if app.config.get('TESTING') \ or current_identity.role.role_name == "ADMIN": messages = dict() for message_row in Message.query.filter_by(done=False).all(): messages[message_row.id] = { "email": message_row.email, "time": message_row.time.isoformat(), "content": message_row.content } return messages, 201 else: return {'message': 'Not authorised'}, 401 @api.route('/complete') class CompleteItem(Resource): @api.expect(message_id) @api.response(204, 'Message successfully updated.') def post(self): req_parse = reqparse.RequestParser(bundle_errors=True) req_parse.add_argument('id', type=int, required=True, help='No id provided', location='json') args = req_parse.parse_args() id = args.get('id') if id == 0: return {'message': {'id': 'No id provided'}}, 400 completed_message = Message.query.filter_by(id=id).first() completed_message.done = True try: completed_message.save() except IntegrityError as e: print(e) return { 'description': 'Failed to update message.' }, 409 except Exception as e: print(e) return {'description': 'Server encountered an error.'}, 500 return {'message': "Message updated"}, 201
KnightHawk3/packr
packr/api/contact.py
Python
mit
4,011
package panels; import javax.swing.JPanel; import javax.swing.JTextArea; public class EditPanel extends JPanel { JTextArea srcEdit; public EditPanel() { srcEdit = new JTextArea(20, 30); String src = ".data\n" + "a: .word 1, 2, 3\n"; srcEdit.setText(src); add(srcEdit); } public JTextArea getSrcEdit() { return srcEdit; } public void setSrcEdit(JTextArea srcEdit) { this.srcEdit = srcEdit; } public String getText() { return getSrcEdit().getText() ; } }
mulderp/plutoasm
src/panels/EditPanel.java
Java
mit
496
class Projects::UsersController < ApplicationController include StaffPlan::SharedFinderMethods before_filter :find_target_user before_filter :find_project, :only => [:update, :destroy] def update if @project.users << @target_user render(json: { users: @project.users.map { |u| UserDecorator.decorate(u).project_json(@project) } }) and return else render(json: { status: 'fail' }) and return end end def destroy User.transaction do @target_user.projects.delete(@project) @target_user.work_weeks.for_project(@project).map(&:destroy) end render(:json => { status: 'ok' }) and return end end
rescuedcode/StaffPlan
app/controllers/projects/users_controller.rb
Ruby
mit
709