text
stringlengths
2
1.04M
meta
dict
layout: sticker name: hatch2 title: "Hatch (Continued)" author: name: "Hatch" url: http://www.hatchpet.com/ tags: [hatch, hatchpet, cute] amount: 10 link: https://telegram.me/addstickers/facebookhatch2 --- Meet the itty-bitty glob that likes affection and naps. <div class="stickers"> <div class="stickers-preview"> <img src="{{ site.baseurl }}/public/stickers/{{ page.name }}/1.png" /> <img src="{{ site.baseurl }}/public/stickers/{{ page.name }}/2.png" /> <img src="{{ site.baseurl }}/public/stickers/{{ page.name }}/3.png" /> <img src="{{ site.baseurl }}/public/stickers/{{ page.name }}/4.png" /> <img src="{{ site.baseurl }}/public/stickers/{{ page.name }}/5.png" /> <img src="{{ site.baseurl }}/public/stickers/{{ page.name }}/6.png" /> <img src="{{ site.baseurl }}/public/stickers/{{ page.name }}/7.png" /> <img src="{{ site.baseurl }}/public/stickers/{{ page.name }}/8.png" /> <img src="{{ site.baseurl }}/public/stickers/{{ page.name }}/9.png" /> <img src="{{ site.baseurl }}/public/stickers/{{ page.name }}/10.png" /> </div> </div>
{ "content_hash": "8e3660508c932c75de26d6b21b79eedd", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 75, "avg_line_length": 40.407407407407405, "alnum_prop": 0.615948670944088, "repo_name": "TelegramTalk/telegramtalk.github.io", "id": "e4d59dea1ab63fec7fe0d93c45df344dde1461c0", "size": "1095", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_stickers/2015-05-24-hatch2.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "27840" }, { "name": "HTML", "bytes": "8140" }, { "name": "Ruby", "bytes": "229" } ], "symlink_target": "" }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.296 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace sGridServer.Resources.FacebookIdProvider { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class InvitationLanding { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal InvitationLanding() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("sGridServer.Views.IdProviderHelper.Resources.InvitationLanding", typeof(InvitationLanding).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Welcome! You have been invited by {0} to join sGrid. . /// </summary> public static string Description { get { return ResourceManager.GetString("Description", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Join sGrid. /// </summary> public static string Title { get { return ResourceManager.GetString("Title", resourceCulture); } } } }
{ "content_hash": "0a6f6c1546df6ce94f40bcf2f84c6754", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 215, "avg_line_length": 43.617283950617285, "alnum_prop": 0.5867534673082366, "repo_name": "ejoebstl/sGrid", "id": "d1d87e0f0be8a45f9e26c2f308e479b0f014cf98", "size": "3535", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "sGridServer/Views/IdProviderHelper/Resources/InvitationLanding.Designer.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "192" }, { "name": "C#", "bytes": "1341788" }, { "name": "CSS", "bytes": "32759" }, { "name": "JavaScript", "bytes": "1489043" }, { "name": "Smalltalk", "bytes": "21449" } ], "symlink_target": "" }
v8_hello_world ================================================== This is a Hello World program with static linking for Google V8 engine. It is not a trivial task to build it on Windows in an *unprepared* environment due to lack of some essential details in documentation. Building Tips -------------------------------------------------- ### Requirements for the development environment: - Visual Studio 2015 update 3 - VC++, Python Tools and Windows SDK must be installed with VS 2015 - Debugging Tools for Windows: download and install [Windows 10 SDK](<https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk>) - Environment variables (use your modified __assets/setenv.bat__ under admin): - `CPP_V8_ROOT` for v8 root folder - `CPP_DT_ROOT` for depot tools root folder - `GYP_MSVS_VERSION=2015` - `DEPOT_TOOLS_WIN_TOOLCHAIN=0` - `PATH=$(CPP_DT_ROOT);%PATH%` Check that the DT path is ahead of any Python installation. ### Depot tools - [Download](<https://storage.googleapis.com/chrome-infra/depot_tools.zip>) - `# cd $(CPP_V8_ROOT)` - `# gclient sync` ### Building static libraries - `# cd $(CPP_V8_ROOT)` - `# fetch v8` - `# gclient sync` - `# python tools/dev/v8gen.py x64.release` - `# gn args out.gn/x64.release` - opens text editor, edit with additional values from __assets/out.gn/x64.release/args.gn__: - `is_component_build = false` - `v8_static_library = true` - this should override settings in __v8.gni__, if not - modify it - `# ninja -C out.gn/x64.release` ### Project Settings 1. __natives_blob.bin__ and __snapshot_blob.bin__ - these file must be copied to *.exe directory 2. Configuration Properties > General > Output and Intermediate Directories - `build\$(Platform)\$(Configuration)\bin\` - `build\$(Platform)\$(Configuration)\obj\` 3. C/C++ > General > Additional Include Directories - `$(CPP_V8_ROOT)\;$(CPP_V8_ROOT)\include\;` 4. Linker > General > Additional Library Directories - `$(CPP_V8_ROOT)\out.gn\x64.release\obj\third_party\icu;$(CPP_V8_ROOT)\out.gn\x64.release\obj\src\inspector;$(CPP_V8_ROOT)\out.gn\x64.release\obj;` 5. Linker > Input > Additional dependencies - `v8_base_0.lib;v8_base_1.lib;v8_libbase.lib;v8_external_snapshot.lib;v8_libplatform.lib;v8_libsampler.lib;icuuc.lib;icui18n.lib;inspector.lib;winmm.lib;dbghelp.lib;shlwapi.lib;%(AdditionalDependencies)` 6. C/C++ > Code Generation > Runtime Library - `Multi-threaded (/MT)` ### References - [Checking out and Building Chromium for Windows](<https://chromium.googlesource.com/chromium/src/+/master/docs/windows_build_instructions.md>) - [Building V8](<https://github.com/v8/v8/wiki/Building-with-GN>) - [How to build V8 on Windows and not go mad](<https://medium.com/dailyjs/how-to-build-v8-on-windows-and-not-go-mad-6347c69aacd4>)
{ "content_hash": "c3ed140c409c0154914221a8e8d268b6", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 210, "avg_line_length": 47.42622950819672, "alnum_prop": 0.6688558589699274, "repo_name": "zubrim/cpp-examples", "id": "785fad0bb1754c8c26ae5066dc44d8ea6fe82f35", "size": "2893", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v8_hello_world/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "240" }, { "name": "C++", "bytes": "11147" } ], "symlink_target": "" }
package org.jabref.gui.keyboard; import javax.inject.Inject; import javafx.fxml.FXML; import javafx.scene.control.ButtonType; import javafx.scene.control.SelectionMode; import javafx.scene.control.SelectionModel; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeTableColumn; import javafx.scene.control.TreeTableView; import org.jabref.gui.DialogService; import org.jabref.gui.icon.JabRefIcon; import org.jabref.gui.util.BaseDialog; import org.jabref.gui.util.ControlHelper; import org.jabref.gui.util.RecursiveTreeItem; import org.jabref.gui.util.ViewModelTreeTableCellFactory; import org.jabref.logic.l10n.Localization; import org.jabref.preferences.PreferencesService; import com.airhacks.afterburner.views.ViewLoader; import org.fxmisc.easybind.EasyBind; public class KeyBindingsDialogView extends BaseDialog<Void> { @FXML private ButtonType resetButton; @FXML private ButtonType saveButton; @FXML private TreeTableView<KeyBindingViewModel> keyBindingsTable; @FXML private TreeTableColumn<KeyBindingViewModel, String> actionColumn; @FXML private TreeTableColumn<KeyBindingViewModel, String> shortcutColumn; @FXML private TreeTableColumn<KeyBindingViewModel, KeyBindingViewModel> resetColumn; @Inject private KeyBindingRepository keyBindingRepository; @Inject private DialogService dialogService; @Inject private PreferencesService preferences; private KeyBindingsDialogViewModel viewModel; public KeyBindingsDialogView() { this.setTitle(Localization.lang("Key bindings")); this.getDialogPane().setPrefSize(375, 475); ViewLoader.view(this) .load() .setAsDialogPane(this); ControlHelper.setAction(resetButton, getDialogPane(), event -> setDefaultBindings()); ControlHelper.setAction(saveButton, getDialogPane(), event -> saveKeyBindingsAndCloseDialog()); } @FXML private void initialize() { viewModel = new KeyBindingsDialogViewModel(keyBindingRepository, dialogService, preferences); keyBindingsTable.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); viewModel.selectedKeyBindingProperty().bind( EasyBind.monadic(keyBindingsTable.selectionModelProperty()) .flatMap(SelectionModel::selectedItemProperty) .selectProperty(TreeItem::valueProperty) ); keyBindingsTable.setOnKeyPressed(evt -> viewModel.setNewBindingForCurrent(evt)); keyBindingsTable.rootProperty().bind( EasyBind.map(viewModel.rootKeyBindingProperty(), keybinding -> new RecursiveTreeItem<>(keybinding, KeyBindingViewModel::getChildren)) ); actionColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().nameProperty()); shortcutColumn.setCellValueFactory(cellData -> cellData.getValue().getValue().shownBindingProperty()); new ViewModelTreeTableCellFactory<KeyBindingViewModel>() .withGraphic(keyBinding -> keyBinding.getIcon().map(JabRefIcon::getGraphicNode).orElse(null)) .withOnMouseClickedEvent(keyBinding -> evt -> keyBinding.resetToDefault()) .install(resetColumn); } @FXML private void closeDialog() { close(); } @FXML private void saveKeyBindingsAndCloseDialog() { viewModel.saveKeyBindings(); closeDialog(); } @FXML private void setDefaultBindings() { viewModel.resetToDefault(); } }
{ "content_hash": "e7af93bb729b980004ce51345c9a709a", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 110, "avg_line_length": 39.93258426966292, "alnum_prop": 0.7287563308947664, "repo_name": "zellerdev/jabref", "id": "69528fc89279d953c4cef060ac047e1e8916d034", "size": "3554", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/jabref/gui/keyboard/KeyBindingsDialogView.java", "mode": "33188", "license": "mit", "language": [ { "name": "ANTLR", "bytes": "1751" }, { "name": "CSS", "bytes": "7825" }, { "name": "GAP", "bytes": "1466" }, { "name": "Java", "bytes": "6353511" }, { "name": "Perl", "bytes": "9622" }, { "name": "Python", "bytes": "17912" }, { "name": "Ruby", "bytes": "1115" }, { "name": "Shell", "bytes": "5058" }, { "name": "TeX", "bytes": "305345" }, { "name": "XSLT", "bytes": "2185" } ], "symlink_target": "" }
module StripeMock module RequestHandlers module BalanceTransactions def BalanceTransactions.included(klass) klass.add_handler 'get /v1/balance_transactions/(.*)', :get_balance_transaction klass.add_handler 'get /v1/balance_transactions', :list_balance_transactions end def get_balance_transaction(route, method_url, params, headers) route =~ method_url assert_existence :balance_transaction, $1, hide_additional_attributes(balance_transactions[$1]) end def list_balance_transactions(route, method_url, params, headers) values = balance_transactions.values if params.has_key?(:transfer) # If transfer supplied as params, need to filter the btxns returned to only include those with the specified transfer id values = values.select{|btxn| btxn[:transfer] == params[:transfer]} end Data.mock_list_object(values.map{|btxn| hide_additional_attributes(btxn)}, params) end private def hide_additional_attributes(btxn) # For automatic Stripe transfers, the transfer attribute on balance_transaction stores the transfer which # included this balance_transaction. However, it is not exposed as a field returned on a balance_transaction. # Therefore, need to not show this attribute if it exists. if !btxn.nil? btxn.reject{|k,v| k == :transfer } end end end end end
{ "content_hash": "5c7b12cc94fc45cf49aa78571b83b79d", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 130, "avg_line_length": 39.7027027027027, "alnum_prop": 0.6780122532334921, "repo_name": "hinthealth/stripe-ruby-mock", "id": "50d29a0a78e949b5b71e1899ab7a999b7d5f2e7e", "size": "1469", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "lib/stripe_mock/request_handlers/balance_transactions.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "483941" } ], "symlink_target": "" }
package edu.gemini.catalog.votable import java.net.{UnknownHostException, URL} import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger import edu.gemini.catalog.api._ import edu.gemini.spModel.core._ import org.apache.commons.httpclient.NameValuePair import org.specs2.mutable.SpecificationWithJUnit import org.specs2.time.NoTimeConversions import scala.concurrent._ import scala.concurrent.duration._ import scala.concurrent.ExecutionContext.Implicits.global import scalaz.NonEmptyList class VoTableClientSpec extends SpecificationWithJUnit with VoTableClient with NoTimeConversions { val noMagnitudeConstraint = MagnitudeConstraints(SingleBand(MagnitudeBand.J), FaintnessConstraint(100), None) "The VoTable client" should { val ra = RightAscension.fromAngle(Angle.fromDegrees(10)) val dec = Declination.fromAngle(Angle.fromDegrees(20)).getOrElse(Declination.zero) val coordinates = Coordinates(ra, dec) val query = CatalogQuery(coordinates, RadiusConstraint.between(Angle.fromDegrees(0), Angle.fromDegrees(0.1)), noMagnitudeConstraint, UCAC4) case class CountingCachedBackend(counter: AtomicInteger, file: String) extends CachedBackend { override val catalogUrls = NonEmptyList(new URL(s"file://$file")) override protected def query(e: SearchKey) = { counter.incrementAndGet() VoTableParser.parse(UCAC4, this.getClass.getResourceAsStream(file)).fold(p => QueryResult(e.query, CatalogQueryResult(TargetsTable.Zero, List(p))), y => QueryResult(e.query, CatalogQueryResult(y))) } } "produce query params" in { ConeSearchBackend.queryParams(query) should beEqualTo(Array(new NameValuePair("CATALOG", "ucac4"), new NameValuePair("RA", "10.000"), new NameValuePair("DEC", "20.000"), new NameValuePair("SR", "0.100"))) } "make a query to a bad site" in { Await.result(doQuery(query, new URL("http://unknown site"), ConeSearchBackend), 30.seconds) should throwA[UnknownHostException] } "be able to select the first successful of several futures" in { def f1 = Future { Thread.sleep(1000); throw new RuntimeException("oops") } def f2 = Future { Thread.sleep(2000); 42 } // this one should complete first def f3 = Future { Thread.sleep(3000); 99 } Await.result(selectOne(NonEmptyList(f1, f2, f3)), 3.seconds) should beEqualTo(42) } "make a query" in { // This test loads a file. There is not much to test but it exercises the query backend chain Await.result(VoTableClient.catalog(query, TestVoTableBackend("/votable-ucac4.xml")), 5.seconds).result.containsError should beFalse } "use the cache to skip queries" in { val counter = new AtomicInteger(0) val countingBackend = CountingCachedBackend(counter, "/votable-ucac4.xml") // Backend should be hit at most once per url val r = for { f1 <- VoTableClient.catalog(query, countingBackend) f2 <- VoTableClient.catalog(query, countingBackend) } yield (f1, f2) // Check both have the same results val result = Await.result(r, 10.seconds) result._1 should beEqualTo(result._2) // Depending on timing it could hit all or less than all parallel urls counter.get() should be_<=(countingBackend.catalogUrls.size) } "use the cache to skip queries that occupy a subset" in { val counter = new AtomicInteger(0) val countingBackend = CountingCachedBackend(counter, "/votable-ucac4.xml") // query2 has smaller radius val query2 = CatalogQuery(coordinates, RadiusConstraint.between(Angle.fromDegrees(0), Angle.fromDegrees(0.1)), noMagnitudeConstraint, UCAC4) // Backend should be hit at most once per url val r = for { f1 <- VoTableClient.catalog(query, countingBackend) f2 <- VoTableClient.catalog(query2, countingBackend) } yield (f1, f2) Await.result(r, 10.seconds) // Depending on timing it could hit all or less than all parallel urls counter.get() should be_<=(countingBackend.catalogUrls.size) } "cache should widen the search to improve efficiency" in { val counter = new AtomicInteger(0) val countingBackend = CountingCachedBackend(counter, "/votable-ucac4.xml") // query2 has a bit bigger radius but the widening effect should avoid doing another query val query = CatalogQuery(coordinates, RadiusConstraint.between(Angle.fromDegrees(0), Angle.fromArcmin(10)), noMagnitudeConstraint, UCAC4) val query2 = CatalogQuery(coordinates, RadiusConstraint.between(Angle.fromDegrees(0), Angle.fromArcmin(12)), noMagnitudeConstraint, UCAC4) // Backend should be hit at most once per url val r = for { f1 <- VoTableClient.catalog(query, countingBackend) _ <- Future.successful(TimeUnit.SECONDS.sleep(1)) // Give it time to hit the first query f2 <- VoTableClient.catalog(query2, countingBackend) } yield (f1, f2) // Depending on timing it could hit all or less than all parallel urls counter.get() should be_<=(countingBackend.catalogUrls.size) } "cache should widen the search to improve efficiency, part 2" in { val counter = new AtomicInteger(0) val countingBackend = CountingCachedBackend(counter, "/votable-ucac4.xml") // query2 has a bit bigger radius but the widening effect should avoid doing another query val query2 = CatalogQuery(coordinates, RadiusConstraint.between(Angle.fromDegrees(0), Angle.fromDegrees(0.11)), noMagnitudeConstraint, UCAC4) // query3 is wider it should hit the catalog again val query3 = CatalogQuery(coordinates, RadiusConstraint.between(Angle.fromDegrees(0), Angle.fromDegrees(0.2)), noMagnitudeConstraint, UCAC4) // Backend should be hit at most once per url val r = for { f1 <- VoTableClient.catalog(query, countingBackend) _ <- Future.successful(TimeUnit.SECONDS.sleep(1)) // Give it time to hit the first query f2 <- VoTableClient.catalog(query2, countingBackend) f3 <- VoTableClient.catalog(query3, countingBackend) } yield (f1, f2, f3) // Depending on timing it could hit all or less than all parallel urls counter.get() should be_<=(2 * countingBackend.catalogUrls.size) } "cache hits should preserve the queries" in { val counter = new AtomicInteger(0) val countingBackend = CountingCachedBackend(counter, "/votable-ucac4.xml") // query2 has smaller radius val query2 = CatalogQuery(coordinates, RadiusConstraint.between(Angle.fromDegrees(0), Angle.fromDegrees(0.1)), noMagnitudeConstraint, UCAC4) // Backend should be hit at most once per url val r = for { f1 <- VoTableClient.catalog(query, countingBackend) f2 <- VoTableClient.catalog(query2, countingBackend) } yield (f1, f2) val result = Await.result(r, 10.seconds) // Check that each query is matched result._1.query should beEqualTo(query) result._2.query should beEqualTo(query2) } "cache hits should be filtered per query result" in { val counter = new AtomicInteger(0) val countingBackend = CountingCachedBackend(counter, "/votable-ucac4.xml") // query2 has smaller radius val query2 = CatalogQuery(coordinates, RadiusConstraint.between(Angle.fromDegrees(0), Angle.fromDegrees(0.05)), noMagnitudeConstraint, UCAC4) // val r = for { f1 <- VoTableClient.catalog(query, countingBackend) _ <- Future.successful(TimeUnit.SECONDS.sleep(1)) // Give it time to hit the first query f2 <- VoTableClient.catalog(query2, countingBackend) } yield (f1, f2) val result = Await.result(r, 10.seconds) // Check that the second query has less hits than the first given its smaller range result._2.result.targets.rows.length should beLessThan(result._1.result.targets.rows.length) } "include query params" in { val counter = new AtomicInteger(0) val countingBackend = CountingCachedBackend(counter, "/votable-ucac4.xml") val mc = MagnitudeConstraints(SingleBand(MagnitudeBand.J), FaintnessConstraint(15.0), None) val query = CatalogQuery(coordinates, RadiusConstraint.between(Angle.fromDegrees(0), Angle.fromDegrees(0.1)), mc, UCAC4) val result = Await.result(VoTableClient.catalog(query, countingBackend), 10.seconds) // Extract the query params from the results result.query should beEqualTo(query) } } }
{ "content_hash": "5d46ab3d3c9d8de1ba908a622926794c", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 210, "avg_line_length": 55.13548387096774, "alnum_prop": 0.7091036742335596, "repo_name": "arturog8m/ocs", "id": "f3680c7bc6509bf55db552265176b7e5bd301f92", "size": "8546", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "bundle/edu.gemini.catalog/src/test/scala/edu/gemini/catalog/votable/VoTableClientSpec.scala", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7919" }, { "name": "HTML", "bytes": "490242" }, { "name": "Java", "bytes": "14504312" }, { "name": "JavaScript", "bytes": "7962" }, { "name": "Scala", "bytes": "4967047" }, { "name": "Shell", "bytes": "4989" }, { "name": "Tcl", "bytes": "2841" } ], "symlink_target": "" }
using namespace Dune; using namespace Dune::GDT; template <class G> using Order1MixedContinuousLagrangeSpace = ContinuousLagrangeSpaceOnMixedLeafViewTest<G, 1, double, 1>; TYPED_TEST_SUITE(Order1MixedContinuousLagrangeSpace, MixedGridsWithConformingIntersections); TYPED_TEST(Order1MixedContinuousLagrangeSpace, gives_correct_identification) { this->gives_correct_identification(); } TYPED_TEST(Order1MixedContinuousLagrangeSpace, basis_exists_on_each_element_with_correct_size) { this->basis_of_lagrange_space_exists_on_each_element_with_correct_size(); } TYPED_TEST(Order1MixedContinuousLagrangeSpace, basis_exists_on_each_element_with_correct_order) { this->basis_of_lagrange_space_exists_on_each_element_with_correct_order(); } TYPED_TEST(Order1MixedContinuousLagrangeSpace, mapper_reports_correct_num_DoFs_on_each_element) { this->mapper_reports_correct_num_DoFs_of_lagrange_space_on_each_element(); } TYPED_TEST(Order1MixedContinuousLagrangeSpace, mapper_reports_correct_max_num_DoFs) { this->mapper_reports_correct_max_num_DoFs(); } TYPED_TEST(Order1MixedContinuousLagrangeSpace, mapper_maps_correctly) { this->mapper_maps_correctly(); } TYPED_TEST(Order1MixedContinuousLagrangeSpace, lagrange_points_exist_on_each_element_with_correct_size) { this->lagrange_points_exist_on_each_element_with_correct_size(); } TYPED_TEST(Order1MixedContinuousLagrangeSpace, basis_is_lagrange_basis) { this->basis_is_lagrange_basis(); } TYPED_TEST(Order1MixedContinuousLagrangeSpace, basis_jacobians_seem_to_be_correct) { this->template basis_jacobians_of_lagrange_space_seem_to_be_correct<>(); } TYPED_TEST(Order1MixedContinuousLagrangeSpace, local_interpolation_seems_to_be_correct) { this->local_interpolation_seems_to_be_correct(); } template <class G> using Order2MixedContinuousLagrangeSpace = ContinuousLagrangeSpaceOnMixedLeafViewTest<G, 1, double, 2>; TYPED_TEST_SUITE(Order2MixedContinuousLagrangeSpace, MixedGridsWithConformingIntersections); TYPED_TEST(Order2MixedContinuousLagrangeSpace, gives_correct_identification) { this->gives_correct_identification(); } TYPED_TEST(Order2MixedContinuousLagrangeSpace, basis_exists_on_each_element_with_correct_size) { this->basis_of_lagrange_space_exists_on_each_element_with_correct_size(); } TYPED_TEST(Order2MixedContinuousLagrangeSpace, basis_exists_on_each_element_with_correct_order) { this->basis_of_lagrange_space_exists_on_each_element_with_correct_order(); } TYPED_TEST(Order2MixedContinuousLagrangeSpace, mapper_reports_correct_num_DoFs_on_each_element) { this->mapper_reports_correct_num_DoFs_of_lagrange_space_on_each_element(); } TYPED_TEST(Order2MixedContinuousLagrangeSpace, mapper_reports_correct_max_num_DoFs) { this->mapper_reports_correct_max_num_DoFs(); } TYPED_TEST(Order2MixedContinuousLagrangeSpace, mapper_maps_correctly) { this->mapper_maps_correctly(); } TYPED_TEST(Order2MixedContinuousLagrangeSpace, lagrange_points_exist_on_each_element_with_correct_size) { this->lagrange_points_exist_on_each_element_with_correct_size(); } TYPED_TEST(Order2MixedContinuousLagrangeSpace, basis_is_lagrange_basis) { this->basis_is_lagrange_basis(); } TYPED_TEST(Order2MixedContinuousLagrangeSpace, basis_jacobians_seem_to_be_correct) { this->template basis_jacobians_of_lagrange_space_seem_to_be_correct<>(); } TYPED_TEST(Order2MixedContinuousLagrangeSpace, local_interpolation_seems_to_be_correct) { this->local_interpolation_seems_to_be_correct(); }
{ "content_hash": "6e2abf8e518aeb5072d7988d6de75ab7", "timestamp": "", "source": "github", "line_count": 92, "max_line_length": 103, "avg_line_length": 37.51086956521739, "alnum_prop": 0.808171544479861, "repo_name": "pymor/dune-gdt", "id": "4761d87016730c94d1266248680249cfe7865376", "size": "4097", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "dune/gdt/test/spaces/spaces_h1_continuous_lagrange__mixed_grids.cc", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C++", "bytes": "1214423" }, { "name": "CMake", "bytes": "10605" } ], "symlink_target": "" }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Original XmlUnit license #pragma warning disable 1591 #pragma warning disable 3001 namespace MbUnit.Framework.Xml { using System.Xml; public class DiffConfiguration { public static readonly WhitespaceHandling DEFAULT_WHITESPACE_HANDLING = WhitespaceHandling.All; public static readonly string DEFAULT_DESCRIPTION = "XmlDiff"; public static readonly bool DEFAULT_USE_VALIDATING_PARSER = true; private readonly string _description; private readonly bool _useValidatingParser; private readonly WhitespaceHandling _whitespaceHandling; public DiffConfiguration(string description, bool useValidatingParser, WhitespaceHandling whitespaceHandling) { _description = description; _useValidatingParser = useValidatingParser; _whitespaceHandling = whitespaceHandling; } public DiffConfiguration(string description, WhitespaceHandling whitespaceHandling) : this (description, DEFAULT_USE_VALIDATING_PARSER, whitespaceHandling) {} public DiffConfiguration(WhitespaceHandling whitespaceHandling) : this(DEFAULT_DESCRIPTION, DEFAULT_USE_VALIDATING_PARSER, whitespaceHandling) {} public DiffConfiguration(string description) : this(description, DEFAULT_USE_VALIDATING_PARSER, DEFAULT_WHITESPACE_HANDLING) {} public DiffConfiguration(bool useValidatingParser) : this(DEFAULT_DESCRIPTION, useValidatingParser, DEFAULT_WHITESPACE_HANDLING) { } public DiffConfiguration() : this(DEFAULT_DESCRIPTION, DEFAULT_USE_VALIDATING_PARSER, DEFAULT_WHITESPACE_HANDLING) {} public string Description { get { return _description; } } public bool UseValidatingParser { get { return _useValidatingParser; } } public WhitespaceHandling WhitespaceHandling { get { return _whitespaceHandling; } } } }
{ "content_hash": "35ae017c1c755034a9d32420f6373f5e", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 103, "avg_line_length": 36.21590909090909, "alnum_prop": 0.5933479761531221, "repo_name": "mterwoord/mbunit-v3", "id": "6a186d942a365dec44ddf2b30edaeb268e51f1ef", "size": "4909", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "src/MbUnit/MbUnit.Compatibility/Framework/Xml/DiffConfiguration.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "8718" }, { "name": "Batchfile", "bytes": "31812" }, { "name": "C", "bytes": "1006" }, { "name": "C#", "bytes": "13534505" }, { "name": "C++", "bytes": "136700" }, { "name": "CSS", "bytes": "14400" }, { "name": "HTML", "bytes": "3812671" }, { "name": "JavaScript", "bytes": "6632" }, { "name": "Objective-C", "bytes": "1024" }, { "name": "PowerShell", "bytes": "11691" }, { "name": "Ruby", "bytes": "3597212" }, { "name": "Visual Basic", "bytes": "12688" }, { "name": "XSLT", "bytes": "123017" } ], "symlink_target": "" }
<?php namespace common\tests\unit\settlement; use common\fixtures\helpers\SettlementFixtureHelper; use common\tests\unit\Unit; use Decimal\Decimal; class CalculationTest extends Unit { private SettlementFixtureHelper $settlementFixture; public function _before() { parent::_before(); $this->settlementFixture = new SettlementFixtureHelper($this->tester); } /** * @return array */ public function _fixtures(): array { return array_merge( SettlementFixtureHelper::settlement(), SettlementFixtureHelper::pay(), ); } public function testPayed(): void { $model = $this->settlementFixture->grabSettlement('payed-with-single-costs'); $this->tester->assertTrue($model->isPayed()); $this->tester->assertTrue( (new Decimal(1230)) ->equals($model->getPays()->getPayedSum()) ); $this->tester->assertTrue( (new Decimal(0)) ->equals($model->getNotPayedPays()->getValueSum()) ); } public function testNotPayed(): void { $model = $this->settlementFixture->grabSettlement('not-payed-with-double-costs'); $this->tester->assertFalse($model->isPayed()); $this->tester->assertTrue( (new Decimal(0)) ->equals($model->getPays()->getPayedSum()) ); $this->tester->assertTrue( (new Decimal(1230)) ->equals($model->getNotPayedPays()->getValueSum()) ); } }
{ "content_hash": "1852c7a246b546130d4cb395c95dd3ed", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 83, "avg_line_length": 24.40740740740741, "alnum_prop": 0.6904400606980273, "repo_name": "edzima/VestraTele", "id": "39de281f8a05fa64ca37db29f6fea1707540aff8", "size": "1318", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "common/tests/unit/settlement/CalculationTest.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "970" }, { "name": "CSS", "bytes": "6759" }, { "name": "Dockerfile", "bytes": "327" }, { "name": "HTML", "bytes": "7549" }, { "name": "JavaScript", "bytes": "27669" }, { "name": "PHP", "bytes": "3099238" }, { "name": "Shell", "bytes": "3173" }, { "name": "TypeScript", "bytes": "5231" }, { "name": "Vue", "bytes": "34794" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Metasphaeria piricola var. periplocae Sacc. ### Remarks null
{ "content_hash": "c432e6890c112a6d897d82f11ea2720e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 43, "avg_line_length": 11.384615384615385, "alnum_prop": 0.722972972972973, "repo_name": "mdoering/backbone", "id": "a5c6e4ed9f6510cdc272227c178b899bf646f4f2", "size": "215", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Dothideales/Dothioraceae/Metasphaeria/Metasphaeria piricola/Metasphaeria piricola periplocae/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!-- @license Copyright (C) 2015 The Android Open Source Project Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <link rel="import" href="../../../behaviors/base-url-behavior/base-url-behavior.html"> <link rel="import" href="../../../behaviors/gr-change-table-behavior/gr-change-table-behavior.html"> <link rel="import" href="../../../behaviors/gr-url-encoding-behavior/gr-url-encoding-behavior.html"> <link rel="import" href="../../../behaviors/keyboard-shortcut-behavior/keyboard-shortcut-behavior.html"> <link rel="import" href="../../../behaviors/rest-client-behavior/rest-client-behavior.html"> <link rel="import" href="../../../bower_components/polymer/polymer.html"> <link rel="import" href="../../../styles/gr-change-list-styles.html"> <link rel="import" href="../../core/gr-navigation/gr-navigation.html"> <link rel="import" href="../../shared/gr-cursor-manager/gr-cursor-manager.html"> <link rel="import" href="../gr-change-list-item/gr-change-list-item.html"> <link rel="import" href="../../../styles/shared-styles.html"> <dom-module id="gr-change-list"> <template> <style include="shared-styles"></style> <style include="gr-change-list-styles"> #changeList { border-collapse: collapse; width: 100%; } </style> <table id="changeList"> <tr class="topHeader"> <th class="leftPadding"></th> <th class="star" hidden$="[[!showStar]]" hidden></th> <th class="number" hidden$="[[!showNumber]]" hidden>#</th> <template is="dom-repeat" items="[[changeTableColumns]]" as="item"> <th class$="[[_lowerCase(item)]]" hidden$="[[isColumnHidden(item, visibleChangeTableColumns)]]"> [[item]] </th> </template> <template is="dom-repeat" items="[[labelNames]]" as="labelName"> <th class="label" title$="[[labelName]]"> [[_computeLabelShortcut(labelName)]] </th> </template> </tr> <template is="dom-repeat" items="[[sections]]" as="changeSection" index-as="sectionIndex"> <template is="dom-if" if="[[changeSection.sectionName]]"> <tr class="groupHeader"> <td class="leftPadding"></td> <td class="star" hidden$="[[!showStar]]" hidden></td> <td class="cell" colspan$="[[_computeColspan(changeTableColumns, labelNames)]]"> <a href$="[[_sectionHref(changeSection.query)]]"> [[changeSection.sectionName]] </a> </td> </tr> </template> <template is="dom-if" if="[[_isEmpty(changeSection)]]"> <tr class="noChanges"> <td class="leftPadding"></td> <td class="star" hidden$="[[!showStar]]" hidden></td> <td class="cell" colspan$="[[_computeColspan(changeTableColumns, labelNames)]]"> <template is="dom-if" if="[[_isOutgoing(changeSection)]]"> <slot name="empty-outgoing"></slot> </template> <template is="dom-if" if="[[!_isOutgoing(changeSection)]]"> No changes </template> </td> </tr> </template> <template is="dom-repeat" items="[[changeSection.results]]" as="change"> <gr-change-list-item selected$="[[_computeItemSelected(sectionIndex, index, selectedIndex)]]" highlight$="[[_computeItemHighlight(account, change)]]" needs-review$="[[_computeItemNeedsReview(account, change, showReviewedState)]]" change="[[change]]" visible-change-table-columns="[[visibleChangeTableColumns]]" show-number="[[showNumber]]" show-star="[[showStar]]" tabindex="0" label-names="[[labelNames]]"></gr-change-list-item> </template> </template> </table> <gr-cursor-manager id="cursor" index="{{selectedIndex}}" scroll-behavior="keep-visible" focus-on-move></gr-cursor-manager> </template> <script src="gr-change-list.js"></script> </dom-module>
{ "content_hash": "bb74d051ca51603e5a5d22909366b04a", "timestamp": "", "source": "github", "line_count": 106, "max_line_length": 104, "avg_line_length": 43.64150943396226, "alnum_prop": 0.5955469087764808, "repo_name": "WANdisco/gerrit", "id": "372e6beff27d3ba8779de99cb1ffd10de86d3657", "size": "4626", "binary": false, "copies": "1", "ref": "refs/heads/2.16.21_WD", "path": "polygerrit-ui/app/elements/change-list/gr-change-list/gr-change-list.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "47431" }, { "name": "GAP", "bytes": "4119" }, { "name": "Go", "bytes": "5563" }, { "name": "HTML", "bytes": "726266" }, { "name": "Java", "bytes": "11491861" }, { "name": "JavaScript", "bytes": "404723" }, { "name": "Makefile", "bytes": "7107" }, { "name": "PLpgSQL", "bytes": "3576" }, { "name": "Perl", "bytes": "9943" }, { "name": "Prolog", "bytes": "17904" }, { "name": "Python", "bytes": "267395" }, { "name": "Roff", "bytes": "32749" }, { "name": "Shell", "bytes": "133358" } ], "symlink_target": "" }
package cloudfoundry.norouter.f5.client; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.net.InetSocketAddress; import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; /** * @author Mike Heath <elcapo@gmail.com> */ public abstract class AbstractIControlClient implements IControlClient { protected static final String EXPAND_SUBCOLLECTIONS = "?expandSubcollections=true"; protected static final String LTM_URI = "/mgmt/tm/ltm"; protected static final String IRULE_URI = LTM_URI + "/rule"; protected static final String POOL_URI = LTM_URI + "/pool"; protected static final String VIRTUAL_URI = LTM_URI + "/virtual"; protected final URI address; protected final ObjectMapper mapper = new ObjectMapper(); protected final JsonNode DISABLE_POOL_MEMBER_BODY = mapper.createObjectNode() .put("session", "user-disabled"); protected AbstractIControlClient(URI address) { this.address = address; } @Override public IRule createIRule(String name, String body) { final JsonNode createdRule = postResource(IRULE_URI, new IRule(name, body)); return readValue(createdRule, IRule.class); } @Override public IRule getIRule(String name) throws ResourceNotFoundException { final String uri = IRULE_URI + "/" + name; return readValue(getResource(uri), IRule.class); } @Override public IRule updateIRule(String name, String body) { final String uri = IRULE_URI + "/" + name; final JsonNode updatedRule = putResource(uri, new IRule(name, body)); return readValue(updatedRule, IRule.class); } @Override public void deleteIRule(String name) { final String uri = IRULE_URI + "/" + name; deleteResource(uri); } @Override public Pool createPool(Pool pool) { final JsonNode createdPool = postResource(POOL_URI, pool); return readValue(createdPool, Pool.class); } @Override public Pool getPool(String name) { final String uri = POOL_URI + "/" + name + EXPAND_SUBCOLLECTIONS; final JsonNode resource = getResource(uri); return readValue(resource, Pool.class); } @Override public void deletePool(String name) { final String uri = POOL_URI + "/" + name; deleteResource(uri); } @Override public Collection<Pool> getAllPools() { return getAllPools(false); } @Override public Collection<Pool> getAllPools(boolean fetchPoolMembers) { final String uri = POOL_URI + (fetchPoolMembers ? EXPAND_SUBCOLLECTIONS : ""); final JsonNode resource = getResource(uri); final JsonNode items = resource.get("items"); final Collection<Pool> pools = new ArrayList<>(); items.elements().forEachRemaining(node -> pools.add(readValue(node, Pool.class))); return pools; } @Override public PoolMember addPoolMember(String poolName, InetSocketAddress poolMember) { return addPoolMember(poolName, poolMember, null); } @Override public PoolMember addPoolMember(String poolName, InetSocketAddress poolMember, String description) { return addPoolMember(poolName, poolMember.toString(), description); } @Override public PoolMember addPoolMember(String poolName, String poolMember) { return addPoolMember(poolName, poolMember, null); } @Override public PoolMember addPoolMember(String poolName, String poolMember, String description) { final PoolMember member = new PoolMember(poolMember, description); final JsonNode resource = postResource(membersUri(poolName), member); return readValue(resource, PoolMember.class); } @Override public void deletePoolMember(String poolName, InetSocketAddress poolMember) { deletePoolMember(poolName, poolMember.toString()); } @Override public void deletePoolMember(String poolName, String poolMember) { deleteResource(membersUri(poolName) + "/" + poolMember); } @Override public Pool updatePoolDescription(String name, String description) { final String uri = POOL_URI + "/" + name; final JsonNode resource = putResource(uri, Collections.singletonMap("description", description)); return readValue(resource, Pool.class); } @Override public PoolMember updatePoolMemberDescription(String poolName, InetSocketAddress member, String description) { final String uri = membersUri(poolName) + "/" + member.toString(); final JsonNode resource = putResource(uri, Collections.singletonMap("description", description)); return readValue(resource, PoolMember.class); } @Override public PoolMember disablePoolMember(String poolName, InetSocketAddress member) { final String uri = membersUri(poolName) + "/" + member.toString(); final JsonNode resource = putResource(uri, DISABLE_POOL_MEMBER_BODY); return readValue(resource, PoolMember.class); } @Override public VirtualServer createVirtualServer(VirtualServer virtualServer) { final JsonNode resource = postResource(VIRTUAL_URI, virtualServer); return readValue(resource, VirtualServer.class); } @Override public VirtualServer updateVirtualServer(VirtualServer virtualServer) { final String uri = VIRTUAL_URI + "/" + virtualServer.getName(); final JsonNode resource = patchResource(uri, virtualServer); return readValue(resource, VirtualServer.class); } @Override public VirtualServer getVirtualServer(String name) { final String uri = VIRTUAL_URI + "/" + name; return readValue(getResource(uri), VirtualServer.class); } @Override public void deleteVirtualServer(String name) { final String uri = VIRTUAL_URI + "/" + name; deleteResource(uri); } protected abstract JsonNode getResource(String uri); protected abstract JsonNode postResource(String uri, Object resource); protected abstract JsonNode putResource(String uri, Object resource); protected abstract JsonNode patchResource(String uri, Object resource); protected abstract void deleteResource(String uri); protected void validateResponse(int statusCode, String reason, String body, int... expectedStatusCodes) { for (int code : expectedStatusCodes) { if (code == statusCode) { return; } } switch (statusCode) { case 401: throw new AuthorizationRequiredException(reason); case 404: throw new ResourceNotFoundException(reason); case 409: throw new ConflictException(reason); default: throw new IControlException("Unexpected response: " + statusCode + " " + reason + "(" + body + ")"); } } private <T> T readValue(JsonNode node, Class<T> type) { try { return mapper.readValue(node.traverse(), type); } catch (IOException e) { throw new JsonException(e); } } private String membersUri(String poolName) { return POOL_URI + "/" + poolName + "/members"; } }
{ "content_hash": "c68aaebbae006f6362878c6af2d45502", "timestamp": "", "source": "github", "line_count": 208, "max_line_length": 111, "avg_line_length": 31.971153846153847, "alnum_prop": 0.7493233082706767, "repo_name": "cloudfoundry-community/norouter-f5", "id": "23f3eb25716fad360599e698ac076be4ca8bdbdd", "size": "7312", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/cloudfoundry/norouter/f5/client/AbstractIControlClient.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "97085" }, { "name": "Smalltalk", "bytes": "5772" } ], "symlink_target": "" }
import os from setuptools import setup, find_packages # Setup version VERSION = '0.6.0' # Read description with open('README.rst', 'r') as readme: README_TEXT = readme.read() def write_version_py(): filename = os.path.join( os.path.dirname(__file__), 'tornadowebapi', 'version.py') ver = "__version__ = '{}'\n" with open(filename, 'w') as fh: fh.write("# Autogenerated by setup.py\n") fh.write(ver.format(VERSION)) write_version_py() # main setup configuration class setup( name='tornadowebapi', version=VERSION, author='SimPhoNy Project', license='BSD', description='Tornado-based WebAPI framework', install_requires=[ "setuptools>=21.0", "tornado>=4.3" ], packages=find_packages(), include_package_data=True, zip_safe=False )
{ "content_hash": "e43155a1333b26a5b7eca38112e2192f", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 49, "avg_line_length": 21.3, "alnum_prop": 0.6150234741784038, "repo_name": "simphony/tornado-webapi", "id": "352f37ca90e7be09ddefdcac13d47a5ec8ba0f20", "size": "852", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "setup.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Makefile", "bytes": "1099" }, { "name": "Python", "bytes": "71184" } ], "symlink_target": "" }
using SoftwareKobo.Social.Sina.Weibo; using System; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Security.Authentication.Web; using Windows.Storage; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; //“空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 上有介绍 namespace Demo { /// <summary> /// 可用于自身或导航至 Frame 内部的空白页。 /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private async void BtnShareText_Click(object sender, RoutedEventArgs e) { try { WeiboClient client = await WeiboClient.CreateAsync(); var shareResult = await client.ShareTextAsync(txtShareText.Text); if (shareResult.IsSuccess) { await new MessageDialog("分享成功").ShowAsync(); } else { await new MessageDialog("分享失败,错误码" + shareResult.ErrorCode).ShowAsync(); } } catch (ArgumentException ex) { // 空字符串或长度超过 140。 await new MessageDialog(ex.Message).ShowAsync(); } catch (AuthorizeException ex) { if (ex.Result.ResponseStatus == WebAuthenticationStatus.UserCancel) { await new MessageDialog("你取消了授权").ShowAsync(); } else if (ex.Result.ResponseStatus == WebAuthenticationStatus.ErrorHttp) { await new MessageDialog("网络故障").ShowAsync(); } } catch (HttpException ex) { await new MessageDialog("网络故障:" + ex.ErrorStatus.ToString()).ShowAsync(); } } private async void BtnShareImage_Click(object sender, RoutedEventArgs e) { try { WeiboClient client = await WeiboClient.CreateAsync(); var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/唱歌1.png")); var data = (await FileIO.ReadBufferAsync(file)).ToArray(); var shareResult = await client.ShareImageAsync(data, txtShareImage.Text); if (shareResult.IsSuccess) { await new MessageDialog("分享成功").ShowAsync(); } else { await new MessageDialog("分享失败,错误码" + shareResult.ErrorCode).ShowAsync(); } } catch (ArgumentException ex) { // 空字符串或长度超过 140。 await new MessageDialog(ex.Message).ShowAsync(); } catch (AuthorizeException ex) { if (ex.Result.ResponseStatus == WebAuthenticationStatus.UserCancel) { await new MessageDialog("你取消了授权").ShowAsync(); } else if (ex.Result.ResponseStatus == WebAuthenticationStatus.ErrorHttp) { await new MessageDialog("网络故障").ShowAsync(); } } catch (HttpException ex) { await new MessageDialog("网络故障:" + ex.ErrorStatus.ToString()).ShowAsync(); } } } }
{ "content_hash": "e953eba7abd2019271568fbe3de8f812", "timestamp": "", "source": "github", "line_count": 103, "max_line_length": 114, "avg_line_length": 34, "alnum_prop": 0.5179897201599086, "repo_name": "h82258652/SoftwareKobo.Social.Sina.Weibo", "id": "37e42177e306f94fe4694dbb70803ec3a7b7ab5c", "size": "3714", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SoftwareKobo.Social.Weibo/Demo/MainPage.xaml.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "48157" } ], "symlink_target": "" }
export * from './artist-list.component'; export * from './artist-form.component'; export * from './artist-routing.module'; export * from './artist.module'; export * from './artist.service'; export * from './artist';
{ "content_hash": "5b4e62de56f51d6813278ad9427601d3", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 40, "avg_line_length": 36, "alnum_prop": 0.6851851851851852, "repo_name": "Zhanat87/go", "id": "263147e69307abc98057aef55cf201304726cea9", "size": "216", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/src/app/modules/artist/index.ts", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "72375" }, { "name": "Go", "bytes": "160404" }, { "name": "HTML", "bytes": "64682" }, { "name": "JavaScript", "bytes": "38598" }, { "name": "Makefile", "bytes": "708" }, { "name": "Nginx", "bytes": "1546" }, { "name": "PHP", "bytes": "2059" }, { "name": "PLpgSQL", "bytes": "14947" }, { "name": "Protocol Buffer", "bytes": "1597" }, { "name": "Python", "bytes": "26" }, { "name": "Ruby", "bytes": "1277" }, { "name": "Shell", "bytes": "29078" }, { "name": "TypeScript", "bytes": "195540" } ], "symlink_target": "" }
.. _semi_supervised: =================================================== Semi-Supervised =================================================== .. currentmodule:: sklearn.semi_supervised `Semi-supervised learning <http://en.wikipedia.org/wiki/Semi-supervised_learning>`_ is a situation in which in your training data some of the samples are not labeled. The semi-supervised estimators, in :mod:`sklean.semi_supervised` are able to make use of this addition unlabeled data to capture better the shape of the underlying data distribution and generalize better to new samples. These algorithms can perform well when we have a very small amount of labeled points and a large amount of unlabeled points. .. topic:: Unlabeled entries in `y` It is important to assign an identifier to unlabeled points along with the labeled data when training the model with the `fit` method. The identifier that this implementation uses the integer value :math:`-1`. .. _label_propagation: Label Propagation ================= Label propagation denote a few variations of semi-supervised graph inference algorithms. A few features available in this model: * Can be used for classification and regression tasks * Kernel methods to project data into alternate dimensional spaces `scikit-learn` provides two label propagation models: :class:`LabelPropagation` and :class:`LabelSpreading`. Both work by constructing a similarity graph over all items in the input dataset. .. figure:: ../auto_examples/semi_supervised/images/plot_label_propagation_structure_1.png :target: ../auto_examples/semi_supervised/plot_label_propagation_structure.html :align: center :scale: 60% **An illustration of label-propagation:** *the structure of unlabeled observations is consistent with the class structure, and thus the class label can be propagated to the unlabeled observations of the training set.* :class:`LabelPropagation` and :class:`LabelSpreading` differ in modifications to the similarity matrix that graph and the clamping effect on the label distributions. Clamping allows the algorithm to change the weight of the true ground labeled data to some degree. The :class:`LabelPropagation` algorithm performs hard clamping of input labels, which means :math:`\alpha=1`. This clamping factor can be relaxed, to say :math:`\alpha=0.8`, which means that we will always retain 80 percent of our original label distribution, but the algorithm gets to change it's confidence of the distribution within 20 percent. :class:`LabelPropagation` uses the raw similarity matrix constructed from the data with no modifications. In contrast, :class:`LabelSpreading` minimizes a loss function that has regularization properties, as such it is often more robust to noise. The algorithm iterates on a modified version of the original graph and normalizes the edge weights by computing the normalized graph Laplacian matrix. This procedure is also used in :ref:`spectral_clustering`. Label propagation models have two built-in kernel methods. Choice of kernel effects both scalability and performance of the algorithms. The following are available: * rbf (:math:`\exp(-\gamma |x-y|^2), \gamma > 0`). :math:`\gamma` is specified by keyword gamma. * knn (:math:`1[x' \in kNN(x)]`). :math:`k` is specified by keyword n_neighbors. RBF kernel will produce a fully connected graph which is represented in memory by a dense matrix. This matrix may be very large and combined with the cost of performing a full matrix multiplication calculation for each iteration of the algorithm can lead to prohibitively long running times. On the other hand, the KNN kernel will produce a much more memory friendly sparse matrix which can drastically reduce running times. .. topic:: Examples * :ref:`example_semi_supervised_plot_label_propagation_versus_svm_iris.py` * :ref:`example_semi_supervised_plot_label_propagation_structure.py` * :ref:`example_semi_supervised_plot_label_propagation_digits_active_learning.py` .. topic:: References [1] Yoshua Bengio, Olivier Delalleau, Nicolas Le Roux. In Semi-Supervised Learning (2006), pp. 193-216 [2] Olivier Delalleau, Yoshua Bengio, Nicolas Le Roux. Efficient Non-Parametric Function Induction in Semi-Supervised Learning. AISTAT 2005 http://research.microsoft.com/en-us/people/nicolasl/efficient_ssl.pdf
{ "content_hash": "ea3da5588a46b2007d801e7f39ccd5c6", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 90, "avg_line_length": 44.292929292929294, "alnum_prop": 0.7562143671607754, "repo_name": "Sklearn-HMM/scikit-learn-HMM", "id": "20f1bc898151e5530a44bb2f1e81cacb89b35004", "size": "4385", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "doc/modules/label_propagation.rst", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "16556045" }, { "name": "C++", "bytes": "136541" }, { "name": "JavaScript", "bytes": "20564" }, { "name": "Python", "bytes": "3344128" }, { "name": "Shell", "bytes": "3768" } ], "symlink_target": "" }
using System; /// <summary> /// Add(System.TimeSpan) /// </summary> public class TimeSpanAdd { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call Add with rand valid value"); try { retVal = VerificationHelper(new TimeSpan(TestLibrary.Generator.GetInt32(-55)), new TimeSpan(TestLibrary.Generator.GetInt32(-55)), "001.1") && retVal; retVal = VerificationHelper(new TimeSpan(TestLibrary.Generator.GetInt32(-55)), new TimeSpan(0), "001.2") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call Add with boundary value"); try { retVal = VerificationHelper(TimeSpan.MaxValue, new TimeSpan(0), "002.1") && retVal; retVal = VerificationHelper(TimeSpan.MinValue, new TimeSpan(0), "002.2") && retVal; retVal = VerificationHelper(TimeSpan.MaxValue, TimeSpan.MinValue, "002.3") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: OverflowException should be thrown when The resulting TimeSpan is less than MinValue or greater than MaxValue"); try { retVal = VerificationHelper(TimeSpan.MaxValue, new TimeSpan(-1), "101.1") && retVal; retVal = VerificationHelper(TimeSpan.MinValue, new TimeSpan(1), "101.2") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("101.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { TimeSpanAdd test = new TimeSpanAdd(); TestLibrary.TestFramework.BeginTestCase("TimeSpanAdd"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Fields private bool VerificationHelper(TimeSpan span1, TimeSpan span2, string errorNo) { bool retVal = true; TimeSpan result = span1.Add(span2); long desired = span1.Ticks + span2.Ticks; long actual = result.Ticks; if (desired != actual) { TestLibrary.TestFramework.LogError(errorNo, "Calling Add method returns a wrong TimeSpan instance"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] desired = " + desired + ", actual = " + actual + ", span1.Ticks = " + span1.Ticks + ", span2.Ticks = " + span2.Ticks); retVal = false; } return retVal; } private bool VerificationHelper(TimeSpan span1, TimeSpan span2, Type desiredException, string errorNo) { bool retVal = true; try { TimeSpan result = span1.Add(span2); TestLibrary.TestFramework.LogError(errorNo + ".1", desiredException + " is not thrown"); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] span1.Ticks = " + span1.Ticks + ", span2.Ticks = " + span2.Ticks); retVal = false; } catch (Exception e) { TestLibrary.TestFramework.LogError(errorNo + ".0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion }
{ "content_hash": "8d49602be59845c6ffae9c8fdbdbcb56", "timestamp": "", "source": "github", "line_count": 158, "max_line_length": 197, "avg_line_length": 30.563291139240505, "alnum_prop": 0.591219714226548, "repo_name": "AlfredoMS/coreclr", "id": "93a6f70e75df853cf59b3ed6ef7617625f4f1461", "size": "4829", "binary": false, "copies": "16", "ref": "refs/heads/master", "path": "tests/src/CoreMangLib/cti/system/timespan/timespanadd.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "939391" }, { "name": "Awk", "bytes": "5652" }, { "name": "Batchfile", "bytes": "34621" }, { "name": "C", "bytes": "6422038" }, { "name": "C#", "bytes": "118937796" }, { "name": "C++", "bytes": "66278196" }, { "name": "CMake", "bytes": "522047" }, { "name": "Groff", "bytes": "529523" }, { "name": "Groovy", "bytes": "19252" }, { "name": "Makefile", "bytes": "2314" }, { "name": "Objective-C", "bytes": "224503" }, { "name": "Perl", "bytes": "63850" }, { "name": "PowerShell", "bytes": "4332" }, { "name": "Python", "bytes": "8165" }, { "name": "Shell", "bytes": "55415" }, { "name": "Smalltalk", "bytes": "1481952" } ], "symlink_target": "" }
package in.srain.cube.image; import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import in.srain.cube.image.iface.ImageLoadHandler; import in.srain.cube.util.CLog; import in.srain.cube.util.CubeDebug; import in.srain.cube.util.Encrypt; import java.lang.ref.WeakReference; /** * A wrapper of the related information used in loading a bitmap * * @author http://www.liaohuqiu.net */ public class ImageTask { protected static final String LOG_TAG = CubeDebug.DEBUG_IMAGE_LOG_TAG_TASK; private static final Object sPoolSync = new Object(); private static ImageTask sTop; private static int sPoolSize = 0; private static final int MAX_POOL_SIZE = 20; private static boolean USE_POOL = false; private static int sId = 0; private final static String SIZE_SP = "_"; // 0000 0111 private static final int ERROR_CODE_MASK = 0x07; // error code, max 0x07 public final static int ERROR_NETWORK = 0x01; public final static int ERROR_BAD_FORMAT = 0x02; public final static int ERROR_EMPTY_URL = 0x03; /** * bits: * 1 error-code * 2 error-code * 3 error-code * 4 loading * 5 pre-load */ private final static int STATUS_LOADING = 0x01 << 3; private final static int STATUS_PRE_LOAD = 0x02 << 3; private int mFlag = 0; protected int mId = 0; // the origin request url for the image. protected String mOriginUrl; // In some situations, we may store the same image in some different servers. So the same image will related to some different urls. private String mIdentityUrl; // The key related to the image this ImageTask is requesting. private String mIdentityKey; // cache for toString(); private String mStr; protected Point mRequestSize = new Point(); protected Point mBitmapOriginSize = new Point(); protected ImageLoadRequest mRequest; protected ImageViewHolder mFirstImageViewHolder; protected ImageTaskStatistics mImageTaskStatistics; ImageTask next; private boolean mHasRecycled = false; protected void clearForRecycle() { mHasRecycled = true; mFlag = 0; mOriginUrl = null; mIdentityUrl = null; mIdentityKey = null; mStr = null; mRequestSize.set(0, 0); mBitmapOriginSize.set(0, 0); mRequest = null; mFirstImageViewHolder = null; mImageTaskStatistics = null; } public static ImageTask obtain() { if (!USE_POOL) { return null; } // pop top, make top.next as top synchronized (sPoolSync) { if (sTop != null) { ImageTask m = sTop; sTop = m.next; m.next = null; sPoolSize--; m.mHasRecycled = false; if (CubeDebug.DEBUG_IMAGE) { CLog.d(LOG_TAG, "%s, obtain reused, pool remain: %d", m, sPoolSize); } return m; } } return null; } public void tryToRecycle() { if (!USE_POOL) { return; } clearForRecycle(); // mark top as the next of current, then push current as pop synchronized (sPoolSync) { if (sPoolSize < MAX_POOL_SIZE) { next = sTop; sTop = this; sPoolSize++; if (CubeDebug.DEBUG_IMAGE) { CLog.d(LOG_TAG, "%s is put to recycle poll, pool size: %d", this, sPoolSize); } else { if (CubeDebug.DEBUG_IMAGE) { CLog.d(LOG_TAG, "%s is not recycled, the poll is full: %d", this, sPoolSize); } } } } } public ImageTask renewForRequest(ImageLoadRequest request) { if (CubeDebug.DEBUG_IMAGE) { int lastId = mId; mId = ++sId; CLog.d(LOG_TAG, "%s, renew: %s => %s", this, lastId, mId); } else { mId = ++sId; } mStr = null; if (ImagePerformanceStatistics.sample(mId)) { mImageTaskStatistics = new ImageTaskStatistics(); } mOriginUrl = request.getUrl(); mRequestSize.set(request.getRequestWidth(), request.getRequestHeight()); mRequest = request; return this; } public ImageTask setOriginUrl(String originUrl) { mOriginUrl = originUrl; return this; } public ImageTask setRequestSize(int requestWidth, int requestHeight) { mRequestSize.set(requestWidth, requestHeight); return this; } /** * For accessing the identity url * * @return */ public String getIdentityUrl() { if (null == mIdentityUrl) { mIdentityUrl = generateIdentityUrl(mOriginUrl); } return mIdentityUrl; } /** * In some situations, we may store the same image in some different servers. So the same image will related to some different urls. * Generate the identity url according your situation. * {@link #mIdentityUrl} * * @return * @deprecated Do not overwrite this method, use {@link in.srain.cube.image.iface.NameGenerator} instead. * should be used. */ @Deprecated protected String generateIdentityUrl(String originUrl) { return ImageLoaderFactory.getNameGenerator().generateIdentityUrlFor(mRequest); } /** * Generate the identity key. * <p/> * This key should be related to the unique image this task is requesting: the size, the remote url. * * @return */ protected String generateIdentityKey() { if (mRequest.getImageReuseInfo() == null) { return getIdentityUrl(); } else { return joinSizeTagToKey(getIdentityUrl(), mRequest.getImageReuseInfo().getIdentitySize()); } } public boolean isPreLoad() { return (mFlag & STATUS_PRE_LOAD) == STATUS_PRE_LOAD; } public void setIsPreLoad() { mFlag = mFlag | STATUS_PRE_LOAD; } public boolean isLoading() { return (mFlag & STATUS_LOADING) != 0; } /** * Check the given {@link in.srain.cube.image.ImageLoadRequest} is loading. * * @param request * @return Identify the given url, if same to {@link #mIdentityUrl} return true. */ public boolean isLoadingThisUrl(ImageLoadRequest request) { String url2 = ImageLoaderFactory.getNameGenerator().generateIdentityUrlFor(request); return getIdentityUrl().equals(url2); } /** * Bind ImageView with ImageTask * * @param imageView */ public void addImageView(CubeImageView imageView) { if (null == imageView) { return; } if (null == mFirstImageViewHolder) { mFirstImageViewHolder = new ImageViewHolder(imageView); return; } ImageViewHolder holder = mFirstImageViewHolder; for (; ; holder = holder.mNext) { if (holder.contains(imageView)) { return; } if (holder.mNext == null) { break; } } ImageViewHolder newHolder = new ImageViewHolder(imageView); newHolder.mPrev = holder; holder.mNext = newHolder; } /** * Remove the ImageView from ImageTask * * @param imageView */ public void removeImageView(CubeImageView imageView) { if (null == imageView || null == mFirstImageViewHolder) { return; } ImageViewHolder holder = mFirstImageViewHolder; do { if (holder.contains(imageView)) { // Make sure entry is right. if (holder == mFirstImageViewHolder) { mFirstImageViewHolder = holder.mNext; } if (null != holder.mNext) { holder.mNext.mPrev = holder.mPrev; } if (null != holder.mPrev) { holder.mPrev.mNext = holder.mNext; } } } while ((holder = holder.mNext) != null); } /** * Check if this ImageTask has any related ImageViews. * * @return */ public boolean stillHasRelatedImageView() { if (null == mFirstImageViewHolder || mFirstImageViewHolder.getImageView() == null) { return false; } else { return true; } } /** * When loading from network * * @param handler */ public void onLoading(ImageLoadHandler handler) { mFlag = mFlag | STATUS_LOADING; if (null == handler) { return; } if (mFirstImageViewHolder == null) { handler.onLoading(this, null); } else { ImageViewHolder holder = mFirstImageViewHolder; do { final CubeImageView imageView = holder.getImageView(); if (null != imageView) { handler.onLoading(this, imageView); } } while ((holder = holder.mNext) != null); } } /** * notify loading * * @param handler * @param imageView */ public void notifyLoading(ImageLoadHandler handler, CubeImageView imageView) { if (handler == null || imageView == null) { return; } handler.onLoading(this, imageView); } /** * Will be called when begin load image data from dish or network * * @param drawable */ public void onLoadTaskFinish(BitmapDrawable drawable, ImageLoadHandler handler) { mFlag &= ~STATUS_LOADING; if (null == handler) { return; } int errorCode = mFlag & ERROR_CODE_MASK; if (errorCode > 0) { onLoadError(errorCode, handler); return; } if (null != mImageTaskStatistics) { mImageTaskStatistics.s5_beforeShow(); } if (mFirstImageViewHolder == null) { handler.onLoadFinish(this, null, drawable); } else { ImageViewHolder holder = mFirstImageViewHolder; do { final CubeImageView imageView = holder.getImageView(); if (null != imageView) { imageView.onLoadFinish(); handler.onLoadFinish(this, imageView, drawable); } } while ((holder = holder.mNext) != null); } if (null != mImageTaskStatistics) { mImageTaskStatistics.s6_afterShow(ImageProvider.getBitmapSize(drawable)); ImagePerformanceStatistics.onImageLoaded(this, mImageTaskStatistics); } } public void onLoadTaskCancel() { } public void setError(int errorCode) { if (errorCode > ERROR_CODE_MASK) { throw new IllegalArgumentException("error code undefined."); } // clear old error flag mFlag = (mFlag & ~ERROR_CODE_MASK); // set current error flag mFlag |= errorCode; } private void onLoadError(int reason, ImageLoadHandler handler) { if (mFirstImageViewHolder == null) { handler.onLoadError(this, null, reason); } else { ImageViewHolder holder = mFirstImageViewHolder; do { final CubeImageView imageView = holder.getImageView(); if (null != imageView) { imageView.onLoadFinish(); handler.onLoadError(this, imageView, reason); } } while ((holder = holder.mNext) != null); } } /** * If you have a thumbnail web service which can return multiple size image according the url, * <p/> * you can implements this method to return the specified url according the request size. * * @return */ public String getRemoteUrl() { return mOriginUrl; } /** * Return the origin request url * * @return */ public String getOriginUrl() { return mOriginUrl; } public void setBitmapOriginSize(int width, int height) { mBitmapOriginSize.set(width, height); } public Point getBitmapOriginSize() { return mBitmapOriginSize; } public Point getRequestSize() { return mRequestSize; } /** * Return the key which identifies this Image Wrapper object. */ public String getIdentityKey() { if (mIdentityKey == null) { mIdentityKey = generateIdentityKey(); } return mIdentityKey; } /** * Join the key and the size information. * * @param key * @param w * @param h * @return "$key" + "_" + "$w" + "_" + "$h" */ public static String joinSizeInfoToKey(String key, int w, int h) { if (w > 0 && h != Integer.MAX_VALUE && h > 0 && h != Integer.MAX_VALUE) { return new StringBuilder(key).append(SIZE_SP).append(w).append(SIZE_SP).append(h).toString(); } return key; } /** * Join the tag with the key. * * @param key * @param tag * @return "$key" + "_" + "$tag" */ public static String joinSizeTagToKey(String key, String tag) { return new StringBuilder(key).append(SIZE_SP).append(tag).toString(); } /** * Return the cache key for file cache. * * @return the cache key for file cache. */ public String getFileCacheKey() { return Encrypt.md5(getIdentityKey()); } /** * @param sizeKey * @return */ public String generateFileCacheKeyForReuse(String sizeKey) { return Encrypt.md5(joinSizeTagToKey(getIdentityUrl(), sizeKey)); } @Override public boolean equals(Object object) { if (object != null && object instanceof ImageTask) { return ((ImageTask) object).getIdentityKey().equals(getIdentityKey()); } return false; } @Override public String toString() { if (mStr == null) { mStr = String.format("[ImageTask@%s %s %sx%s %s]", Integer.toHexString(hashCode()), mId, mRequestSize.x, mRequestSize.y, mHasRecycled); } return mStr; } public ImageTaskStatistics getStatistics() { return mImageTaskStatistics; } /** * A tiny and light linked-list like container to hold all the ImageViews related to the ImageTask. */ private static class ImageViewHolder { private WeakReference<CubeImageView> mImageViewRef; private ImageViewHolder mNext; private ImageViewHolder mPrev; public ImageViewHolder(CubeImageView imageView) { mImageViewRef = new WeakReference<CubeImageView>(imageView); } boolean contains(CubeImageView imageView) { return mImageViewRef != null && imageView == mImageViewRef.get(); } CubeImageView getImageView() { if (null == mImageViewRef) { return null; } return mImageViewRef.get(); } } public ImageLoadRequest getRequest() { return mRequest; } }
{ "content_hash": "ebd55c32a50a0a26b3ffcea2d0e3b360", "timestamp": "", "source": "github", "line_count": 539, "max_line_length": 147, "avg_line_length": 28.4860853432282, "alnum_prop": 0.5697538100820633, "repo_name": "liqk2014/cube-sdk", "id": "f9a146ac51d832a7d0fa5fd46a850771888aa6df", "size": "15354", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "core/src/in/srain/cube/image/ImageTask.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "486258" }, { "name": "Python", "bytes": "944" }, { "name": "Shell", "bytes": "81" } ], "symlink_target": "" }
/** * InternalRedirectCreative.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201411; /** * A {@code Creative} hosted by either DoubleClick for Advertisers * (DFA) or DART * for Publishers. * <p> * Similar to third-party creatives, a DoubleClick tag is * used to retrieve a * creative asset. However, DoubleClick tags are not sent * to the user's browser. * Instead, they are processed internally within the DoubleClick * system.. */ public class InternalRedirectCreative extends com.google.api.ads.dfp.axis.v201411.Creative implements java.io.Serializable { /* A locked orientation for this creative to be displayed in. */ private com.google.api.ads.dfp.axis.v201411.LockedOrientation lockedOrientation; /* The asset size of an internal redirect creative. * Note that this may differ from {@code size} if * users set {@code overrideSize} to true. * This attribute is read-only and is populated * by Google. */ private com.google.api.ads.dfp.axis.v201411.Size assetSize; /* The internal redirect URL of the DFA or DART for Publishers * hosted creative. * This attribute is required and has a maximum length * of 1024 characters. */ private java.lang.String internalRedirectUrl; /* Allows the creative size to differ from the actual size specified * in the * internal redirect's url. This attribute is optional. */ private java.lang.Boolean overrideSize; /* {@code true} if this internal redirect creative is interstitial. */ private java.lang.Boolean isInterstitial; /* The SSL compatibility scan result for this creative. * * <p>This attribute is read-only and determined * by Google. */ private com.google.api.ads.dfp.axis.v201411.SslScanResult sslScanResult; /* The manual override for the SSL compatibility of this creative. * * <p>This attribute is optional and defaults to * {@link SslManualOverride#NO_OVERRIDE}. */ private com.google.api.ads.dfp.axis.v201411.SslManualOverride sslManualOverride; public InternalRedirectCreative() { } public InternalRedirectCreative( java.lang.Long advertiserId, java.lang.Long id, java.lang.String name, com.google.api.ads.dfp.axis.v201411.Size size, java.lang.String previewUrl, com.google.api.ads.dfp.axis.v201411.AppliedLabel[] appliedLabels, com.google.api.ads.dfp.axis.v201411.DateTime lastModifiedDateTime, com.google.api.ads.dfp.axis.v201411.BaseCustomFieldValue[] customFieldValues, java.lang.String creativeType, com.google.api.ads.dfp.axis.v201411.LockedOrientation lockedOrientation, com.google.api.ads.dfp.axis.v201411.Size assetSize, java.lang.String internalRedirectUrl, java.lang.Boolean overrideSize, java.lang.Boolean isInterstitial, com.google.api.ads.dfp.axis.v201411.SslScanResult sslScanResult, com.google.api.ads.dfp.axis.v201411.SslManualOverride sslManualOverride) { super( advertiserId, id, name, size, previewUrl, appliedLabels, lastModifiedDateTime, customFieldValues, creativeType); this.lockedOrientation = lockedOrientation; this.assetSize = assetSize; this.internalRedirectUrl = internalRedirectUrl; this.overrideSize = overrideSize; this.isInterstitial = isInterstitial; this.sslScanResult = sslScanResult; this.sslManualOverride = sslManualOverride; } /** * Gets the lockedOrientation value for this InternalRedirectCreative. * * @return lockedOrientation * A locked orientation for this creative to be displayed in. */ public com.google.api.ads.dfp.axis.v201411.LockedOrientation getLockedOrientation() { return lockedOrientation; } /** * Sets the lockedOrientation value for this InternalRedirectCreative. * * @param lockedOrientation * A locked orientation for this creative to be displayed in. */ public void setLockedOrientation(com.google.api.ads.dfp.axis.v201411.LockedOrientation lockedOrientation) { this.lockedOrientation = lockedOrientation; } /** * Gets the assetSize value for this InternalRedirectCreative. * * @return assetSize * The asset size of an internal redirect creative. * Note that this may differ from {@code size} if * users set {@code overrideSize} to true. * This attribute is read-only and is populated * by Google. */ public com.google.api.ads.dfp.axis.v201411.Size getAssetSize() { return assetSize; } /** * Sets the assetSize value for this InternalRedirectCreative. * * @param assetSize * The asset size of an internal redirect creative. * Note that this may differ from {@code size} if * users set {@code overrideSize} to true. * This attribute is read-only and is populated * by Google. */ public void setAssetSize(com.google.api.ads.dfp.axis.v201411.Size assetSize) { this.assetSize = assetSize; } /** * Gets the internalRedirectUrl value for this InternalRedirectCreative. * * @return internalRedirectUrl * The internal redirect URL of the DFA or DART for Publishers * hosted creative. * This attribute is required and has a maximum length * of 1024 characters. */ public java.lang.String getInternalRedirectUrl() { return internalRedirectUrl; } /** * Sets the internalRedirectUrl value for this InternalRedirectCreative. * * @param internalRedirectUrl * The internal redirect URL of the DFA or DART for Publishers * hosted creative. * This attribute is required and has a maximum length * of 1024 characters. */ public void setInternalRedirectUrl(java.lang.String internalRedirectUrl) { this.internalRedirectUrl = internalRedirectUrl; } /** * Gets the overrideSize value for this InternalRedirectCreative. * * @return overrideSize * Allows the creative size to differ from the actual size specified * in the * internal redirect's url. This attribute is optional. */ public java.lang.Boolean getOverrideSize() { return overrideSize; } /** * Sets the overrideSize value for this InternalRedirectCreative. * * @param overrideSize * Allows the creative size to differ from the actual size specified * in the * internal redirect's url. This attribute is optional. */ public void setOverrideSize(java.lang.Boolean overrideSize) { this.overrideSize = overrideSize; } /** * Gets the isInterstitial value for this InternalRedirectCreative. * * @return isInterstitial * {@code true} if this internal redirect creative is interstitial. */ public java.lang.Boolean getIsInterstitial() { return isInterstitial; } /** * Sets the isInterstitial value for this InternalRedirectCreative. * * @param isInterstitial * {@code true} if this internal redirect creative is interstitial. */ public void setIsInterstitial(java.lang.Boolean isInterstitial) { this.isInterstitial = isInterstitial; } /** * Gets the sslScanResult value for this InternalRedirectCreative. * * @return sslScanResult * The SSL compatibility scan result for this creative. * * <p>This attribute is read-only and determined * by Google. */ public com.google.api.ads.dfp.axis.v201411.SslScanResult getSslScanResult() { return sslScanResult; } /** * Sets the sslScanResult value for this InternalRedirectCreative. * * @param sslScanResult * The SSL compatibility scan result for this creative. * * <p>This attribute is read-only and determined * by Google. */ public void setSslScanResult(com.google.api.ads.dfp.axis.v201411.SslScanResult sslScanResult) { this.sslScanResult = sslScanResult; } /** * Gets the sslManualOverride value for this InternalRedirectCreative. * * @return sslManualOverride * The manual override for the SSL compatibility of this creative. * * <p>This attribute is optional and defaults to * {@link SslManualOverride#NO_OVERRIDE}. */ public com.google.api.ads.dfp.axis.v201411.SslManualOverride getSslManualOverride() { return sslManualOverride; } /** * Sets the sslManualOverride value for this InternalRedirectCreative. * * @param sslManualOverride * The manual override for the SSL compatibility of this creative. * * <p>This attribute is optional and defaults to * {@link SslManualOverride#NO_OVERRIDE}. */ public void setSslManualOverride(com.google.api.ads.dfp.axis.v201411.SslManualOverride sslManualOverride) { this.sslManualOverride = sslManualOverride; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof InternalRedirectCreative)) return false; InternalRedirectCreative other = (InternalRedirectCreative) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.lockedOrientation==null && other.getLockedOrientation()==null) || (this.lockedOrientation!=null && this.lockedOrientation.equals(other.getLockedOrientation()))) && ((this.assetSize==null && other.getAssetSize()==null) || (this.assetSize!=null && this.assetSize.equals(other.getAssetSize()))) && ((this.internalRedirectUrl==null && other.getInternalRedirectUrl()==null) || (this.internalRedirectUrl!=null && this.internalRedirectUrl.equals(other.getInternalRedirectUrl()))) && ((this.overrideSize==null && other.getOverrideSize()==null) || (this.overrideSize!=null && this.overrideSize.equals(other.getOverrideSize()))) && ((this.isInterstitial==null && other.getIsInterstitial()==null) || (this.isInterstitial!=null && this.isInterstitial.equals(other.getIsInterstitial()))) && ((this.sslScanResult==null && other.getSslScanResult()==null) || (this.sslScanResult!=null && this.sslScanResult.equals(other.getSslScanResult()))) && ((this.sslManualOverride==null && other.getSslManualOverride()==null) || (this.sslManualOverride!=null && this.sslManualOverride.equals(other.getSslManualOverride()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getLockedOrientation() != null) { _hashCode += getLockedOrientation().hashCode(); } if (getAssetSize() != null) { _hashCode += getAssetSize().hashCode(); } if (getInternalRedirectUrl() != null) { _hashCode += getInternalRedirectUrl().hashCode(); } if (getOverrideSize() != null) { _hashCode += getOverrideSize().hashCode(); } if (getIsInterstitial() != null) { _hashCode += getIsInterstitial().hashCode(); } if (getSslScanResult() != null) { _hashCode += getSslScanResult().hashCode(); } if (getSslManualOverride() != null) { _hashCode += getSslManualOverride().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(InternalRedirectCreative.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "InternalRedirectCreative")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("lockedOrientation"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "lockedOrientation")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "LockedOrientation")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("assetSize"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "assetSize")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "Size")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("internalRedirectUrl"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "internalRedirectUrl")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("overrideSize"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "overrideSize")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("isInterstitial"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "isInterstitial")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("sslScanResult"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "sslScanResult")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "SslScanResult")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("sslManualOverride"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "sslManualOverride")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201411", "SslManualOverride")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
{ "content_hash": "4b8213d6ba137bb480f9b16065f386a7", "timestamp": "", "source": "github", "line_count": 426, "max_line_length": 140, "avg_line_length": 40.978873239436616, "alnum_prop": 0.6428366844245861, "repo_name": "raja15792/googleads-java-lib", "id": "c548c6de578722ebfad6a41d18b55b972f26899d", "size": "17457", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201411/InternalRedirectCreative.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "91011716" } ], "symlink_target": "" }
""" Build index by path into a content-keyed data store. """ # import binascii # from nlhtree import NLHLeaf # from xlattice import SHA1_BIN_NONE, SHA2_BIN_NONE # from xlcrypto import ( # AES_BLOCK_BYTES, addPKCS7Padding, stripPKCS7Padding) __all__ = ['__version__', '__version_date__', ] __version__ = '0.0.24' __version_date__ = '2018-02-27'
{ "content_hash": "829cfca06d157054fb640fba59b1a48b", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 58, "avg_line_length": 22.6875, "alnum_prop": 0.6446280991735537, "repo_name": "jddixon/bindex", "id": "920c2a3103ca8a675fae3542be89686dee9d8582", "size": "386", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/bindex/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6648" }, { "name": "Python", "bytes": "1524" }, { "name": "Shell", "bytes": "1507" } ], "symlink_target": "" }
<?php namespace test\h\c; class j { }
{ "content_hash": "1a19b5472a63022bbb03e52b18c946b0", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 19, "avg_line_length": 12.333333333333334, "alnum_prop": 0.6486486486486487, "repo_name": "darrelljefferson/themcset.com", "id": "bed4b21eb41221de072e67b4830df4c205b94b19", "size": "37", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "bin/test/h/c/j.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1099" }, { "name": "Batchfile", "bytes": "21" }, { "name": "CSS", "bytes": "889639" }, { "name": "HTML", "bytes": "17830980" }, { "name": "Java", "bytes": "58853" }, { "name": "JavaScript", "bytes": "2251931" }, { "name": "PHP", "bytes": "13665910" }, { "name": "Shell", "bytes": "7918" }, { "name": "Smarty", "bytes": "2149" } ], "symlink_target": "" }
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("Hatfield.EnviroData.DataAcquisition.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Hatfield.EnviroData.DataAcquisition.Test")] [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("c36f70aa-7be5-456b-8c3b-876c0dfdb44c")] // 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.1")] [assembly: AssemblyFileVersion("1.0.0.1")]
{ "content_hash": "72ecf1ae84110cbf6a732f4440c31fbb", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 84, "avg_line_length": 40.361111111111114, "alnum_prop": 0.7508602890571232, "repo_name": "kgarsuta/Hatfield.EnviroData.DataAcquisition", "id": "f5214b369a79428ea43405afcc2bc3185fb77590", "size": "1456", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Test/Hatfield.EnviroData.DataAcquisition.Test/Properties/AssemblyInfo.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "350861" } ], "symlink_target": "" }
id: 5e7b9f170b6c005b0e76f087 title: Ciclo de vida de um objeto challengeType: 11 videoId: p1r3h_AMMIM bilibiliIds: aid: 461998717 bvid: BV1JL411n7Hr cid: 377529681 dashedName: object-lifecycle --- # --question-- ## --text-- O que será impresso pelo código a seguir?: ```python class PartyAnimal: x = 0 name = '' def __init__(self, nam): self.name = nam print(self.name,'constructed') def party(self): self.x = self.x + 1 print(self.name,'party count',self.x) q = PartyAnimal('Quincy') m = PartyAnimal('Miya') q.party() m.party() q.party() ``` ## --answers-- <pre> Quincy constructed Miya constructed Quincy party count 1 Miya party count 2 Quincy party count 3 </pre> --- <pre> Quincy constructed Miya constructed Quincy party count 1 Miya party count 1 Quincy party count 2 </pre> --- <pre> Quincy constructed Quincy party count 1 Quincy party count 2 Miya constructed Miya party count 1 </pre> ## --video-solution-- 2
{ "content_hash": "0f18651dd02765ae1717c43cac61240f", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 45, "avg_line_length": 14.128571428571428, "alnum_prop": 0.6744186046511628, "repo_name": "FreeCodeCamp/FreeCodeCamp", "id": "74d32fbebfc00038f089e8128d489ea0de01bbad", "size": "995", "binary": false, "copies": "2", "ref": "refs/heads/i18n-sync-client", "path": "curriculum/challenges/portuguese/07-scientific-computing-with-python/python-for-everybody/object-lifecycle.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "190263" }, { "name": "HTML", "bytes": "160430" }, { "name": "JavaScript", "bytes": "546299" } ], "symlink_target": "" }
namespace browser { // Pops up an error box with an OK button. If |parent| is non-null, the box // will be modal on it. (On Mac, it is always app-modal.) Generally speaking, // this function should not be used for much. Infobars are preferred. void ShowErrorBox(gfx::NativeWindow parent, const string16& title, const string16& message); // Pops up a dialog box with two buttons (Yes/No), with the default button of // Yes. If |parent| is non-null, the box will be modal on it. (On Mac, it is // always app-modal.) Returns true if the Yes button was chosen. bool ShowYesNoBox(gfx::NativeWindow parent, const string16& title, const string16& message); } // namespace browser #endif // CHROME_BROWSER_SIMPLE_MESSAGE_BOX_H_
{ "content_hash": "45df0a4005d604892bf0893cf2168994", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 77, "avg_line_length": 42, "alnum_prop": 0.6691729323308271, "repo_name": "aYukiSekiguchi/ACCESS-Chromium", "id": "009417448692748f3a9c61154ce6e22150d6f2db", "size": "1140", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "chrome/browser/simple_message_box.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "1174606" }, { "name": "C", "bytes": "65916105" }, { "name": "C++", "bytes": "113472993" }, { "name": "F#", "bytes": "381" }, { "name": "Go", "bytes": "10440" }, { "name": "Java", "bytes": "11354" }, { "name": "JavaScript", "bytes": "8864255" }, { "name": "Objective-C", "bytes": "8990130" }, { "name": "PHP", "bytes": "97796" }, { "name": "Perl", "bytes": "903036" }, { "name": "Python", "bytes": "5269405" }, { "name": "R", "bytes": "524" }, { "name": "Shell", "bytes": "4123452" }, { "name": "Tcl", "bytes": "277077" } ], "symlink_target": "" }
cask "font-hachi-maru-pop" do version :latest sha256 :no_check url "https://github.com/google/fonts/raw/main/ofl/hachimarupop/HachiMaruPop-Regular.ttf", verified: "github.com/google/fonts/" name "Hachi Maru Pop" desc "Handwritten font" homepage "https://fonts.google.com/specimen/Hachi+Maru+Pop" font "HachiMaruPop-Regular.ttf" end
{ "content_hash": "664023be563fbdfcd0e8b6fc7345f748", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 91, "avg_line_length": 29.5, "alnum_prop": 0.731638418079096, "repo_name": "alerque/homebrew-fonts", "id": "78ec52c81a3500337111ba6f102f9ddac13d341f", "size": "354", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Casks/font-hachi-maru-pop.rb", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Python", "bytes": "8143" }, { "name": "Ruby", "bytes": "1069262" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.jaxonbrown.mcdev</groupId> <artifactId>BukkitArchetype</artifactId> <version>1.0</version> </project>
{ "content_hash": "f0a98302f4668948a9e8eb6eb3533fca", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 108, "avg_line_length": 39, "alnum_prop": 0.6783216783216783, "repo_name": "MeRPG/BukkitArchetype", "id": "3f7d24e87cfca09e585d24ca0bab9b299d887991", "size": "429", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "303" } ], "symlink_target": "" }
package org.elasticsearch.xpack.security.authz.interceptor; import org.elasticsearch.ElasticsearchSecurityException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.IndicesRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.license.XPackLicenseState; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.threadpool.ThreadPool; /** * If field level security is enabled this interceptor disables the request cache for search requests. */ public class SearchRequestInterceptor extends FieldAndDocumentLevelSecurityRequestInterceptor { public SearchRequestInterceptor(ThreadPool threadPool, XPackLicenseState licenseState) { super(threadPool.getThreadContext(), licenseState); } @Override public void disableFeatures(IndicesRequest indicesRequest, boolean fieldLevelSecurityEnabled, boolean documentLevelSecurityEnabled, ActionListener<Void> listener) { final SearchRequest request = (SearchRequest) indicesRequest; request.requestCache(false); if (documentLevelSecurityEnabled) { if (request.source() != null && request.source().suggest() != null) { listener.onFailure(new ElasticsearchSecurityException("Suggest isn't supported if document level security is enabled", RestStatus.BAD_REQUEST)); } else if (request.source() != null && request.source().profile()) { listener.onFailure(new ElasticsearchSecurityException("A search request cannot be profiled if document level security " + "is enabled", RestStatus.BAD_REQUEST)); } else { listener.onResponse(null); } } else { listener.onResponse(null); } } @Override public boolean supports(IndicesRequest request) { return request instanceof SearchRequest; } }
{ "content_hash": "a5678c13061d15b531255679c0ccd0ba", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 137, "avg_line_length": 42.80434782608695, "alnum_prop": 0.706957846622651, "repo_name": "nknize/elasticsearch", "id": "14084b963c3a14ba26f408d9370e845bcdc0c207", "size": "2210", "binary": false, "copies": "18", "ref": "refs/heads/master", "path": "x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/interceptor/SearchRequestInterceptor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "12298" }, { "name": "Batchfile", "bytes": "16353" }, { "name": "Emacs Lisp", "bytes": "3341" }, { "name": "FreeMarker", "bytes": "45" }, { "name": "Groovy", "bytes": "251795" }, { "name": "HTML", "bytes": "5348" }, { "name": "Java", "bytes": "36849935" }, { "name": "Perl", "bytes": "7116" }, { "name": "Python", "bytes": "76127" }, { "name": "Shell", "bytes": "102829" } ], "symlink_target": "" }
(function() { //Going sloppy to avoid 'use strict' string cost, but strict practices should //be followed. /*jslint sloppy: true */ /*global setTimeout: false */ var requirejs, require, define; (function (undef) { var main, req, makeMap, handlers, defined = {}, waiting = {}, config = {}, defining = {}, hasOwn = Object.prototype.hasOwnProperty, aps = [].slice; function hasProp(obj, prop) { return hasOwn.call(obj, prop); } /** * Given a relative module name, like ./something, normalize it to * a real name that can be mapped to a path. * @param {String} name the relative name * @param {String} baseName a real name that the name arg is relative * to. * @returns {String} normalized name */ function normalize(name, baseName) { var nameParts, nameSegment, mapValue, foundMap, foundI, foundStarMap, starI, i, j, part, baseParts = baseName && baseName.split("/"), map = config.map, starMap = (map && map['*']) || {}; //Adjust any relative paths. if (name && name.charAt(0) === ".") { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { //Convert baseName to array, and lop off the last part, //so that . matches that "directory" and not name of the baseName's //module. For instance, baseName of "one/two/three", maps to //"one/two/three.js", but we want the directory, "one/two" for //this normalization. baseParts = baseParts.slice(0, baseParts.length - 1); name = baseParts.concat(name.split("/")); //start trimDots for (i = 0; i < name.length; i += 1) { part = name[i]; if (part === ".") { name.splice(i, 1); i -= 1; } else if (part === "..") { if (i === 1 && (name[2] === '..' || name[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { name.splice(i - 1, 2); i -= 2; } } } //end trimDots name = name.join("/"); } else if (name.indexOf('./') === 0) { // No baseName, so this is ID is resolved relative // to baseUrl, pull off the leading dot. name = name.substring(2); } } //Apply map config if available. if ((baseParts || starMap) && map) { nameParts = name.split('/'); for (i = nameParts.length; i > 0; i -= 1) { nameSegment = nameParts.slice(0, i).join("/"); if (baseParts) { //Find the longest baseName segment match in the config. //So, do joins on the biggest to smallest lengths of baseParts. for (j = baseParts.length; j > 0; j -= 1) { mapValue = map[baseParts.slice(0, j).join('/')]; //baseName segment has config, find if it has one for //this name. if (mapValue) { mapValue = mapValue[nameSegment]; if (mapValue) { //Match, update name to the new value. foundMap = mapValue; foundI = i; break; } } } } if (foundMap) { break; } //Check for a star map match, but just hold on to it, //if there is a shorter segment match later in a matching //config, then favor over this star map. if (!foundStarMap && starMap && starMap[nameSegment]) { foundStarMap = starMap[nameSegment]; starI = i; } } if (!foundMap && foundStarMap) { foundMap = foundStarMap; foundI = starI; } if (foundMap) { nameParts.splice(0, foundI, foundMap); name = nameParts.join('/'); } } return name; } function makeRequire(relName, forceSync) { return function () { //A version of a require function that passes a moduleName //value for items that may need to //look up paths relative to the moduleName return req.apply(undef, aps.call(arguments, 0).concat([relName, forceSync])); }; } function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(depName) { return function (value) { defined[depName] = value; }; } function callDep(name) { if (hasProp(waiting, name)) { var args = waiting[name]; delete waiting[name]; defining[name] = true; main.apply(undef, args); } if (!hasProp(defined, name) && !hasProp(defining, name)) { throw new Error('No ' + name); } return defined[name]; } //Turns a plugin!resource to [plugin, resource] //with the plugin being undefined if the name //did not have a plugin prefix. function splitPrefix(name) { var prefix, index = name ? name.indexOf('!') : -1; if (index > -1) { prefix = name.substring(0, index); name = name.substring(index + 1, name.length); } return [prefix, name]; } function onResourceLoad(name, defined, deps){ if(requirejs.onResourceLoad && name){ requirejs.onResourceLoad({defined:defined}, {id:name}, deps); } } /** * Makes a name map, normalizing the name, and using a plugin * for normalization if necessary. Grabs a ref to plugin * too, as an optimization. */ makeMap = function (name, relName) { var plugin, parts = splitPrefix(name), prefix = parts[0]; name = parts[1]; if (prefix) { prefix = normalize(prefix, relName); plugin = callDep(prefix); } //Normalize according if (prefix) { if (plugin && plugin.normalize) { name = plugin.normalize(name, makeNormalize(relName)); } else { name = normalize(name, relName); } } else { name = normalize(name, relName); parts = splitPrefix(name); prefix = parts[0]; name = parts[1]; if (prefix) { plugin = callDep(prefix); } } //Using ridiculous property names for space reasons return { f: prefix ? prefix + '!' + name : name, //fullName n: name, pr: prefix, p: plugin }; }; function makeConfig(name) { return function () { return (config && config.config && config.config[name]) || {}; }; } handlers = { require: function (name) { return makeRequire(name); }, exports: function (name) { var e = defined[name]; if (typeof e !== 'undefined') { return e; } else { return (defined[name] = {}); } }, module: function (name) { return { id: name, uri: '', exports: defined[name], config: makeConfig(name) }; } }; main = function (name, deps, callback, relName) { var cjsModule, depName, ret, map, i, args = [], usingExports; //Use name if no relName relName = relName || name; //Call the callback to define the module, if necessary. if (typeof callback === 'function') { //Pull out the defined dependencies and pass the ordered //values to the callback. //Default to [require, exports, module] if no deps deps = !deps.length && callback.length ? ['require', 'exports', 'module'] : deps; for (i = 0; i < deps.length; i += 1) { map = makeMap(deps[i], relName); depName = map.f; //Fast path CommonJS standard dependencies. if (depName === "require") { args[i] = handlers.require(name); } else if (depName === "exports") { //CommonJS module spec 1.1 args[i] = handlers.exports(name); usingExports = true; } else if (depName === "module") { //CommonJS module spec 1.1 cjsModule = args[i] = handlers.module(name); } else if (hasProp(defined, depName) || hasProp(waiting, depName) || hasProp(defining, depName)) { args[i] = callDep(depName); } else if (map.p) { map.p.load(map.n, makeRequire(relName, true), makeLoad(depName), {}); args[i] = defined[depName]; } else { throw new Error(name + ' missing ' + depName); } } ret = callback.apply(defined[name], args); if (name) { //If setting exports via "module" is in play, //favor that over return value and exports. After that, //favor a non-undefined return value over exports use. if (cjsModule && cjsModule.exports !== undef && cjsModule.exports !== defined[name]) { defined[name] = cjsModule.exports; } else if (ret !== undef || !usingExports) { //Use the return value from the function. defined[name] = ret; } } } else if (name) { //May just be an object definition for the module. Only //worry about defining if have a module name. defined[name] = callback; } onResourceLoad(name, defined, args); }; requirejs = require = req = function (deps, callback, relName, forceSync, alt) { if (typeof deps === "string") { if (handlers[deps]) { //callback in this case is really relName return handlers[deps](callback); } //Just return the module wanted. In this scenario, the //deps arg is the module name, and second arg (if passed) //is just the relName. //Normalize module name, if it contains . or .. return callDep(makeMap(deps, callback).f); } else if (!deps.splice) { //deps is a config object, not an array. config = deps; if (callback.splice) { //callback is an array, which means it is a dependency list. //Adjust args if there are dependencies deps = callback; callback = relName; relName = null; } else { deps = undef; } } //Support require(['a']) callback = callback || function () {}; //If relName is a function, it is an errback handler, //so remove it. if (typeof relName === 'function') { relName = forceSync; forceSync = alt; } //Simulate async callback; if (forceSync) { main(undef, deps, callback, relName); } else { //Using a non-zero value because of concern for what old browsers //do, and latest browsers "upgrade" to 4 if lower value is used: //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout: //If want a value immediately, use require('id') instead -- something //that works in almond on the global level, but not guaranteed and //unlikely to work in other AMD implementations. setTimeout(function () { main(undef, deps, callback, relName); }, 4); } return req; }; /** * Just drops the config on the floor, but returns req in case * the config return value is used. */ req.config = function (cfg) { config = cfg; if (config.deps) { req(config.deps, config.callback); } return req; }; /** * Expose module registry for debugging and tooling */ requirejs._defined = defined; define = function (name, deps, callback) { //This module may not have dependencies if (!deps.splice) { //deps is not an array, so probably means //an object literal or factory function for //the value. Adjust args. callback = deps; deps = []; } if (!hasProp(defined, name) && !hasProp(waiting, name)) { waiting[name] = [name, deps, callback]; } }; define.amd = { jQuery: true }; }());/*! * jQuery JavaScript Library v1.9.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-2-4 */ (function( window, undefined ) { // 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 // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<9 // For `typeof node.method` instead of `node.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.9.1", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // 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 = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/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(); }, // The ready event handler completed = function( event ) { // 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(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { 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 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 rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_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 a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // 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 ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_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] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; 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; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // 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 ( length === i ) { 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({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // 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.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // 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 ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // 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 && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // 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 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 ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing 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; }, noop: function() {}, // 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; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality 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 { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_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 l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // 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 if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_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 = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_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; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function 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; }, now: function() { return ( new Date() ).getTime(); } }); 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 ); }; // 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 ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); // 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( core_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 = []; 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 ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { 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 action = tuple[ 0 ], 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[ action + "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 = core_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 ? core_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(); } }); jQuery.support = (function() { var support, all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) 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) optSelected: opt.selected, // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: document.compatMode === "CSS1Compat", // Will be defined later deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // 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: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // 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"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.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() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // 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>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_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.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // 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 ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // 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)) && getByName && data === undefined ) { 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 ) { elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].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 ( getByName ) { // 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 i, l, thisCache, 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 ) ); } for ( i = 0, l = name.length; i < l; 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 : 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) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, 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 ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( !name.indexOf( "data-" ) ) { 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 jQuery.access( this, function( value ) { if ( value === undefined ) { // Try to fetch any internally stored data first return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; } this.each(function() { jQuery.data( this, key, value ); }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); 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; } 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--; } hooks.cur = fn; 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 ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ 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 ); }; }); }, 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 nodeHook, boolHook, rclass = /[\t\r\n]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.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 ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, 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( core_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 + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, 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( core_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 + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; 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 ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_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; }, val: function( value ) { var ret, hooks, 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, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.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 ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, 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 ( jQuery.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 values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, notxml, 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 === core_strundefined ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945) // Support: IE9+ if ( typeof elem.getAttribute !== core_strundefined ) { ret = elem.getAttribute( 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( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( rboolean.test( name ) ) { // Set corresponding property to false for boolean attributes // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 if ( !getSetAttribute && ruseDefault.test( name ) ) { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } else { 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 ( !jQuery.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; } } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, 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 ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return 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/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { var // Use .prop to determine if this attribute is understood as boolean prop = jQuery.prop( elem, name ), // Fetch it accordingly attr = typeof prop === "boolean" && elem.getAttribute( name ), detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ? attr != null : // oldIE fabricates an empty string for missing boolean attributes // and conflates checked/selected into attroperties ruseDefault.test( name ) ? elem[ jQuery.camelCase( "default-" + name ) ] : !!attr : // fetch an attribute node for properties not recognized as boolean elem.getAttributeNode( name ); return detail && detail.value !== false ? name.toLowerCase() : undefined; }, 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; } }; // fix oldIE value attroperty if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return jQuery.nodeName( elem, "input" ) ? // Ignore the value *property* by using defaultValue elem.defaultValue : ret && ret.specified ? ret.value : undefined; }, 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 = jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, 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) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, 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 ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret == null ? undefined : ret; } }); }); // 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 ); } }; }); } if ( !jQuery.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 + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( 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; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } /* * 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 !== core_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 // jQuery(...).bind("mouseover mouseout", fn); types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // 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( core_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 = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_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 ); event.isTrigger = true; 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 && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === 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( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && 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 = core_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") ) { for ( ; cur != this; cur = cur.parentNode || this ) { // 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 }, 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; } } }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== document.activeElement && 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 === document.activeElement && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { 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 ] === core_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.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? 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() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, 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 ( !jQuery.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 ( !jQuery.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 ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } 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 ); }); }, 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 ); }, 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 ); } } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var i, cachedruns, Expr, getText, isXML, compile, hasDuplicate, outermostContext, // Local document vars setDocument, document, docElem, documentIsXML, rbuggyQSA, rbuggyMatches, matches, contains, sortOrder, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // 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#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + 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" ), // 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" ) }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /^[^{]+\{\s*\[native code/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Use a stripped-down slice if we can't use a native one try { slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; while ( (elem = this[i++]) ) { results.push( elem ); } return results; }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * 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 cache, keys = []; return (cache = function( 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); }); } /** * 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 { // release memory in IE div = null; } } 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 || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( !documentIsXML && !seed ) { // Shortcuts if ( (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 #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, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } // QSA path if ( support.qsa && !rbuggyQSA.test(selector) ) { old = true; nid = expando; newContext = context; newSelector = nodeType === 9 && 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 ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Detect xml * @param {Element|Object} elem An element or a document */ 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 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; // Support tests documentIsXML = isXML( doc ); // Check if getElementsByTagName("*") returns only elements support.tagNameNoComments = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getByClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID support.getByName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName( expando + 0 ).length; support.getIdNotName = !doc.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // IE6/7 return modified attributes Expr.attrHandle = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; // ID find and filter if ( support.getIdNotName ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { 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 { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.tagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, 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; }; // Name Expr.find["NAME"] = support.getByName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; // Class Expr.find["CLASS"] = support.getByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { return context.getElementsByClassName( className ); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ]; if ( (support.qsa = isNative(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 explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // 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"); } }); assert(function( div ) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if ( div.querySelectorAll("[i^='']").length ) { rbuggyQSA.push( "[*^$]=" + 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 = isNative( (matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || 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 = new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? 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; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { var compare; if ( a === b ) { hasDuplicate = true; return 0; } if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { if ( a === doc || contains( preferredDoc, a ) ) { return -1; } if ( b === doc || contains( preferredDoc, b ) ) { return 1; } return 0; } return compare & 4 ? -1 : 1; } return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 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; }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). hasDuplicate = false; [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; return document; }; 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']" ); // rbuggyQSA always contains :focus, so no need for an existence check if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !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 ) { var val; // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( !documentIsXML ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( documentIsXML || support.attributes ) { return elem.getAttribute( name ); } return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; function siblingCheck( a, b ) { var cur = b && a, diff = cur && ( ~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 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 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 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]); } } }); }); } /** * 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 for ( ; (node = elem[i]); 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 (see #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, 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[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[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[4] ) { match[2] = match[4]; // 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( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); return 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( elem.className || (typeof elem.getAttribute !== strundefined && 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 + " " ).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.call( 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 ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { 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 identifider if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsXML ? elem.getAttribute("xml:lang") || elem.getAttribute("lang") : elem.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 only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { 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; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // 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; }) } }; // 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 ); } function tokenize( 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 data, cache, outerCache, dirkey = 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 ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { 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 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.call( 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.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; 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( tokens.slice( 0, i - 1 ) ).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 ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (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; cachedruns = ++matcherCachedRuns; } } // 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, group /* 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 ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is 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" && context.nodeType === 9 && !documentIsXML && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; if ( !context ) { return results; } 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 ) && 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, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, documentIsXML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Initialize with the default document setDocument(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; 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; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret, self, len = this.length; if ( typeof selector !== "string" ) { self = this; return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } ret = []; for ( i = 0; i < len; i++ ) { jQuery.find( selector, this[ 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; return ret; }, 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; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true) ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // 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". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // 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 ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; 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 ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, 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; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } 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, manipulation_rcheckableType = /^(?:checkbox|radio)$/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: jQuery.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; jQuery.fn.extend({ text: function( value ) { return jQuery.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 ); }, 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(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { 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 jQuery.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 ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.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( value ) { var isFunc = jQuery.isFunction( value ); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( !isFunc && typeof value !== "string" ) { value = jQuery( value ).not( this ).detach(); } return this.domManip( [ value ], true, function( elem ) { var next = this.nextSibling, parent = this.parentNode; if ( parent ) { jQuery( this ).remove(); parent.insertBefore( elem, next ); } }); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = core_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" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, table ? self.html() : undefined ); } self.domManip( args, table, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); 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( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : 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 ) { // Hope ajax is available... jQuery.ajax({ url: node.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { var attr = elem.getAttributeNode("type"); elem.type = ( attr && attr.specified ) + "/" + 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 ( !jQuery.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 ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_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.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() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_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 ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.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 ( (!jQuery.support.noCloneEvent || !jQuery.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 ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.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 ( !jQuery.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 = jQuery.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 !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // 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]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], 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 isHidden( 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 ); } 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", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { 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; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, 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 ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); 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; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": 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": jQuery.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 NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( 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 ( !jQuery.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 ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #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; }, // A method for quickly swapping in/out CSS properties to get correct calculations 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; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; 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; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // 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; } } return ret === "" ? "auto" : ret; }; } 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 = jQuery.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 && ( jQuery.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"; } // Try to determine the default display value of an element function css_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'/>") .css( "cssText", "display:block !important" ) ).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; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } 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 elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? 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, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.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; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: 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" ] ); } } }; } // 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 if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: 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; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { 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 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // 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; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; 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 || !manipulation_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(); } }); //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, "+" ); }; 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 ); } } 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.hover = function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }; var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, 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+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* 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( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[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; } 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 = 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.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.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" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": window.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( core_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 fireGlobals = 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 += ( ajax_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_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_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; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // 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 ) { isSuccess = true; statusText = "nocontent"; // if not modified } else if ( status === 304 ) { isSuccess = true; statusText = "notmodified"; // If we have data, let's convert it } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.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; }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); } }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - 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, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // 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 function ajaxConvert( s, response ) { var conv2, current, conv, tmp, converters = {}, i = 0, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ]; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current 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.splice( i--, 0, current ); } 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 }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } // 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 + "_" + ( ajax_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 += ( ajax_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"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( 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 ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.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 ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#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 && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.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 { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 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 ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } 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; } } createTweens( animation, props ); 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 ); } function propFilter( props, specialEasing ) { var value, name, index, easing, 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; } } } 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 ); } } }); function defaultPrefilter( elem, props, opts ) { /*jshint validthis:true */ var prop, index, length, value, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // 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 if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // 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 ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } 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; } } } }; // Remove in 2.0 - this supports IE8's 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.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 ); }; }); 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 ); doAnimation.finish = function() { anim.stop( true ); }; // 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.cur && hooks.cur.finish ) { hooks.cur.finish.call( this ); } // 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; }); } }); // 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; } // 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.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.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; 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 ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; 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 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.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 !== core_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 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // 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({ 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 it's 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 || document.documentElement; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.documentElement; }); } }); // 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 jQuery.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 ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // 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 jQuery.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 ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // })(); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use 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. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window ); /** * Durandal 2.0.1 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. * Available via the MIT license. * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. */ /** * The system module encapsulates the most basic features used by other modules. * @module system * @requires require * @requires jquery */ define('durandal/system',['require', 'jquery'], function(require, $) { var isDebugging = false, nativeKeys = Object.keys, hasOwnProperty = Object.prototype.hasOwnProperty, toString = Object.prototype.toString, system, treatAsIE8 = false, nativeIsArray = Array.isArray, slice = Array.prototype.slice; //see http://patik.com/blog/complete-cross-browser-console-log/ // Tell IE9 to use its built-in console if (Function.prototype.bind && (typeof console === 'object' || typeof console === 'function') && typeof console.log == 'object') { try { ['log', 'info', 'warn', 'error', 'assert', 'dir', 'clear', 'profile', 'profileEnd'] .forEach(function(method) { console[method] = this.call(console[method], console); }, Function.prototype.bind); } catch (ex) { treatAsIE8 = true; } } // callback for dojo's loader // note: if you wish to use Durandal with dojo's AMD loader, // currently you must fork the dojo source with the following // dojo/dojo.js, line 1187, the last line of the finishExec() function: // (add) signal("moduleLoaded", [module.result, module.mid]); // an enhancement request has been submitted to dojo to make this // a permanent change. To view the status of this request, visit: // http://bugs.dojotoolkit.org/ticket/16727 if (require.on) { require.on("moduleLoaded", function(module, mid) { system.setModuleId(module, mid); }); } // callback for require.js loader if (typeof requirejs !== 'undefined') { requirejs.onResourceLoad = function(context, map, depArray) { system.setModuleId(context.defined[map.id], map.id); }; } var noop = function() { }; var log = function() { try { // Modern browsers if (typeof console != 'undefined' && typeof console.log == 'function') { // Opera 11 if (window.opera) { var i = 0; while (i < arguments.length) { console.log('Item ' + (i + 1) + ': ' + arguments[i]); i++; } } // All other modern browsers else if ((slice.call(arguments)).length == 1 && typeof slice.call(arguments)[0] == 'string') { console.log((slice.call(arguments)).toString()); } else { console.log.apply(console, slice.call(arguments)); } } // IE8 else if ((!Function.prototype.bind || treatAsIE8) && typeof console != 'undefined' && typeof console.log == 'object') { Function.prototype.call.call(console.log, console, slice.call(arguments)); } // IE7 and lower, and other old browsers } catch (ignore) { } }; var logError = function(error) { if(error instanceof Error){ throw error; } throw new Error(error); }; /** * @class SystemModule * @static */ system = { /** * Durandal's version. * @property {string} version */ version: "2.0.1", /** * A noop function. * @method noop */ noop: noop, /** * Gets the module id for the specified object. * @method getModuleId * @param {object} obj The object whose module id you wish to determine. * @return {string} The module id. */ getModuleId: function(obj) { if (!obj) { return null; } if (typeof obj == 'function') { return obj.prototype.__moduleId__; } if (typeof obj == 'string') { return null; } return obj.__moduleId__; }, /** * Sets the module id for the specified object. * @method setModuleId * @param {object} obj The object whose module id you wish to set. * @param {string} id The id to set for the specified object. */ setModuleId: function(obj, id) { if (!obj) { return; } if (typeof obj == 'function') { obj.prototype.__moduleId__ = id; return; } if (typeof obj == 'string') { return; } obj.__moduleId__ = id; }, /** * Resolves the default object instance for a module. If the module is an object, the module is returned. If the module is a function, that function is called with `new` and it's result is returned. * @method resolveObject * @param {object} module The module to use to get/create the default object for. * @return {object} The default object for the module. */ resolveObject: function(module) { if (system.isFunction(module)) { return new module(); } else { return module; } }, /** * Gets/Sets whether or not Durandal is in debug mode. * @method debug * @param {boolean} [enable] Turns on/off debugging. * @return {boolean} Whether or not Durandal is current debugging. */ debug: function(enable) { if (arguments.length == 1) { isDebugging = enable; if (isDebugging) { this.log = log; this.error = logError; this.log('Debug:Enabled'); } else { this.log('Debug:Disabled'); this.log = noop; this.error = noop; } } return isDebugging; }, /** * Logs data to the console. Pass any number of parameters to be logged. Log output is not processed if the framework is not running in debug mode. * @method log * @param {object} info* The objects to log. */ log: noop, /** * Logs an error. * @method error * @param {string|Error} obj The error to report. */ error: noop, /** * Asserts a condition by throwing an error if the condition fails. * @method assert * @param {boolean} condition The condition to check. * @param {string} message The message to report in the error if the condition check fails. */ assert: function (condition, message) { if (!condition) { system.error(new Error(message || 'Assert:Failed')); } }, /** * Creates a deferred object which can be used to create a promise. Optionally pass a function action to perform which will be passed an object used in resolving the promise. * @method defer * @param {function} [action] The action to defer. You will be passed the deferred object as a paramter. * @return {Deferred} The deferred object. */ defer: function(action) { return $.Deferred(action); }, /** * Creates a simple V4 UUID. This should not be used as a PK in your database. It can be used to generate internal, unique ids. For a more robust solution see [node-uuid](https://github.com/broofa/node-uuid). * @method guid * @return {string} The guid. */ guid: function() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }, /** * Uses require.js to obtain a module. This function returns a promise which resolves with the module instance. You can pass more than one module id to this function or an array of ids. If more than one or an array is passed, then the promise will resolve with an array of module instances. * @method acquire * @param {string|string[]} moduleId The id(s) of the modules to load. * @return {Promise} A promise for the loaded module(s). */ acquire: function() { var modules, first = arguments[0], arrayRequest = false; if(system.isArray(first)){ modules = first; arrayRequest = true; }else{ modules = slice.call(arguments, 0); } return this.defer(function(dfd) { require(modules, function() { var args = arguments; setTimeout(function() { if(args.length > 1 || arrayRequest){ dfd.resolve(slice.call(args, 0)); }else{ dfd.resolve(args[0]); } }, 1); }, function(err){ dfd.reject(err); }); }).promise(); }, /** * Extends the first object with the properties of the following objects. * @method extend * @param {object} obj The target object to extend. * @param {object} extension* Uses to extend the target object. */ extend: function(obj) { var rest = slice.call(arguments, 1); for (var i = 0; i < rest.length; i++) { var source = rest[i]; if (source) { for (var prop in source) { obj[prop] = source[prop]; } } } return obj; }, /** * Uses a setTimeout to wait the specified milliseconds. * @method wait * @param {number} milliseconds The number of milliseconds to wait. * @return {Promise} */ wait: function(milliseconds) { return system.defer(function(dfd) { setTimeout(dfd.resolve, milliseconds); }).promise(); } }; /** * Gets all the owned keys of the specified object. * @method keys * @param {object} object The object whose owned keys should be returned. * @return {string[]} The keys. */ system.keys = nativeKeys || function(obj) { if (obj !== Object(obj)) { throw new TypeError('Invalid object'); } var keys = []; for (var key in obj) { if (hasOwnProperty.call(obj, key)) { keys[keys.length] = key; } } return keys; }; /** * Determines if the specified object is an html element. * @method isElement * @param {object} object The object to check. * @return {boolean} True if matches the type, false otherwise. */ system.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; /** * Determines if the specified object is an array. * @method isArray * @param {object} object The object to check. * @return {boolean} True if matches the type, false otherwise. */ system.isArray = nativeIsArray || function(obj) { return toString.call(obj) == '[object Array]'; }; /** * Determines if the specified object is...an object. ie. Not an array, string, etc. * @method isObject * @param {object} object The object to check. * @return {boolean} True if matches the type, false otherwise. */ system.isObject = function(obj) { return obj === Object(obj); }; /** * Determines if the specified object is a boolean. * @method isBoolean * @param {object} object The object to check. * @return {boolean} True if matches the type, false otherwise. */ system.isBoolean = function(obj) { return typeof(obj) === "boolean"; }; /** * Determines if the specified object is a promise. * @method isPromise * @param {object} object The object to check. * @return {boolean} True if matches the type, false otherwise. */ system.isPromise = function(obj) { return obj && system.isFunction(obj.then); }; /** * Determines if the specified object is a function arguments object. * @method isArguments * @param {object} object The object to check. * @return {boolean} True if matches the type, false otherwise. */ /** * Determines if the specified object is a function. * @method isFunction * @param {object} object The object to check. * @return {boolean} True if matches the type, false otherwise. */ /** * Determines if the specified object is a string. * @method isString * @param {object} object The object to check. * @return {boolean} True if matches the type, false otherwise. */ /** * Determines if the specified object is a number. * @method isNumber * @param {object} object The object to check. * @return {boolean} True if matches the type, false otherwise. */ /** * Determines if the specified object is a date. * @method isDate * @param {object} object The object to check. * @return {boolean} True if matches the type, false otherwise. */ /** * Determines if the specified object is a boolean. * @method isBoolean * @param {object} object The object to check. * @return {boolean} True if matches the type, false otherwise. */ //isArguments, isFunction, isString, isNumber, isDate, isRegExp. var isChecks = ['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp']; function makeIsFunction(name) { var value = '[object ' + name + ']'; system['is' + name] = function(obj) { return toString.call(obj) == value; }; } for (var i = 0; i < isChecks.length; i++) { makeIsFunction(isChecks[i]); } return system; }); /** * Durandal 2.0.1 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. * Available via the MIT license. * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. */ /** * The viewEngine module provides information to the viewLocator module which is used to locate the view's source file. The viewEngine also transforms a view id into a view instance. * @module viewEngine * @requires system * @requires jquery */ define('durandal/viewEngine',['durandal/system', 'jquery'], function (system, $) { var parseMarkup; if ($.parseHTML) { parseMarkup = function (html) { return $.parseHTML(html); }; } else { parseMarkup = function (html) { return $(html).get(); }; } /** * @class ViewEngineModule * @static */ return { /** * The file extension that view source files are expected to have. * @property {string} viewExtension * @default .html */ viewExtension: '.html', /** * The name of the RequireJS loader plugin used by the viewLocator to obtain the view source. (Use requirejs to map the plugin's full path). * @property {string} viewPlugin * @default text */ viewPlugin: 'text', /** * Determines if the url is a url for a view, according to the view engine. * @method isViewUrl * @param {string} url The potential view url. * @return {boolean} True if the url is a view url, false otherwise. */ isViewUrl: function (url) { return url.indexOf(this.viewExtension, url.length - this.viewExtension.length) !== -1; }, /** * Converts a view url into a view id. * @method convertViewUrlToViewId * @param {string} url The url to convert. * @return {string} The view id. */ convertViewUrlToViewId: function (url) { return url.substring(0, url.length - this.viewExtension.length); }, /** * Converts a view id into a full RequireJS path. * @method convertViewIdToRequirePath * @param {string} viewId The view id to convert. * @return {string} The require path. */ convertViewIdToRequirePath: function (viewId) { return this.viewPlugin + '!' + viewId + this.viewExtension; }, /** * Parses the view engine recognized markup and returns DOM elements. * @method parseMarkup * @param {string} markup The markup to parse. * @return {DOMElement[]} The elements. */ parseMarkup: parseMarkup, /** * Calls `parseMarkup` and then pipes the results through `ensureSingleElement`. * @method processMarkup * @param {string} markup The markup to process. * @return {DOMElement} The view. */ processMarkup: function (markup) { var allElements = this.parseMarkup(markup); return this.ensureSingleElement(allElements); }, /** * Converts an array of elements into a single element. White space and comments are removed. If a single element does not remain, then the elements are wrapped. * @method ensureSingleElement * @param {DOMElement[]} allElements The elements. * @return {DOMElement} A single element. */ ensureSingleElement:function(allElements){ if (allElements.length == 1) { return allElements[0]; } var withoutCommentsOrEmptyText = []; for (var i = 0; i < allElements.length; i++) { var current = allElements[i]; if (current.nodeType != 8) { if (current.nodeType == 3) { var result = /\S/.test(current.nodeValue); if (!result) { continue; } } withoutCommentsOrEmptyText.push(current); } } if (withoutCommentsOrEmptyText.length > 1) { return $(withoutCommentsOrEmptyText).wrapAll('<div class="durandal-wrapper"></div>').parent().get(0); } return withoutCommentsOrEmptyText[0]; }, /** * Creates the view associated with the view id. * @method createView * @param {string} viewId The view id whose view should be created. * @return {Promise} A promise of the view. */ createView: function(viewId) { var that = this; var requirePath = this.convertViewIdToRequirePath(viewId); return system.defer(function(dfd) { system.acquire(requirePath).then(function(markup) { var element = that.processMarkup(markup); element.setAttribute('data-view', viewId); dfd.resolve(element); }).fail(function(err){ that.createFallbackView(viewId, requirePath, err).then(function(element){ element.setAttribute('data-view', viewId); dfd.resolve(element); }); }); }).promise(); }, /** * Called when a view cannot be found to provide the opportunity to locate or generate a fallback view. Mainly used to ease development. * @method createFallbackView * @param {string} viewId The view id whose view should be created. * @param {string} requirePath The require path that was attempted. * @param {Error} requirePath The error that was returned from the attempt to locate the default view. * @return {Promise} A promise for the fallback view. */ createFallbackView: function (viewId, requirePath, err) { var that = this, message = 'View Not Found. Searched for "' + viewId + '" via path "' + requirePath + '".'; return system.defer(function(dfd) { dfd.resolve(that.processMarkup('<div class="durandal-view-404">' + message + '</div>')); }).promise(); } }; }); /** * Durandal 2.0.1 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. * Available via the MIT license. * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. */ /** * The viewLocator module collaborates with the viewEngine module to provide views (literally dom sub-trees) to other parts of the framework as needed. The primary consumer of the viewLocator is the composition module. * @module viewLocator * @requires system * @requires viewEngine */ define('durandal/viewLocator',['durandal/system', 'durandal/viewEngine'], function (system, viewEngine) { function findInElements(nodes, url) { for (var i = 0; i < nodes.length; i++) { var current = nodes[i]; var existingUrl = current.getAttribute('data-view'); if (existingUrl == url) { return current; } } } function escape(str) { return (str + '').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1"); } /** * @class ViewLocatorModule * @static */ return { /** * Allows you to set up a convention for mapping module folders to view folders. It is a convenience method that customizes `convertModuleIdToViewId` and `translateViewIdToArea` under the covers. * @method useConvention * @param {string} [modulesPath] A string to match in the path and replace with the viewsPath. If not specified, the match is 'viewmodels'. * @param {string} [viewsPath] The replacement for the modulesPath. If not specified, the replacement is 'views'. * @param {string} [areasPath] Partial views are mapped to the "views" folder if not specified. Use this parameter to change their location. */ useConvention: function(modulesPath, viewsPath, areasPath) { modulesPath = modulesPath || 'viewmodels'; viewsPath = viewsPath || 'views'; areasPath = areasPath || viewsPath; var reg = new RegExp(escape(modulesPath), 'gi'); this.convertModuleIdToViewId = function (moduleId) { return moduleId.replace(reg, viewsPath); }; this.translateViewIdToArea = function (viewId, area) { if (!area || area == 'partial') { return areasPath + '/' + viewId; } return areasPath + '/' + area + '/' + viewId; }; }, /** * Maps an object instance to a view instance. * @method locateViewForObject * @param {object} obj The object to locate the view for. * @param {string} [area] The area to translate the view to. * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first. * @return {Promise} A promise of the view. */ locateViewForObject: function(obj, area, elementsToSearch) { var view; if (obj.getView) { view = obj.getView(); if (view) { return this.locateView(view, area, elementsToSearch); } } if (obj.viewUrl) { return this.locateView(obj.viewUrl, area, elementsToSearch); } var id = system.getModuleId(obj); if (id) { return this.locateView(this.convertModuleIdToViewId(id), area, elementsToSearch); } return this.locateView(this.determineFallbackViewId(obj), area, elementsToSearch); }, /** * Converts a module id into a view id. By default the ids are the same. * @method convertModuleIdToViewId * @param {string} moduleId The module id. * @return {string} The view id. */ convertModuleIdToViewId: function(moduleId) { return moduleId; }, /** * If no view id can be determined, this function is called to genreate one. By default it attempts to determine the object's type and use that. * @method determineFallbackViewId * @param {object} obj The object to determine the fallback id for. * @return {string} The view id. */ determineFallbackViewId: function (obj) { var funcNameRegex = /function (.{1,})\(/; var results = (funcNameRegex).exec((obj).constructor.toString()); var typeName = (results && results.length > 1) ? results[1] : ""; return 'views/' + typeName; }, /** * Takes a view id and translates it into a particular area. By default, no translation occurs. * @method translateViewIdToArea * @param {string} viewId The view id. * @param {string} area The area to translate the view to. * @return {string} The translated view id. */ translateViewIdToArea: function (viewId, area) { return viewId; }, /** * Locates the specified view. * @method locateView * @param {string|DOMElement} viewOrUrlOrId A view, view url or view id to locate. * @param {string} [area] The area to translate the view to. * @param {DOMElement[]} [elementsToSearch] An existing set of elements to search first. * @return {Promise} A promise of the view. */ locateView: function(viewOrUrlOrId, area, elementsToSearch) { if (typeof viewOrUrlOrId === 'string') { var viewId; if (viewEngine.isViewUrl(viewOrUrlOrId)) { viewId = viewEngine.convertViewUrlToViewId(viewOrUrlOrId); } else { viewId = viewOrUrlOrId; } if (area) { viewId = this.translateViewIdToArea(viewId, area); } if (elementsToSearch) { var existing = findInElements(elementsToSearch, viewId); if (existing) { return system.defer(function(dfd) { dfd.resolve(existing); }).promise(); } } return viewEngine.createView(viewId); } return system.defer(function(dfd) { dfd.resolve(viewOrUrlOrId); }).promise(); } }; }); // Knockout JavaScript library v2.3.0 // (c) Steven Sanderson - http://knockoutjs.com/ // License: MIT (http://www.opensource.org/licenses/mit-license.php) (function() {function F(q){return function(){return q}};(function(q){var w=this||(0,eval)("this"),s=w.document,H=w.navigator,t=w.jQuery,y=w.JSON;(function(q){"function"===typeof require&&"object"===typeof exports&&"object"===typeof module?q(module.exports||exports):"function"===typeof define&&define.amd?define('knockout',["exports"],q):q(w.ko={})})(function(C){function G(b,c,d,f){a.d[b]={init:function(b){a.a.f.set(b,I,{});return{controlsDescendantBindings:!0}},update:function(b,e,m,h,k){m=a.a.f.get(b,I);e=a.a.c(e());h=!d!==!e;var l=!m.fb;if(l||c||h!==m.vb)l&&(m.fb= a.a.Oa(a.e.childNodes(b),!0)),h?(l||a.e.P(b,a.a.Oa(m.fb)),a.Ja(f?f(k,e):k,b)):a.e.ba(b),m.vb=h}};a.g.S[b]=!1;a.e.L[b]=!0}function J(b,c,d){d&&c!==a.h.n(b)&&a.h.W(b,c);c!==a.h.n(b)&&a.q.I(a.a.Ga,null,[b,"change"])}var a="undefined"!==typeof C?C:{};a.b=function(b,c){for(var d=b.split("."),f=a,g=0;g<d.length-1;g++)f=f[d[g]];f[d[d.length-1]]=c};a.r=function(a,c,d){a[c]=d};a.version="2.3.0";a.b("version",a.version);a.a=function(){function b(a,b){for(var e in a)a.hasOwnProperty(e)&&b(e,a[e])}function c(b, e){if("input"!==a.a.u(b)||!b.type||"click"!=e.toLowerCase())return!1;var k=b.type;return"checkbox"==k||"radio"==k}var d={},f={};d[H&&/Firefox\/2/i.test(H.userAgent)?"KeyboardEvent":"UIEvents"]=["keyup","keydown","keypress"];d.MouseEvents="click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave".split(" ");b(d,function(a,b){if(b.length)for(var e=0,c=b.length;e<c;e++)f[b[e]]=a});var g={propertychange:!0},e=s&&function(){for(var a=3,b=s.createElement("div"),e=b.getElementsByTagName("i");b.innerHTML= "\x3c!--[if gt IE "+ ++a+"]><i></i><![endif]--\x3e",e[0];);return 4<a?a:q}();return{Ta:["authenticity_token",/^__RequestVerificationToken(_.*)?$/],p:function(a,b){for(var e=0,c=a.length;e<c;e++)b(a[e])},k:function(a,b){if("function"==typeof Array.prototype.indexOf)return Array.prototype.indexOf.call(a,b);for(var e=0,c=a.length;e<c;e++)if(a[e]===b)return e;return-1},La:function(a,b,e){for(var c=0,d=a.length;c<d;c++)if(b.call(e,a[c]))return a[c];return null},ka:function(b,e){var c=a.a.k(b,e);0<=c&& b.splice(c,1)},Ma:function(b){b=b||[];for(var e=[],c=0,d=b.length;c<d;c++)0>a.a.k(e,b[c])&&e.push(b[c]);return e},Z:function(a,b){a=a||[];for(var e=[],c=0,d=a.length;c<d;c++)e.push(b(a[c]));return e},Y:function(a,b){a=a||[];for(var e=[],c=0,d=a.length;c<d;c++)b(a[c])&&e.push(a[c]);return e},R:function(a,b){if(b instanceof Array)a.push.apply(a,b);else for(var e=0,c=b.length;e<c;e++)a.push(b[e]);return a},ja:function(b,e,c){var d=b.indexOf?b.indexOf(e):a.a.k(b,e);0>d?c&&b.push(e):c||b.splice(d,1)}, extend:function(a,b){if(b)for(var e in b)b.hasOwnProperty(e)&&(a[e]=b[e]);return a},w:b,oa:function(b){for(;b.firstChild;)a.removeNode(b.firstChild)},Mb:function(b){b=a.a.N(b);for(var e=s.createElement("div"),c=0,d=b.length;c<d;c++)e.appendChild(a.H(b[c]));return e},Oa:function(b,e){for(var c=0,d=b.length,g=[];c<d;c++){var f=b[c].cloneNode(!0);g.push(e?a.H(f):f)}return g},P:function(b,e){a.a.oa(b);if(e)for(var c=0,d=e.length;c<d;c++)b.appendChild(e[c])},eb:function(b,e){var c=b.nodeType?[b]:b;if(0< c.length){for(var d=c[0],g=d.parentNode,f=0,r=e.length;f<r;f++)g.insertBefore(e[f],d);f=0;for(r=c.length;f<r;f++)a.removeNode(c[f])}},hb:function(a,b){7>e?a.setAttribute("selected",b):a.selected=b},F:function(a){return null===a||a===q?"":a.trim?a.trim():a.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")},Wb:function(b,e){for(var c=[],d=(b||"").split(e),g=0,f=d.length;g<f;g++){var r=a.a.F(d[g]);""!==r&&c.push(r)}return c},Tb:function(a,b){a=a||"";return b.length>a.length?!1:a.substring(0,b.length)=== b},yb:function(a,b){if(b.compareDocumentPosition)return 16==(b.compareDocumentPosition(a)&16);for(;null!=a;){if(a==b)return!0;a=a.parentNode}return!1},aa:function(b){return a.a.yb(b,b.ownerDocument)},pb:function(b){return!!a.a.La(b,a.a.aa)},u:function(a){return a&&a.tagName&&a.tagName.toLowerCase()},o:function(b,d,k){var f=e&&g[d];if(f||"undefined"==typeof t)if(f||"function"!=typeof b.addEventListener)if("undefined"!=typeof b.attachEvent){var n=function(a){k.call(b,a)},p="on"+d;b.attachEvent(p,n); a.a.C.ia(b,function(){b.detachEvent(p,n)})}else throw Error("Browser doesn't support addEventListener or attachEvent");else b.addEventListener(d,k,!1);else{if(c(b,d)){var r=k;k=function(a,b){var e=this.checked;b&&(this.checked=!0!==b.sb);r.call(this,a);this.checked=e}}t(b).bind(d,k)}},Ga:function(a,b){if(!a||!a.nodeType)throw Error("element must be a DOM node when calling triggerEvent");if("undefined"!=typeof t){var e=[];c(a,b)&&e.push({sb:a.checked});t(a).trigger(b,e)}else if("function"==typeof s.createEvent)if("function"== typeof a.dispatchEvent)e=s.createEvent(f[b]||"HTMLEvents"),e.initEvent(b,!0,!0,w,0,0,0,0,0,!1,!1,!1,!1,0,a),a.dispatchEvent(e);else throw Error("The supplied element doesn't support dispatchEvent");else if("undefined"!=typeof a.fireEvent)c(a,b)&&(a.checked=!0!==a.checked),a.fireEvent("on"+b);else throw Error("Browser doesn't support triggering events");},c:function(b){return a.T(b)?b():b},ya:function(b){return a.T(b)?b.t():b},ga:function(b,e,c){if(e){var d=/\S+/g,g=b.className.match(d)||[];a.a.p(e.match(d), function(b){a.a.ja(g,b,c)});b.className=g.join(" ")}},ib:function(b,e){var c=a.a.c(e);if(null===c||c===q)c="";var d=a.e.firstChild(b);!d||3!=d.nodeType||a.e.nextSibling(d)?a.e.P(b,[s.createTextNode(c)]):d.data=c;a.a.Bb(b)},gb:function(a,b){a.name=b;if(7>=e)try{a.mergeAttributes(s.createElement("<input name='"+a.name+"'/>"),!1)}catch(c){}},Bb:function(a){9<=e&&(a=1==a.nodeType?a:a.parentNode,a.style&&(a.style.zoom=a.style.zoom))},zb:function(a){if(e){var b=a.style.width;a.style.width=0;a.style.width= b}},Qb:function(b,e){b=a.a.c(b);e=a.a.c(e);for(var c=[],d=b;d<=e;d++)c.push(d);return c},N:function(a){for(var b=[],e=0,c=a.length;e<c;e++)b.push(a[e]);return b},Ub:6===e,Vb:7===e,ca:e,Ua:function(b,e){for(var c=a.a.N(b.getElementsByTagName("input")).concat(a.a.N(b.getElementsByTagName("textarea"))),d="string"==typeof e?function(a){return a.name===e}:function(a){return e.test(a.name)},g=[],f=c.length-1;0<=f;f--)d(c[f])&&g.push(c[f]);return g},Nb:function(b){return"string"==typeof b&&(b=a.a.F(b))? y&&y.parse?y.parse(b):(new Function("return "+b))():null},Ca:function(b,e,c){if(!y||!y.stringify)throw Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");return y.stringify(a.a.c(b),e,c)},Ob:function(e,c,d){d=d||{};var g=d.params||{},f=d.includeFields||this.Ta,p=e;if("object"==typeof e&&"form"===a.a.u(e))for(var p=e.action,r=f.length-1;0<=r;r--)for(var z= a.a.Ua(e,f[r]),D=z.length-1;0<=D;D--)g[z[D].name]=z[D].value;c=a.a.c(c);var q=s.createElement("form");q.style.display="none";q.action=p;q.method="post";for(var v in c)e=s.createElement("input"),e.name=v,e.value=a.a.Ca(a.a.c(c[v])),q.appendChild(e);b(g,function(a,b){var e=s.createElement("input");e.name=a;e.value=b;q.appendChild(e)});s.body.appendChild(q);d.submitter?d.submitter(q):q.submit();setTimeout(function(){q.parentNode.removeChild(q)},0)}}}();a.b("utils",a.a);a.b("utils.arrayForEach",a.a.p); a.b("utils.arrayFirst",a.a.La);a.b("utils.arrayFilter",a.a.Y);a.b("utils.arrayGetDistinctValues",a.a.Ma);a.b("utils.arrayIndexOf",a.a.k);a.b("utils.arrayMap",a.a.Z);a.b("utils.arrayPushAll",a.a.R);a.b("utils.arrayRemoveItem",a.a.ka);a.b("utils.extend",a.a.extend);a.b("utils.fieldsIncludedWithJsonPost",a.a.Ta);a.b("utils.getFormFields",a.a.Ua);a.b("utils.peekObservable",a.a.ya);a.b("utils.postJson",a.a.Ob);a.b("utils.parseJson",a.a.Nb);a.b("utils.registerEventHandler",a.a.o);a.b("utils.stringifyJson", a.a.Ca);a.b("utils.range",a.a.Qb);a.b("utils.toggleDomNodeCssClass",a.a.ga);a.b("utils.triggerEvent",a.a.Ga);a.b("utils.unwrapObservable",a.a.c);a.b("utils.objectForEach",a.a.w);a.b("utils.addOrRemoveItem",a.a.ja);a.b("unwrap",a.a.c);Function.prototype.bind||(Function.prototype.bind=function(a){var c=this,d=Array.prototype.slice.call(arguments);a=d.shift();return function(){return c.apply(a,d.concat(Array.prototype.slice.call(arguments)))}});a.a.f=new function(){var b=0,c="__ko__"+(new Date).getTime(), d={};return{get:function(b,c){var e=a.a.f.pa(b,!1);return e===q?q:e[c]},set:function(b,c,e){if(e!==q||a.a.f.pa(b,!1)!==q)a.a.f.pa(b,!0)[c]=e},pa:function(a,g){var e=a[c];if(!e||"null"===e||!d[e]){if(!g)return q;e=a[c]="ko"+b++;d[e]={}}return d[e]},clear:function(a){var b=a[c];return b?(delete d[b],a[c]=null,!0):!1}}};a.b("utils.domData",a.a.f);a.b("utils.domData.clear",a.a.f.clear);a.a.C=new function(){function b(b,c){var g=a.a.f.get(b,d);g===q&&c&&(g=[],a.a.f.set(b,d,g));return g}function c(e){var d= b(e,!1);if(d)for(var d=d.slice(0),f=0;f<d.length;f++)d[f](e);a.a.f.clear(e);"function"==typeof t&&"function"==typeof t.cleanData&&t.cleanData([e]);if(g[e.nodeType])for(d=e.firstChild;e=d;)d=e.nextSibling,8===e.nodeType&&c(e)}var d="__ko_domNodeDisposal__"+(new Date).getTime(),f={1:!0,8:!0,9:!0},g={1:!0,9:!0};return{ia:function(a,c){if("function"!=typeof c)throw Error("Callback must be a function");b(a,!0).push(c)},cb:function(e,c){var g=b(e,!1);g&&(a.a.ka(g,c),0==g.length&&a.a.f.set(e,d,q))},H:function(b){if(f[b.nodeType]&& (c(b),g[b.nodeType])){var d=[];a.a.R(d,b.getElementsByTagName("*"));for(var h=0,k=d.length;h<k;h++)c(d[h])}return b},removeNode:function(b){a.H(b);b.parentNode&&b.parentNode.removeChild(b)}}};a.H=a.a.C.H;a.removeNode=a.a.C.removeNode;a.b("cleanNode",a.H);a.b("removeNode",a.removeNode);a.b("utils.domNodeDisposal",a.a.C);a.b("utils.domNodeDisposal.addDisposeCallback",a.a.C.ia);a.b("utils.domNodeDisposal.removeDisposeCallback",a.a.C.cb);(function(){a.a.xa=function(b){var c;if("undefined"!=typeof t)if(t.parseHTML)c= t.parseHTML(b)||[];else{if((c=t.clean([b]))&&c[0]){for(b=c[0];b.parentNode&&11!==b.parentNode.nodeType;)b=b.parentNode;b.parentNode&&b.parentNode.removeChild(b)}}else{var d=a.a.F(b).toLowerCase();c=s.createElement("div");d=d.match(/^<(thead|tbody|tfoot)/)&&[1,"<table>","</table>"]||!d.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!d.indexOf("<td")||!d.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||[0,"",""];b="ignored<div>"+d[1]+b+d[2]+"</div>";for("function"==typeof w.innerShiv? c.appendChild(w.innerShiv(b)):c.innerHTML=b;d[0]--;)c=c.lastChild;c=a.a.N(c.lastChild.childNodes)}return c};a.a.fa=function(b,c){a.a.oa(b);c=a.a.c(c);if(null!==c&&c!==q)if("string"!=typeof c&&(c=c.toString()),"undefined"!=typeof t)t(b).html(c);else for(var d=a.a.xa(c),f=0;f<d.length;f++)b.appendChild(d[f])}})();a.b("utils.parseHtmlFragment",a.a.xa);a.b("utils.setHtml",a.a.fa);a.s=function(){function b(c,f){if(c)if(8==c.nodeType){var g=a.s.$a(c.nodeValue);null!=g&&f.push({xb:c,Kb:g})}else if(1==c.nodeType)for(var g= 0,e=c.childNodes,m=e.length;g<m;g++)b(e[g],f)}var c={};return{va:function(a){if("function"!=typeof a)throw Error("You can only pass a function to ko.memoization.memoize()");var b=(4294967296*(1+Math.random())|0).toString(16).substring(1)+(4294967296*(1+Math.random())|0).toString(16).substring(1);c[b]=a;return"\x3c!--[ko_memo:"+b+"]--\x3e"},mb:function(a,b){var g=c[a];if(g===q)throw Error("Couldn't find any memo with ID "+a+". Perhaps it's already been unmemoized.");try{return g.apply(null,b||[]), !0}finally{delete c[a]}},nb:function(c,f){var g=[];b(c,g);for(var e=0,m=g.length;e<m;e++){var h=g[e].xb,k=[h];f&&a.a.R(k,f);a.s.mb(g[e].Kb,k);h.nodeValue="";h.parentNode&&h.parentNode.removeChild(h)}},$a:function(a){return(a=a.match(/^\[ko_memo\:(.*?)\]$/))?a[1]:null}}}();a.b("memoization",a.s);a.b("memoization.memoize",a.s.va);a.b("memoization.unmemoize",a.s.mb);a.b("memoization.parseMemoText",a.s.$a);a.b("memoization.unmemoizeDomNodeAndDescendants",a.s.nb);a.Sa={throttle:function(b,c){b.throttleEvaluation= c;var d=null;return a.j({read:b,write:function(a){clearTimeout(d);d=setTimeout(function(){b(a)},c)}})},notify:function(b,c){b.equalityComparer="always"==c?F(!1):a.m.fn.equalityComparer;return b}};a.b("extenders",a.Sa);a.kb=function(b,c,d){this.target=b;this.la=c;this.wb=d;a.r(this,"dispose",this.B)};a.kb.prototype.B=function(){this.Hb=!0;this.wb()};a.V=function(){this.G={};a.a.extend(this,a.V.fn);a.r(this,"subscribe",this.Da);a.r(this,"extend",this.extend);a.r(this,"getSubscriptionsCount",this.Db)}; a.V.fn={Da:function(b,c,d){d=d||"change";var f=new a.kb(this,c?b.bind(c):b,function(){a.a.ka(this.G[d],f)}.bind(this));this.G[d]||(this.G[d]=[]);this.G[d].push(f);return f},notifySubscribers:function(b,c){c=c||"change";this.G[c]&&a.q.I(function(){a.a.p(this.G[c].slice(0),function(a){a&&!0!==a.Hb&&a.la(b)})},this)},Db:function(){var b=0;a.a.w(this.G,function(a,d){b+=d.length});return b},extend:function(b){var c=this;b&&a.a.w(b,function(b,f){var g=a.Sa[b];"function"==typeof g&&(c=g(c,f))});return c}}; a.Wa=function(a){return null!=a&&"function"==typeof a.Da&&"function"==typeof a.notifySubscribers};a.b("subscribable",a.V);a.b("isSubscribable",a.Wa);a.q=function(){var b=[];return{rb:function(a){b.push({la:a,Ra:[]})},end:function(){b.pop()},bb:function(c){if(!a.Wa(c))throw Error("Only subscribable things can act as dependencies");if(0<b.length){var d=b[b.length-1];!d||0<=a.a.k(d.Ra,c)||(d.Ra.push(c),d.la(c))}},I:function(a,d,f){try{return b.push(null),a.apply(d,f||[])}finally{b.pop()}}}}();var L= {undefined:!0,"boolean":!0,number:!0,string:!0};a.m=function(b){function c(){if(0<arguments.length)return c.equalityComparer&&c.equalityComparer(d,arguments[0])||(c.K(),d=arguments[0],c.J()),this;a.q.bb(c);return d}var d=b;a.V.call(c);c.t=function(){return d};c.J=function(){c.notifySubscribers(d)};c.K=function(){c.notifySubscribers(d,"beforeChange")};a.a.extend(c,a.m.fn);a.r(c,"peek",c.t);a.r(c,"valueHasMutated",c.J);a.r(c,"valueWillMutate",c.K);return c};a.m.fn={equalityComparer:function(a,c){return null=== a||typeof a in L?a===c:!1}};var A=a.m.Pb="__ko_proto__";a.m.fn[A]=a.m;a.qa=function(b,c){return null===b||b===q||b[A]===q?!1:b[A]===c?!0:a.qa(b[A],c)};a.T=function(b){return a.qa(b,a.m)};a.Xa=function(b){return"function"==typeof b&&b[A]===a.m||"function"==typeof b&&b[A]===a.j&&b.Eb?!0:!1};a.b("observable",a.m);a.b("isObservable",a.T);a.b("isWriteableObservable",a.Xa);a.U=function(b){b=b||[];if("object"!=typeof b||!("length"in b))throw Error("The argument passed when initializing an observable array must be an array, or null, or undefined."); b=a.m(b);a.a.extend(b,a.U.fn);return b};a.U.fn={remove:function(a){for(var c=this.t(),d=[],f="function"==typeof a?a:function(e){return e===a},g=0;g<c.length;g++){var e=c[g];f(e)&&(0===d.length&&this.K(),d.push(e),c.splice(g,1),g--)}d.length&&this.J();return d},removeAll:function(b){if(b===q){var c=this.t(),d=c.slice(0);this.K();c.splice(0,c.length);this.J();return d}return b?this.remove(function(c){return 0<=a.a.k(b,c)}):[]},destroy:function(a){var c=this.t(),d="function"==typeof a?a:function(c){return c=== a};this.K();for(var f=c.length-1;0<=f;f--)d(c[f])&&(c[f]._destroy=!0);this.J()},destroyAll:function(b){return b===q?this.destroy(F(!0)):b?this.destroy(function(c){return 0<=a.a.k(b,c)}):[]},indexOf:function(b){var c=this();return a.a.k(c,b)},replace:function(a,c){var d=this.indexOf(a);0<=d&&(this.K(),this.t()[d]=c,this.J())}};a.a.p("pop push reverse shift sort splice unshift".split(" "),function(b){a.U.fn[b]=function(){var a=this.t();this.K();a=a[b].apply(a,arguments);this.J();return a}});a.a.p(["slice"], function(b){a.U.fn[b]=function(){var a=this();return a[b].apply(a,arguments)}});a.b("observableArray",a.U);a.j=function(b,c,d){function f(){a.a.p(v,function(a){a.B()});v=[]}function g(){var a=m.throttleEvaluation;a&&0<=a?(clearTimeout(t),t=setTimeout(e,a)):e()}function e(){if(!n)if(l&&D())x();else{n=!0;try{var b=a.a.Z(v,function(a){return a.target});a.q.rb(function(e){var c;0<=(c=a.a.k(b,e))?b[c]=q:v.push(e.Da(g))});for(var e=p.call(c),d=b.length-1;0<=d;d--)b[d]&&v.splice(d,1)[0].B();l=!0;m.notifySubscribers(k, "beforeChange");k=e;m.notifySubscribers(k)}finally{a.q.end(),n=!1}v.length||x()}}function m(){if(0<arguments.length){if("function"===typeof r)r.apply(c,arguments);else throw Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");return this}l||e();a.q.bb(m);return k}function h(){return!l||0<v.length}var k,l=!1,n=!1,p=b;p&&"object"==typeof p?(d=p,p=d.read):(d=d||{},p||(p=d.read));if("function"!=typeof p)throw Error("Pass a function that returns the value of the ko.computed"); var r=d.write,z=d.disposeWhenNodeIsRemoved||d.$||null,D=d.disposeWhen||d.Qa||F(!1),x=f,v=[],t=null;c||(c=d.owner);m.t=function(){l||e();return k};m.Cb=function(){return v.length};m.Eb="function"===typeof d.write;m.B=function(){x()};m.ta=h;a.V.call(m);a.a.extend(m,a.j.fn);a.r(m,"peek",m.t);a.r(m,"dispose",m.B);a.r(m,"isActive",m.ta);a.r(m,"getDependenciesCount",m.Cb);!0!==d.deferEvaluation&&e();if(z&&h()){x=function(){a.a.C.cb(z,x);f()};a.a.C.ia(z,x);var s=D,D=function(){return!a.a.aa(z)||s()}}return m}; a.Gb=function(b){return a.qa(b,a.j)};C=a.m.Pb;a.j[C]=a.m;a.j.fn={};a.j.fn[C]=a.j;a.b("dependentObservable",a.j);a.b("computed",a.j);a.b("isComputed",a.Gb);(function(){function b(a,g,e){e=e||new d;a=g(a);if("object"!=typeof a||null===a||a===q||a instanceof Date||a instanceof String||a instanceof Number||a instanceof Boolean)return a;var m=a instanceof Array?[]:{};e.save(a,m);c(a,function(c){var d=g(a[c]);switch(typeof d){case "boolean":case "number":case "string":case "function":m[c]=d;break;case "object":case "undefined":var l= e.get(d);m[c]=l!==q?l:b(d,g,e)}});return m}function c(a,b){if(a instanceof Array){for(var e=0;e<a.length;e++)b(e);"function"==typeof a.toJSON&&b("toJSON")}else for(e in a)b(e)}function d(){this.keys=[];this.Ha=[]}a.lb=function(c){if(0==arguments.length)throw Error("When calling ko.toJS, pass the object you want to convert.");return b(c,function(b){for(var e=0;a.T(b)&&10>e;e++)b=b();return b})};a.toJSON=function(b,c,e){b=a.lb(b);return a.a.Ca(b,c,e)};d.prototype={save:function(b,c){var e=a.a.k(this.keys, b);0<=e?this.Ha[e]=c:(this.keys.push(b),this.Ha.push(c))},get:function(b){b=a.a.k(this.keys,b);return 0<=b?this.Ha[b]:q}}})();a.b("toJS",a.lb);a.b("toJSON",a.toJSON);(function(){a.h={n:function(b){switch(a.a.u(b)){case "option":return!0===b.__ko__hasDomDataOptionValue__?a.a.f.get(b,a.d.options.wa):7>=a.a.ca?b.getAttributeNode("value")&&b.getAttributeNode("value").specified?b.value:b.text:b.value;case "select":return 0<=b.selectedIndex?a.h.n(b.options[b.selectedIndex]):q;default:return b.value}},W:function(b, c){switch(a.a.u(b)){case "option":switch(typeof c){case "string":a.a.f.set(b,a.d.options.wa,q);"__ko__hasDomDataOptionValue__"in b&&delete b.__ko__hasDomDataOptionValue__;b.value=c;break;default:a.a.f.set(b,a.d.options.wa,c),b.__ko__hasDomDataOptionValue__=!0,b.value="number"===typeof c?c:""}break;case "select":""===c&&(c=q);if(null===c||c===q)b.selectedIndex=-1;for(var d=b.options.length-1;0<=d;d--)if(a.h.n(b.options[d])==c){b.selectedIndex=d;break}1<b.size||-1!==b.selectedIndex||(b.selectedIndex= 0);break;default:if(null===c||c===q)c="";b.value=c}}}})();a.b("selectExtensions",a.h);a.b("selectExtensions.readValue",a.h.n);a.b("selectExtensions.writeValue",a.h.W);a.g=function(){function b(a,b){for(var d=null;a!=d;)d=a,a=a.replace(c,function(a,c){return b[c]});return a}var c=/\@ko_token_(\d+)\@/g,d=["true","false","null","undefined"],f=/^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;return{S:[],da:function(c){var e=a.a.F(c);if(3>e.length)return[];"{"===e.charAt(0)&&(e=e.substring(1,e.length- 1));c=[];for(var d=null,f,k=0;k<e.length;k++){var l=e.charAt(k);if(null===d)switch(l){case '"':case "'":case "/":d=k,f=l}else if(l==f&&"\\"!==e.charAt(k-1)){l=e.substring(d,k+1);c.push(l);var n="@ko_token_"+(c.length-1)+"@",e=e.substring(0,d)+n+e.substring(k+1),k=k-(l.length-n.length),d=null}}f=d=null;for(var p=0,r=null,k=0;k<e.length;k++){l=e.charAt(k);if(null===d)switch(l){case "{":d=k;r=l;f="}";break;case "(":d=k;r=l;f=")";break;case "[":d=k,r=l,f="]"}l===r?p++:l===f&&(p--,0===p&&(l=e.substring(d, k+1),c.push(l),n="@ko_token_"+(c.length-1)+"@",e=e.substring(0,d)+n+e.substring(k+1),k-=l.length-n.length,d=null))}f=[];e=e.split(",");d=0;for(k=e.length;d<k;d++)p=e[d],r=p.indexOf(":"),0<r&&r<p.length-1?(l=p.substring(r+1),f.push({key:b(p.substring(0,r),c),value:b(l,c)})):f.push({unknown:b(p,c)});return f},ea:function(b){var e="string"===typeof b?a.g.da(b):b,c=[];b=[];for(var h,k=0;h=e[k];k++)if(0<c.length&&c.push(","),h.key){var l;a:{l=h.key;var n=a.a.F(l);switch(n.length&&n.charAt(0)){case "'":case '"':break a; default:l="'"+n+"'"}}h=h.value;c.push(l);c.push(":");c.push(h);h=a.a.F(h);0<=a.a.k(d,a.a.F(h).toLowerCase())?h=!1:(n=h.match(f),h=null===n?!1:n[1]?"Object("+n[1]+")"+n[2]:h);h&&(0<b.length&&b.push(", "),b.push(l+" : function(__ko_value) { "+h+" = __ko_value; }"))}else h.unknown&&c.push(h.unknown);e=c.join("");0<b.length&&(e=e+", '_ko_property_writers' : { "+b.join("")+" } ");return e},Jb:function(b,c){for(var d=0;d<b.length;d++)if(a.a.F(b[d].key)==c)return!0;return!1},ha:function(b,c,d,f,k){if(b&& a.T(b))!a.Xa(b)||k&&b.t()===f||b(f);else if((b=c()._ko_property_writers)&&b[d])b[d](f)}}}();a.b("expressionRewriting",a.g);a.b("expressionRewriting.bindingRewriteValidators",a.g.S);a.b("expressionRewriting.parseObjectLiteral",a.g.da);a.b("expressionRewriting.preProcessBindings",a.g.ea);a.b("jsonExpressionRewriting",a.g);a.b("jsonExpressionRewriting.insertPropertyAccessorsIntoJson",a.g.ea);(function(){function b(a){return 8==a.nodeType&&(g?a.text:a.nodeValue).match(e)}function c(a){return 8==a.nodeType&& (g?a.text:a.nodeValue).match(m)}function d(a,e){for(var d=a,g=1,f=[];d=d.nextSibling;){if(c(d)&&(g--,0===g))return f;f.push(d);b(d)&&g++}if(!e)throw Error("Cannot find closing comment tag to match: "+a.nodeValue);return null}function f(a,b){var c=d(a,b);return c?0<c.length?c[c.length-1].nextSibling:a.nextSibling:null}var g=s&&"\x3c!--test--\x3e"===s.createComment("test").text,e=g?/^\x3c!--\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*--\x3e$/:/^\s*ko(?:\s+(.+\s*\:[\s\S]*))?\s*$/,m=g?/^\x3c!--\s*\/ko\s*--\x3e$/: /^\s*\/ko\s*$/,h={ul:!0,ol:!0};a.e={L:{},childNodes:function(a){return b(a)?d(a):a.childNodes},ba:function(c){if(b(c)){c=a.e.childNodes(c);for(var e=0,d=c.length;e<d;e++)a.removeNode(c[e])}else a.a.oa(c)},P:function(c,e){if(b(c)){a.e.ba(c);for(var d=c.nextSibling,g=0,f=e.length;g<f;g++)d.parentNode.insertBefore(e[g],d)}else a.a.P(c,e)},ab:function(a,c){b(a)?a.parentNode.insertBefore(c,a.nextSibling):a.firstChild?a.insertBefore(c,a.firstChild):a.appendChild(c)},Va:function(c,e,d){d?b(c)?c.parentNode.insertBefore(e, d.nextSibling):d.nextSibling?c.insertBefore(e,d.nextSibling):c.appendChild(e):a.e.ab(c,e)},firstChild:function(a){return b(a)?!a.nextSibling||c(a.nextSibling)?null:a.nextSibling:a.firstChild},nextSibling:function(a){b(a)&&(a=f(a));return a.nextSibling&&c(a.nextSibling)?null:a.nextSibling},ob:function(a){return(a=b(a))?a[1]:null},Za:function(e){if(h[a.a.u(e)]){var d=e.firstChild;if(d){do if(1===d.nodeType){var g;g=d.firstChild;var m=null;if(g){do if(m)m.push(g);else if(b(g)){var r=f(g,!0);r?g=r:m= [g]}else c(g)&&(m=[g]);while(g=g.nextSibling)}if(g=m)for(m=d.nextSibling,r=0;r<g.length;r++)m?e.insertBefore(g[r],m):e.appendChild(g[r])}while(d=d.nextSibling)}}}}})();a.b("virtualElements",a.e);a.b("virtualElements.allowedBindings",a.e.L);a.b("virtualElements.emptyNode",a.e.ba);a.b("virtualElements.insertAfter",a.e.Va);a.b("virtualElements.prepend",a.e.ab);a.b("virtualElements.setDomNodeChildren",a.e.P);(function(){a.M=function(){this.Na={}};a.a.extend(a.M.prototype,{nodeHasBindings:function(b){switch(b.nodeType){case 1:return null!= b.getAttribute("data-bind");case 8:return null!=a.e.ob(b);default:return!1}},getBindings:function(a,c){var d=this.getBindingsString(a,c);return d?this.parseBindingsString(d,c,a):null},getBindingsString:function(b){switch(b.nodeType){case 1:return b.getAttribute("data-bind");case 8:return a.e.ob(b);default:return null}},parseBindingsString:function(b,c,d){try{var f;if(!(f=this.Na[b])){var g=this.Na,e,m="with($context){with($data||{}){return{"+a.g.ea(b)+"}}}";e=new Function("$context","$element",m); f=g[b]=e}return f(c,d)}catch(h){throw h.message="Unable to parse bindings.\nBindings value: "+b+"\nMessage: "+h.message,h;}}});a.M.instance=new a.M})();a.b("bindingProvider",a.M);(function(){function b(b,e,d){for(var f=a.e.firstChild(e);e=f;)f=a.e.nextSibling(e),c(b,e,d)}function c(c,e,f){var h=!0,k=1===e.nodeType;k&&a.e.Za(e);if(k&&f||a.M.instance.nodeHasBindings(e))h=d(e,null,c,f).Sb;h&&b(c,e,!k)}function d(b,c,d,h){function k(a){return function(){return p[a]}}function l(){return p}var n=0,p,r, z=a.a.f.get(b,f);if(!c){if(z)throw Error("You cannot apply bindings multiple times to the same element.");a.a.f.set(b,f,!0)}a.j(function(){var f=d&&d instanceof a.A?d:new a.A(a.a.c(d)),x=f.$data;!z&&h&&a.jb(b,f);if(p=("function"==typeof c?c(f,b):c)||a.M.instance.getBindings(b,f))0===n&&(n=1,a.a.w(p,function(c){var e=a.d[c];if(e&&8===b.nodeType&&!a.e.L[c])throw Error("The binding '"+c+"' cannot be used with virtual elements");if(e&&"function"==typeof e.init&&(e=(0,e.init)(b,k(c),l,x,f))&&e.controlsDescendantBindings){if(r!== q)throw Error("Multiple bindings ("+r+" and "+c+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");r=c}}),n=2),2===n&&a.a.w(p,function(c){var e=a.d[c];e&&"function"==typeof e.update&&(0,e.update)(b,k(c),l,x,f)})},null,{$:b});return{Sb:r===q}}a.d={};a.A=function(b,c,d){c?(a.a.extend(this,c),this.$parentContext=c,this.$parent=c.$data,this.$parents=(c.$parents||[]).slice(0),this.$parents.unshift(this.$parent)):(this.$parents= [],this.$root=b,this.ko=a);this.$data=b;d&&(this[d]=b)};a.A.prototype.createChildContext=function(b,c){return new a.A(b,this,c)};a.A.prototype.extend=function(b){var c=a.a.extend(new a.A,this);return a.a.extend(c,b)};var f="__ko_boundElement";a.jb=function(b,c){if(2==arguments.length)a.a.f.set(b,"__ko_bindingContext__",c);else return a.a.f.get(b,"__ko_bindingContext__")};a.Ka=function(b,c,f){1===b.nodeType&&a.e.Za(b);return d(b,c,f,!0)};a.Ja=function(a,c){1!==c.nodeType&&8!==c.nodeType||b(a,c,!0)}; a.Ia=function(a,b){if(b&&1!==b.nodeType&&8!==b.nodeType)throw Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");b=b||w.document.body;c(a,b,!0)};a.na=function(b){switch(b.nodeType){case 1:case 8:var c=a.jb(b);if(c)return c;if(b.parentNode)return a.na(b.parentNode)}return q};a.ub=function(b){return(b=a.na(b))?b.$data:q};a.b("bindingHandlers",a.d);a.b("applyBindings",a.Ia);a.b("applyBindingsToDescendants",a.Ja);a.b("applyBindingsToNode",a.Ka); a.b("contextFor",a.na);a.b("dataFor",a.ub)})();var K={"class":"className","for":"htmlFor"};a.d.attr={update:function(b,c){var d=a.a.c(c())||{};a.a.w(d,function(c,d){d=a.a.c(d);var e=!1===d||null===d||d===q;e&&b.removeAttribute(c);8>=a.a.ca&&c in K?(c=K[c],e?b.removeAttribute(c):b[c]=d):e||b.setAttribute(c,d.toString());"name"===c&&a.a.gb(b,e?"":d.toString())})}};a.d.checked={init:function(b,c,d){a.a.o(b,"click",function(){var f;if("checkbox"==b.type)f=b.checked;else if("radio"==b.type&&b.checked)f= b.value;else return;var g=c(),e=a.a.c(g);"checkbox"==b.type&&e instanceof Array?a.a.ja(g,b.value,b.checked):a.g.ha(g,d,"checked",f,!0)});"radio"!=b.type||b.name||a.d.uniqueName.init(b,F(!0))},update:function(b,c){var d=a.a.c(c());"checkbox"==b.type?b.checked=d instanceof Array?0<=a.a.k(d,b.value):d:"radio"==b.type&&(b.checked=b.value==d)}};a.d.css={update:function(b,c){var d=a.a.c(c());"object"==typeof d?a.a.w(d,function(c,d){d=a.a.c(d);a.a.ga(b,c,d)}):(d=String(d||""),a.a.ga(b,b.__ko__cssValue,!1), b.__ko__cssValue=d,a.a.ga(b,d,!0))}};a.d.enable={update:function(b,c){var d=a.a.c(c());d&&b.disabled?b.removeAttribute("disabled"):d||b.disabled||(b.disabled=!0)}};a.d.disable={update:function(b,c){a.d.enable.update(b,function(){return!a.a.c(c())})}};a.d.event={init:function(b,c,d,f){var g=c()||{};a.a.w(g,function(e){"string"==typeof e&&a.a.o(b,e,function(b){var g,k=c()[e];if(k){var l=d();try{var n=a.a.N(arguments);n.unshift(f);g=k.apply(f,n)}finally{!0!==g&&(b.preventDefault?b.preventDefault():b.returnValue= !1)}!1===l[e+"Bubble"]&&(b.cancelBubble=!0,b.stopPropagation&&b.stopPropagation())}})})}};a.d.foreach={Ya:function(b){return function(){var c=b(),d=a.a.ya(c);if(!d||"number"==typeof d.length)return{foreach:c,templateEngine:a.D.sa};a.a.c(c);return{foreach:d.data,as:d.as,includeDestroyed:d.includeDestroyed,afterAdd:d.afterAdd,beforeRemove:d.beforeRemove,afterRender:d.afterRender,beforeMove:d.beforeMove,afterMove:d.afterMove,templateEngine:a.D.sa}}},init:function(b,c){return a.d.template.init(b,a.d.foreach.Ya(c))}, update:function(b,c,d,f,g){return a.d.template.update(b,a.d.foreach.Ya(c),d,f,g)}};a.g.S.foreach=!1;a.e.L.foreach=!0;a.d.hasfocus={init:function(b,c,d){function f(e){b.__ko_hasfocusUpdating=!0;var f=b.ownerDocument;if("activeElement"in f){var g;try{g=f.activeElement}catch(l){g=f.body}e=g===b}f=c();a.g.ha(f,d,"hasfocus",e,!0);b.__ko_hasfocusLastValue=e;b.__ko_hasfocusUpdating=!1}var g=f.bind(null,!0),e=f.bind(null,!1);a.a.o(b,"focus",g);a.a.o(b,"focusin",g);a.a.o(b,"blur",e);a.a.o(b,"focusout",e)}, update:function(b,c){var d=!!a.a.c(c());b.__ko_hasfocusUpdating||b.__ko_hasfocusLastValue===d||(d?b.focus():b.blur(),a.q.I(a.a.Ga,null,[b,d?"focusin":"focusout"]))}};a.d.hasFocus=a.d.hasfocus;a.d.html={init:function(){return{controlsDescendantBindings:!0}},update:function(b,c){a.a.fa(b,c())}};var I="__ko_withIfBindingData";G("if");G("ifnot",!1,!0);G("with",!0,!1,function(a,c){return a.createChildContext(c)});a.d.options={init:function(b){if("select"!==a.a.u(b))throw Error("options binding applies only to SELECT elements"); for(;0<b.length;)b.remove(0);return{controlsDescendantBindings:!0}},update:function(b,c,d){function f(a,b,c){var d=typeof b;return"function"==d?b(a):"string"==d?a[b]:c}function g(b,c){if(p){var d=0<=a.a.k(p,a.h.n(c[0]));a.a.hb(c[0],d)}}var e=0==b.length,m=!e&&b.multiple?b.scrollTop:null;c=a.a.c(c());var h=d(),k=h.optionsIncludeDestroyed,l={},n,p;b.multiple?p=a.a.Z(b.selectedOptions||a.a.Y(b.childNodes,function(b){return b.tagName&&"option"===a.a.u(b)&&b.selected}),function(b){return a.h.n(b)}):0<= b.selectedIndex&&(p=[a.h.n(b.options[b.selectedIndex])]);if(c){"undefined"==typeof c.length&&(c=[c]);var r=a.a.Y(c,function(b){return k||b===q||null===b||!a.a.c(b._destroy)});"optionsCaption"in h&&(n=a.a.c(h.optionsCaption),null!==n&&n!==q&&r.unshift(l))}else c=[];d=g;h.optionsAfterRender&&(d=function(b,c){g(0,c);a.q.I(h.optionsAfterRender,null,[c[0],b!==l?b:q])});a.a.Aa(b,r,function(b,c,d){d.length&&(p=d[0].selected&&[a.h.n(d[0])]);c=s.createElement("option");b===l?(a.a.fa(c,n),a.h.W(c,q)):(d=f(b, h.optionsValue,b),a.h.W(c,a.a.c(d)),b=f(b,h.optionsText,d),a.a.ib(c,b));return[c]},null,d);p=null;e&&"value"in h&&J(b,a.a.ya(h.value),!0);a.a.zb(b);m&&20<Math.abs(m-b.scrollTop)&&(b.scrollTop=m)}};a.d.options.wa="__ko.optionValueDomData__";a.d.selectedOptions={init:function(b,c,d){a.a.o(b,"change",function(){var f=c(),g=[];a.a.p(b.getElementsByTagName("option"),function(b){b.selected&&g.push(a.h.n(b))});a.g.ha(f,d,"selectedOptions",g)})},update:function(b,c){if("select"!=a.a.u(b))throw Error("values binding applies only to SELECT elements"); var d=a.a.c(c());d&&"number"==typeof d.length&&a.a.p(b.getElementsByTagName("option"),function(b){var c=0<=a.a.k(d,a.h.n(b));a.a.hb(b,c)})}};a.d.style={update:function(b,c){var d=a.a.c(c()||{});a.a.w(d,function(c,d){d=a.a.c(d);b.style[c]=d||""})}};a.d.submit={init:function(b,c,d,f){if("function"!=typeof c())throw Error("The value for a submit binding must be a function");a.a.o(b,"submit",function(a){var d,m=c();try{d=m.call(f,b)}finally{!0!==d&&(a.preventDefault?a.preventDefault():a.returnValue=!1)}})}}; a.d.text={update:function(b,c){a.a.ib(b,c())}};a.e.L.text=!0;a.d.uniqueName={init:function(b,c){if(c()){var d="ko_unique_"+ ++a.d.uniqueName.tb;a.a.gb(b,d)}}};a.d.uniqueName.tb=0;a.d.value={init:function(b,c,d){function f(){m=!1;var e=c(),f=a.h.n(b);a.g.ha(e,d,"value",f)}var g=["change"],e=d().valueUpdate,m=!1;e&&("string"==typeof e&&(e=[e]),a.a.R(g,e),g=a.a.Ma(g));!a.a.ca||("input"!=b.tagName.toLowerCase()||"text"!=b.type||"off"==b.autocomplete||b.form&&"off"==b.form.autocomplete)||-1!=a.a.k(g,"propertychange")|| (a.a.o(b,"propertychange",function(){m=!0}),a.a.o(b,"blur",function(){m&&f()}));a.a.p(g,function(c){var d=f;a.a.Tb(c,"after")&&(d=function(){setTimeout(f,0)},c=c.substring(5));a.a.o(b,c,d)})},update:function(b,c){var d="select"===a.a.u(b),f=a.a.c(c()),g=a.h.n(b);f!==g&&(g=function(){a.h.W(b,f)},g(),d&&setTimeout(g,0));d&&0<b.length&&J(b,f,!1)}};a.d.visible={update:function(b,c){var d=a.a.c(c()),f="none"!=b.style.display;d&&!f?b.style.display="":!d&&f&&(b.style.display="none")}};(function(b){a.d[b]= {init:function(c,d,f,g){return a.d.event.init.call(this,c,function(){var a={};a[b]=d();return a},f,g)}}})("click");a.v=function(){};a.v.prototype.renderTemplateSource=function(){throw Error("Override renderTemplateSource");};a.v.prototype.createJavaScriptEvaluatorBlock=function(){throw Error("Override createJavaScriptEvaluatorBlock");};a.v.prototype.makeTemplateSource=function(b,c){if("string"==typeof b){c=c||s;var d=c.getElementById(b);if(!d)throw Error("Cannot find template with ID "+b);return new a.l.i(d)}if(1== b.nodeType||8==b.nodeType)return new a.l.Q(b);throw Error("Unknown template type: "+b);};a.v.prototype.renderTemplate=function(a,c,d,f){a=this.makeTemplateSource(a,f);return this.renderTemplateSource(a,c,d)};a.v.prototype.isTemplateRewritten=function(a,c){return!1===this.allowTemplateRewriting?!0:this.makeTemplateSource(a,c).data("isRewritten")};a.v.prototype.rewriteTemplate=function(a,c,d){a=this.makeTemplateSource(a,d);c=c(a.text());a.text(c);a.data("isRewritten",!0)};a.b("templateEngine",a.v); a.Ea=function(){function b(b,c,d,m){b=a.g.da(b);for(var h=a.g.S,k=0;k<b.length;k++){var l=b[k].key;if(h.hasOwnProperty(l)){var n=h[l];if("function"===typeof n){if(l=n(b[k].value))throw Error(l);}else if(!n)throw Error("This template engine does not support the '"+l+"' binding within its templates");}}d="ko.__tr_ambtns(function($context,$element){return(function(){return{ "+a.g.ea(b)+" } })()},'"+d.toLowerCase()+"')";return m.createJavaScriptEvaluatorBlock(d)+c}var c=/(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi, d=/\x3c!--\s*ko\b\s*([\s\S]*?)\s*--\x3e/g;return{Ab:function(b,c,d){c.isTemplateRewritten(b,d)||c.rewriteTemplate(b,function(b){return a.Ea.Lb(b,c)},d)},Lb:function(a,g){return a.replace(c,function(a,c,d,f,l){return b(l,c,d,g)}).replace(d,function(a,c){return b(c,"\x3c!-- ko --\x3e","#comment",g)})},qb:function(b,c){return a.s.va(function(d,m){var h=d.nextSibling;h&&h.nodeName.toLowerCase()===c&&a.Ka(h,b,m)})}}}();a.b("__tr_ambtns",a.Ea.qb);(function(){a.l={};a.l.i=function(a){this.i=a};a.l.i.prototype.text= function(){var b=a.a.u(this.i),b="script"===b?"text":"textarea"===b?"value":"innerHTML";if(0==arguments.length)return this.i[b];var c=arguments[0];"innerHTML"===b?a.a.fa(this.i,c):this.i[b]=c};a.l.i.prototype.data=function(b){if(1===arguments.length)return a.a.f.get(this.i,"templateSourceData_"+b);a.a.f.set(this.i,"templateSourceData_"+b,arguments[1])};a.l.Q=function(a){this.i=a};a.l.Q.prototype=new a.l.i;a.l.Q.prototype.text=function(){if(0==arguments.length){var b=a.a.f.get(this.i,"__ko_anon_template__")|| {};b.Fa===q&&b.ma&&(b.Fa=b.ma.innerHTML);return b.Fa}a.a.f.set(this.i,"__ko_anon_template__",{Fa:arguments[0]})};a.l.i.prototype.nodes=function(){if(0==arguments.length)return(a.a.f.get(this.i,"__ko_anon_template__")||{}).ma;a.a.f.set(this.i,"__ko_anon_template__",{ma:arguments[0]})};a.b("templateSources",a.l);a.b("templateSources.domElement",a.l.i);a.b("templateSources.anonymousTemplate",a.l.Q)})();(function(){function b(b,c,d){var f;for(c=a.e.nextSibling(c);b&&(f=b)!==c;)b=a.e.nextSibling(f),1!== f.nodeType&&8!==f.nodeType||d(f)}function c(c,d){if(c.length){var f=c[0],g=c[c.length-1];b(f,g,function(b){a.Ia(d,b)});b(f,g,function(b){a.s.nb(b,[d])})}}function d(a){return a.nodeType?a:0<a.length?a[0]:null}function f(b,f,h,k,l){l=l||{};var n=b&&d(b),n=n&&n.ownerDocument,p=l.templateEngine||g;a.Ea.Ab(h,p,n);h=p.renderTemplate(h,k,l,n);if("number"!=typeof h.length||0<h.length&&"number"!=typeof h[0].nodeType)throw Error("Template engine must return an array of DOM nodes");n=!1;switch(f){case "replaceChildren":a.e.P(b, h);n=!0;break;case "replaceNode":a.a.eb(b,h);n=!0;break;case "ignoreTargetNode":break;default:throw Error("Unknown renderMode: "+f);}n&&(c(h,k),l.afterRender&&a.q.I(l.afterRender,null,[h,k.$data]));return h}var g;a.Ba=function(b){if(b!=q&&!(b instanceof a.v))throw Error("templateEngine must inherit from ko.templateEngine");g=b};a.za=function(b,c,h,k,l){h=h||{};if((h.templateEngine||g)==q)throw Error("Set a template engine before calling renderTemplate");l=l||"replaceChildren";if(k){var n=d(k);return a.j(function(){var g= c&&c instanceof a.A?c:new a.A(a.a.c(c)),r="function"==typeof b?b(g.$data,g):b,g=f(k,l,r,g,h);"replaceNode"==l&&(k=g,n=d(k))},null,{Qa:function(){return!n||!a.a.aa(n)},$:n&&"replaceNode"==l?n.parentNode:n})}return a.s.va(function(d){a.za(b,c,h,d,"replaceNode")})};a.Rb=function(b,d,g,k,l){function n(a,b){c(b,r);g.afterRender&&g.afterRender(b,a)}function p(c,d){r=l.createChildContext(a.a.c(c),g.as);r.$index=d;var k="function"==typeof b?b(c,r):b;return f(null,"ignoreTargetNode",k,r,g)}var r;return a.j(function(){var b= a.a.c(d)||[];"undefined"==typeof b.length&&(b=[b]);b=a.a.Y(b,function(b){return g.includeDestroyed||b===q||null===b||!a.a.c(b._destroy)});a.q.I(a.a.Aa,null,[k,b,p,g,n])},null,{$:k})};a.d.template={init:function(b,c){var d=a.a.c(c());"string"==typeof d||(d.name||1!=b.nodeType&&8!=b.nodeType)||(d=1==b.nodeType?b.childNodes:a.e.childNodes(b),d=a.a.Mb(d),(new a.l.Q(b)).nodes(d));return{controlsDescendantBindings:!0}},update:function(b,c,d,f,g){c=a.a.c(c());d={};f=!0;var n,p=null;"string"!=typeof c&&(d= c,c=a.a.c(d.name),"if"in d&&(f=a.a.c(d["if"])),f&&"ifnot"in d&&(f=!a.a.c(d.ifnot)),n=a.a.c(d.data));"foreach"in d?p=a.Rb(c||b,f&&d.foreach||[],d,b,g):f?(g="data"in d?g.createChildContext(n,d.as):g,p=a.za(c||b,g,d,b)):a.e.ba(b);g=p;(n=a.a.f.get(b,"__ko__templateComputedDomDataKey__"))&&"function"==typeof n.B&&n.B();a.a.f.set(b,"__ko__templateComputedDomDataKey__",g&&g.ta()?g:q)}};a.g.S.template=function(b){b=a.g.da(b);return 1==b.length&&b[0].unknown||a.g.Jb(b,"name")?null:"This template engine does not support anonymous templates nested within its templates"}; a.e.L.template=!0})();a.b("setTemplateEngine",a.Ba);a.b("renderTemplate",a.za);a.a.Pa=function(){function a(b,d,f,g,e){var m=Math.min,h=Math.max,k=[],l,n=b.length,p,r=d.length,q=r-n||1,t=n+r+1,s,v,w;for(l=0;l<=n;l++)for(v=s,k.push(s=[]),w=m(r,l+q),p=h(0,l-1);p<=w;p++)s[p]=p?l?b[l-1]===d[p-1]?v[p-1]:m(v[p]||t,s[p-1]||t)+1:p+1:l+1;m=[];h=[];q=[];l=n;for(p=r;l||p;)r=k[l][p]-1,p&&r===k[l][p-1]?h.push(m[m.length]={status:f,value:d[--p],index:p}):l&&r===k[l-1][p]?q.push(m[m.length]={status:g,value:b[--l], index:l}):(m.push({status:"retained",value:d[--p]}),--l);if(h.length&&q.length){b=10*n;var E;for(d=f=0;(e||d<b)&&(E=h[f]);f++){for(g=0;k=q[g];g++)if(E.value===k.value){E.moved=k.index;k.moved=E.index;q.splice(g,1);d=g=0;break}d+=g}}return m.reverse()}return function(c,d,f){c=c||[];d=d||[];return c.length<=d.length?a(c,d,"added","deleted",f):a(d,c,"deleted","added",f)}}();a.b("utils.compareArrays",a.a.Pa);(function(){function b(b){for(;b.length&&!a.a.aa(b[0]);)b.splice(0,1);if(1<b.length){for(var c= b[0],g=b[b.length-1],e=[c];c!==g;){c=c.nextSibling;if(!c)return;e.push(c)}Array.prototype.splice.apply(b,[0,b.length].concat(e))}return b}function c(c,f,g,e,m){var h=[];c=a.j(function(){var c=f(g,m,b(h))||[];0<h.length&&(a.a.eb(h,c),e&&a.q.I(e,null,[g,c,m]));h.splice(0,h.length);a.a.R(h,c)},null,{$:c,Qa:function(){return!a.a.pb(h)}});return{O:h,j:c.ta()?c:q}}a.a.Aa=function(d,f,g,e,m){function h(a,c){u=n[c];x!==c&&(E[a]=u);u.ra(x++);b(u.O);t.push(u);w.push(u)}function k(b,c){if(b)for(var d=0,e=c.length;d< e;d++)c[d]&&a.a.p(c[d].O,function(a){b(a,d,c[d].X)})}f=f||[];e=e||{};var l=a.a.f.get(d,"setDomNodeChildrenFromArrayMapping_lastMappingResult")===q,n=a.a.f.get(d,"setDomNodeChildrenFromArrayMapping_lastMappingResult")||[],p=a.a.Z(n,function(a){return a.X}),r=a.a.Pa(p,f,e.dontLimitMoves),t=[],s=0,x=0,v=[],w=[];f=[];for(var E=[],p=[],u,B=0,y,A;y=r[B];B++)switch(A=y.moved,y.status){case "deleted":A===q&&(u=n[s],u.j&&u.j.B(),v.push.apply(v,b(u.O)),e.beforeRemove&&(f[B]=u,w.push(u)));s++;break;case "retained":h(B, s++);break;case "added":A!==q?h(B,A):(u={X:y.value,ra:a.m(x++)},t.push(u),w.push(u),l||(p[B]=u))}k(e.beforeMove,E);a.a.p(v,e.beforeRemove?a.H:a.removeNode);for(var B=0,l=a.e.firstChild(d),C;u=w[B];B++){u.O||a.a.extend(u,c(d,g,u.X,m,u.ra));for(s=0;r=u.O[s];l=r.nextSibling,C=r,s++)r!==l&&a.e.Va(d,r,C);!u.Fb&&m&&(m(u.X,u.O,u.ra),u.Fb=!0)}k(e.beforeRemove,f);k(e.afterMove,E);k(e.afterAdd,p);a.a.f.set(d,"setDomNodeChildrenFromArrayMapping_lastMappingResult",t)}})();a.b("utils.setDomNodeChildrenFromArrayMapping", a.a.Aa);a.D=function(){this.allowTemplateRewriting=!1};a.D.prototype=new a.v;a.D.prototype.renderTemplateSource=function(b){var c=(9>a.a.ca?0:b.nodes)?b.nodes():null;if(c)return a.a.N(c.cloneNode(!0).childNodes);b=b.text();return a.a.xa(b)};a.D.sa=new a.D;a.Ba(a.D.sa);a.b("nativeTemplateEngine",a.D);(function(){a.ua=function(){var a=this.Ib=function(){if("undefined"==typeof t||!t.tmpl)return 0;try{if(0<=t.tmpl.tag.tmpl.open.toString().indexOf("__"))return 2}catch(a){}return 1}();this.renderTemplateSource= function(b,f,g){g=g||{};if(2>a)throw Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");var e=b.data("precompiled");e||(e=b.text()||"",e=t.template(null,"{{ko_with $item.koBindingContext}}"+e+"{{/ko_with}}"),b.data("precompiled",e));b=[f.$data];f=t.extend({koBindingContext:f},g.templateOptions);f=t.tmpl(e,b,f);f.appendTo(s.createElement("div"));t.fragments={};return f};this.createJavaScriptEvaluatorBlock=function(a){return"{{ko_code ((function() { return "+ a+" })()) }}"};this.addTemplate=function(a,b){s.write("<script type='text/html' id='"+a+"'>"+b+"\x3c/script>")};0<a&&(t.tmpl.tag.ko_code={open:"__.push($1 || '');"},t.tmpl.tag.ko_with={open:"with($1) {",close:"} "})};a.ua.prototype=new a.v;var b=new a.ua;0<b.Ib&&a.Ba(b);a.b("jqueryTmplTemplateEngine",a.ua)})()})})(); })(); /** * Durandal 2.0.1 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. * Available via the MIT license. * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. */ /** * The binder joins an object instance and a DOM element tree by applying databinding and/or invoking binding lifecycle callbacks (binding and bindingComplete). * @module binder * @requires system * @requires knockout */ define('durandal/binder',['durandal/system', 'knockout'], function (system, ko) { var binder, insufficientInfoMessage = 'Insufficient Information to Bind', unexpectedViewMessage = 'Unexpected View Type', bindingInstructionKey = 'durandal-binding-instruction', koBindingContextKey = '__ko_bindingContext__'; function normalizeBindingInstruction(result){ if(result === undefined){ return { applyBindings: true }; } if(system.isBoolean(result)){ return { applyBindings:result }; } if(result.applyBindings === undefined){ result.applyBindings = true; } return result; } function doBind(obj, view, bindingTarget, data){ if (!view || !bindingTarget) { if (binder.throwOnErrors) { system.error(insufficientInfoMessage); } else { system.log(insufficientInfoMessage, view, data); } return; } if (!view.getAttribute) { if (binder.throwOnErrors) { system.error(unexpectedViewMessage); } else { system.log(unexpectedViewMessage, view, data); } return; } var viewName = view.getAttribute('data-view'); try { var instruction; if (obj && obj.binding) { instruction = obj.binding(view); } instruction = normalizeBindingInstruction(instruction); binder.binding(data, view, instruction); if(instruction.applyBindings){ system.log('Binding', viewName, data); ko.applyBindings(bindingTarget, view); }else if(obj){ ko.utils.domData.set(view, koBindingContextKey, { $data:obj }); } binder.bindingComplete(data, view, instruction); if (obj && obj.bindingComplete) { obj.bindingComplete(view); } ko.utils.domData.set(view, bindingInstructionKey, instruction); return instruction; } catch (e) { e.message = e.message + ';\nView: ' + viewName + ";\nModuleId: " + system.getModuleId(data); if (binder.throwOnErrors) { system.error(e); } else { system.log(e.message); } } } /** * @class BinderModule * @static */ return binder = { /** * Called before every binding operation. Does nothing by default. * @method binding * @param {object} data The data that is about to be bound. * @param {DOMElement} view The view that is about to be bound. * @param {object} instruction The object that carries the binding instructions. */ binding: system.noop, /** * Called after every binding operation. Does nothing by default. * @method bindingComplete * @param {object} data The data that has just been bound. * @param {DOMElement} view The view that has just been bound. * @param {object} instruction The object that carries the binding instructions. */ bindingComplete: system.noop, /** * Indicates whether or not the binding system should throw errors or not. * @property {boolean} throwOnErrors * @default false The binding system will not throw errors by default. Instead it will log them. */ throwOnErrors: false, /** * Gets the binding instruction that was associated with a view when it was bound. * @method getBindingInstruction * @param {DOMElement} view The view that was previously bound. * @return {object} The object that carries the binding instructions. */ getBindingInstruction:function(view){ return ko.utils.domData.get(view, bindingInstructionKey); }, /** * Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context. * @method bindContext * @param {KnockoutBindingContext} bindingContext The current binding context. * @param {DOMElement} view The view to bind. * @param {object} [obj] The data to bind to, causing the creation of a child binding context if present. */ bindContext: function(bindingContext, view, obj) { if (obj && bindingContext) { bindingContext = bindingContext.createChildContext(obj); } return doBind(obj, view, bindingContext, obj || (bindingContext ? bindingContext.$data : null)); }, /** * Binds the view, preserving the existing binding context. Optionally, a new context can be created, parented to the previous context. * @method bind * @param {object} obj The data to bind to. * @param {DOMElement} view The view to bind. */ bind: function(obj, view) { return doBind(obj, view, obj, obj); } }; }); /** * Durandal 2.0.1 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. * Available via the MIT license. * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. */ /** * The activator module encapsulates all logic related to screen/component activation. * An activator is essentially an asynchronous state machine that understands a particular state transition protocol. * The protocol ensures that the following series of events always occur: `canDeactivate` (previous state), `canActivate` (new state), `deactivate` (previous state), `activate` (new state). * Each of the _can_ callbacks may return a boolean, affirmative value or promise for one of those. If either of the _can_ functions yields a false result, then activation halts. * @module activator * @requires system * @requires knockout */ define('durandal/activator',['durandal/system', 'knockout'], function (system, ko) { var activator; function ensureSettings(settings) { if (settings == undefined) { settings = {}; } if (!settings.closeOnDeactivate) { settings.closeOnDeactivate = activator.defaults.closeOnDeactivate; } if (!settings.beforeActivate) { settings.beforeActivate = activator.defaults.beforeActivate; } if (!settings.afterDeactivate) { settings.afterDeactivate = activator.defaults.afterDeactivate; } if(!settings.affirmations){ settings.affirmations = activator.defaults.affirmations; } if (!settings.interpretResponse) { settings.interpretResponse = activator.defaults.interpretResponse; } if (!settings.areSameItem) { settings.areSameItem = activator.defaults.areSameItem; } return settings; } function invoke(target, method, data) { if (system.isArray(data)) { return target[method].apply(target, data); } return target[method](data); } function deactivate(item, close, settings, dfd, setter) { if (item && item.deactivate) { system.log('Deactivating', item); var result; try { result = item.deactivate(close); } catch(error) { system.error(error); dfd.resolve(false); return; } if (result && result.then) { result.then(function() { settings.afterDeactivate(item, close, setter); dfd.resolve(true); }, function(reason) { system.log(reason); dfd.resolve(false); }); } else { settings.afterDeactivate(item, close, setter); dfd.resolve(true); } } else { if (item) { settings.afterDeactivate(item, close, setter); } dfd.resolve(true); } } function activate(newItem, activeItem, callback, activationData) { if (newItem) { if (newItem.activate) { system.log('Activating', newItem); var result; try { result = invoke(newItem, 'activate', activationData); } catch (error) { system.error(error); callback(false); return; } if (result && result.then) { result.then(function() { activeItem(newItem); callback(true); }, function(reason) { system.log(reason); callback(false); }); } else { activeItem(newItem); callback(true); } } else { activeItem(newItem); callback(true); } } else { callback(true); } } function canDeactivateItem(item, close, settings) { settings.lifecycleData = null; return system.defer(function (dfd) { if (item && item.canDeactivate) { var resultOrPromise; try { resultOrPromise = item.canDeactivate(close); } catch(error) { system.error(error); dfd.resolve(false); return; } if (resultOrPromise.then) { resultOrPromise.then(function(result) { settings.lifecycleData = result; dfd.resolve(settings.interpretResponse(result)); }, function(reason) { system.error(reason); dfd.resolve(false); }); } else { settings.lifecycleData = resultOrPromise; dfd.resolve(settings.interpretResponse(resultOrPromise)); } } else { dfd.resolve(true); } }).promise(); }; function canActivateItem(newItem, activeItem, settings, activationData) { settings.lifecycleData = null; return system.defer(function (dfd) { if (newItem == activeItem()) { dfd.resolve(true); return; } if (newItem && newItem.canActivate) { var resultOrPromise; try { resultOrPromise = invoke(newItem, 'canActivate', activationData); } catch (error) { system.error(error); dfd.resolve(false); return; } if (resultOrPromise.then) { resultOrPromise.then(function(result) { settings.lifecycleData = result; dfd.resolve(settings.interpretResponse(result)); }, function(reason) { system.error(reason); dfd.resolve(false); }); } else { settings.lifecycleData = resultOrPromise; dfd.resolve(settings.interpretResponse(resultOrPromise)); } } else { dfd.resolve(true); } }).promise(); }; /** * An activator is a read/write computed observable that enforces the activation lifecycle whenever changing values. * @class Activator */ function createActivator(initialActiveItem, settings) { var activeItem = ko.observable(null); var activeData; settings = ensureSettings(settings); var computed = ko.computed({ read: function () { return activeItem(); }, write: function (newValue) { computed.viaSetter = true; computed.activateItem(newValue); } }); computed.__activator__ = true; /** * The settings for this activator. * @property {ActivatorSettings} settings */ computed.settings = settings; settings.activator = computed; /** * An observable which indicates whether or not the activator is currently in the process of activating an instance. * @method isActivating * @return {boolean} */ computed.isActivating = ko.observable(false); /** * Determines whether or not the specified item can be deactivated. * @method canDeactivateItem * @param {object} item The item to check. * @param {boolean} close Whether or not to check if close is possible. * @return {promise} */ computed.canDeactivateItem = function (item, close) { return canDeactivateItem(item, close, settings); }; /** * Deactivates the specified item. * @method deactivateItem * @param {object} item The item to deactivate. * @param {boolean} close Whether or not to close the item. * @return {promise} */ computed.deactivateItem = function (item, close) { return system.defer(function(dfd) { computed.canDeactivateItem(item, close).then(function(canDeactivate) { if (canDeactivate) { deactivate(item, close, settings, dfd, activeItem); } else { computed.notifySubscribers(); dfd.resolve(false); } }); }).promise(); }; /** * Determines whether or not the specified item can be activated. * @method canActivateItem * @param {object} item The item to check. * @param {object} activationData Data associated with the activation. * @return {promise} */ computed.canActivateItem = function (newItem, activationData) { return canActivateItem(newItem, activeItem, settings, activationData); }; /** * Activates the specified item. * @method activateItem * @param {object} newItem The item to activate. * @param {object} newActivationData Data associated with the activation. * @return {promise} */ computed.activateItem = function (newItem, newActivationData) { var viaSetter = computed.viaSetter; computed.viaSetter = false; return system.defer(function (dfd) { if (computed.isActivating()) { dfd.resolve(false); return; } computed.isActivating(true); var currentItem = activeItem(); if (settings.areSameItem(currentItem, newItem, activeData, newActivationData)) { computed.isActivating(false); dfd.resolve(true); return; } computed.canDeactivateItem(currentItem, settings.closeOnDeactivate).then(function (canDeactivate) { if (canDeactivate) { computed.canActivateItem(newItem, newActivationData).then(function (canActivate) { if (canActivate) { system.defer(function (dfd2) { deactivate(currentItem, settings.closeOnDeactivate, settings, dfd2); }).promise().then(function () { newItem = settings.beforeActivate(newItem, newActivationData); activate(newItem, activeItem, function (result) { activeData = newActivationData; computed.isActivating(false); dfd.resolve(result); }, newActivationData); }); } else { if (viaSetter) { computed.notifySubscribers(); } computed.isActivating(false); dfd.resolve(false); } }); } else { if (viaSetter) { computed.notifySubscribers(); } computed.isActivating(false); dfd.resolve(false); } }); }).promise(); }; /** * Determines whether or not the activator, in its current state, can be activated. * @method canActivate * @return {promise} */ computed.canActivate = function () { var toCheck; if (initialActiveItem) { toCheck = initialActiveItem; initialActiveItem = false; } else { toCheck = computed(); } return computed.canActivateItem(toCheck); }; /** * Activates the activator, in its current state. * @method activate * @return {promise} */ computed.activate = function () { var toActivate; if (initialActiveItem) { toActivate = initialActiveItem; initialActiveItem = false; } else { toActivate = computed(); } return computed.activateItem(toActivate); }; /** * Determines whether or not the activator, in its current state, can be deactivated. * @method canDeactivate * @return {promise} */ computed.canDeactivate = function (close) { return computed.canDeactivateItem(computed(), close); }; /** * Deactivates the activator, in its current state. * @method deactivate * @return {promise} */ computed.deactivate = function (close) { return computed.deactivateItem(computed(), close); }; computed.includeIn = function (includeIn) { includeIn.canActivate = function () { return computed.canActivate(); }; includeIn.activate = function () { return computed.activate(); }; includeIn.canDeactivate = function (close) { return computed.canDeactivate(close); }; includeIn.deactivate = function (close) { return computed.deactivate(close); }; }; if (settings.includeIn) { computed.includeIn(settings.includeIn); } else if (initialActiveItem) { computed.activate(); } computed.forItems = function (items) { settings.closeOnDeactivate = false; settings.determineNextItemToActivate = function (list, lastIndex) { var toRemoveAt = lastIndex - 1; if (toRemoveAt == -1 && list.length > 1) { return list[1]; } if (toRemoveAt > -1 && toRemoveAt < list.length - 1) { return list[toRemoveAt]; } return null; }; settings.beforeActivate = function (newItem) { var currentItem = computed(); if (!newItem) { newItem = settings.determineNextItemToActivate(items, currentItem ? items.indexOf(currentItem) : 0); } else { var index = items.indexOf(newItem); if (index == -1) { items.push(newItem); } else { newItem = items()[index]; } } return newItem; }; settings.afterDeactivate = function (oldItem, close) { if (close) { items.remove(oldItem); } }; var originalCanDeactivate = computed.canDeactivate; computed.canDeactivate = function (close) { if (close) { return system.defer(function (dfd) { var list = items(); var results = []; function finish() { for (var j = 0; j < results.length; j++) { if (!results[j]) { dfd.resolve(false); return; } } dfd.resolve(true); } for (var i = 0; i < list.length; i++) { computed.canDeactivateItem(list[i], close).then(function (result) { results.push(result); if (results.length == list.length) { finish(); } }); } }).promise(); } else { return originalCanDeactivate(); } }; var originalDeactivate = computed.deactivate; computed.deactivate = function (close) { if (close) { return system.defer(function (dfd) { var list = items(); var results = 0; var listLength = list.length; function doDeactivate(item) { computed.deactivateItem(item, close).then(function () { results++; items.remove(item); if (results == listLength) { dfd.resolve(); } }); } for (var i = 0; i < listLength; i++) { doDeactivate(list[i]); } }).promise(); } else { return originalDeactivate(); } }; return computed; }; return computed; } /** * @class ActivatorSettings * @static */ var activatorSettings = { /** * The default value passed to an object's deactivate function as its close parameter. * @property {boolean} closeOnDeactivate * @default true */ closeOnDeactivate: true, /** * Lower-cased words which represent a truthy value. * @property {string[]} affirmations * @default ['yes', 'ok', 'true'] */ affirmations: ['yes', 'ok', 'true'], /** * Interprets the response of a `canActivate` or `canDeactivate` call using the known affirmative values in the `affirmations` array. * @method interpretResponse * @param {object} value * @return {boolean} */ interpretResponse: function(value) { if(system.isObject(value)) { value = value.can || false; } if(system.isString(value)) { return ko.utils.arrayIndexOf(this.affirmations, value.toLowerCase()) !== -1; } return value; }, /** * Determines whether or not the current item and the new item are the same. * @method areSameItem * @param {object} currentItem * @param {object} newItem * @param {object} currentActivationData * @param {object} newActivationData * @return {boolean} */ areSameItem: function(currentItem, newItem, currentActivationData, newActivationData) { return currentItem == newItem; }, /** * Called immediately before the new item is activated. * @method beforeActivate * @param {object} newItem */ beforeActivate: function(newItem) { return newItem; }, /** * Called immediately after the old item is deactivated. * @method afterDeactivate * @param {object} oldItem The previous item. * @param {boolean} close Whether or not the previous item was closed. * @param {function} setter The activate item setter function. */ afterDeactivate: function(oldItem, close, setter) { if(close && setter) { setter(null); } } }; /** * @class ActivatorModule * @static */ activator = { /** * The default settings used by activators. * @property {ActivatorSettings} defaults */ defaults: activatorSettings, /** * Creates a new activator. * @method create * @param {object} [initialActiveItem] The item which should be immediately activated upon creation of the ativator. * @param {ActivatorSettings} [settings] Per activator overrides of the default activator settings. * @return {Activator} The created activator. */ create: createActivator, /** * Determines whether or not the provided object is an activator or not. * @method isActivator * @param {object} object Any object you wish to verify as an activator or not. * @return {boolean} True if the object is an activator; false otherwise. */ isActivator:function(object){ return object && object.__activator__; } }; return activator; }); /** * Durandal 2.0.1 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. * Available via the MIT license. * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. */ /** * The composition module encapsulates all functionality related to visual composition. * @module composition * @requires system * @requires viewLocator * @requires binder * @requires viewEngine * @requires activator * @requires jquery * @requires knockout */ define('durandal/composition',['durandal/system', 'durandal/viewLocator', 'durandal/binder', 'durandal/viewEngine', 'durandal/activator', 'jquery', 'knockout'], function (system, viewLocator, binder, viewEngine, activator, $, ko) { var dummyModel = {}, activeViewAttributeName = 'data-active-view', composition, compositionCompleteCallbacks = [], compositionCount = 0, compositionDataKey = 'durandal-composition-data', partAttributeName = 'data-part', bindableSettings = ['model', 'view', 'transition', 'area', 'strategy', 'activationData'], visibilityKey = "durandal-visibility-data", composeBindings = ['compose:']; function getHostState(parent) { var elements = []; var state = { childElements: elements, activeView: null }; var child = ko.virtualElements.firstChild(parent); while (child) { if (child.nodeType == 1) { elements.push(child); if (child.getAttribute(activeViewAttributeName)) { state.activeView = child; } } child = ko.virtualElements.nextSibling(child); } if(!state.activeView){ state.activeView = elements[0]; } return state; } function endComposition() { compositionCount--; if (compositionCount === 0) { setTimeout(function(){ var i = compositionCompleteCallbacks.length; while(i--) { try{ compositionCompleteCallbacks[i](); }catch(e){ system.error(e); } } compositionCompleteCallbacks = []; }, 1); } } function cleanUp(context){ delete context.activeView; delete context.viewElements; } function tryActivate(context, successCallback, skipActivation) { if(skipActivation){ successCallback(); } else if (context.activate && context.model && context.model.activate) { var result; try{ if(system.isArray(context.activationData)) { result = context.model.activate.apply(context.model, context.activationData); } else { result = context.model.activate(context.activationData); } if(result && result.then) { result.then(successCallback, function(reason) { system.error(reason); successCallback(); }); } else if(result || result === undefined) { successCallback(); } else { endComposition(); cleanUp(context); } } catch(e){ system.error(e); } } else { successCallback(); } } function triggerAttach() { var context = this; if (context.activeView) { context.activeView.removeAttribute(activeViewAttributeName); } if (context.child) { try{ if (context.model && context.model.attached) { if (context.composingNewView || context.alwaysTriggerAttach) { context.model.attached(context.child, context.parent, context); } } if (context.attached) { context.attached(context.child, context.parent, context); } context.child.setAttribute(activeViewAttributeName, true); if (context.composingNewView && context.model && context.model.detached) { ko.utils.domNodeDisposal.addDisposeCallback(context.child, function () { try{ context.model.detached(context.child, context.parent, context); }catch(e2){ system.error(e2); } }); } }catch(e){ system.error(e); } } context.triggerAttach = system.noop; } function shouldTransition(context) { if (system.isString(context.transition)) { if (context.activeView) { if (context.activeView == context.child) { return false; } if (!context.child) { return true; } if (context.skipTransitionOnSameViewId) { var currentViewId = context.activeView.getAttribute('data-view'); var newViewId = context.child.getAttribute('data-view'); return currentViewId != newViewId; } } return true; } return false; } function cloneNodes(nodesArray) { for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) { var clonedNode = nodesArray[i].cloneNode(true); newNodesArray.push(clonedNode); } return newNodesArray; } function replaceParts(context){ var parts = cloneNodes(context.parts); var replacementParts = composition.getParts(parts, null, true); var standardParts = composition.getParts(context.child); for (var partId in replacementParts) { $(standardParts[partId]).replaceWith(replacementParts[partId]); } } function removePreviousView(context){ var children = ko.virtualElements.childNodes(context.parent), i, len; if(!system.isArray(children)){ var arrayChildren = []; for(i = 0, len = children.length; i < len; i++){ arrayChildren[i] = children[i]; } children = arrayChildren; } for(i = 1,len = children.length; i < len; i++){ ko.removeNode(children[i]); } } function hide(view) { ko.utils.domData.set(view, visibilityKey, view.style.display); view.style.display = "none"; } function show(view) { view.style.display = ko.utils.domData.get(view, visibilityKey); } function hasComposition(element){ var dataBind = element.getAttribute('data-bind'); if(!dataBind){ return false; } for(var i = 0, length = composeBindings.length; i < length; i++){ if(dataBind.indexOf(composeBindings[i]) > -1){ return true; } } return false; } /** * @class CompositionTransaction * @static */ var compositionTransaction = { /** * Registers a callback which will be invoked when the current composition transaction has completed. The transaction includes all parent and children compositions. * @method complete * @param {function} callback The callback to be invoked when composition is complete. */ complete: function (callback) { compositionCompleteCallbacks.push(callback); } }; /** * @class CompositionModule * @static */ composition = { /** * An array of all the binding handler names (includeing :) that trigger a composition. * @property {string} composeBindings * @default ['compose:'] */ composeBindings:composeBindings, /** * Converts a transition name to its moduleId. * @method convertTransitionToModuleId * @param {string} name The name of the transtion. * @return {string} The moduleId. */ convertTransitionToModuleId: function (name) { return 'transitions/' + name; }, /** * The name of the transition to use in all compositions. * @property {string} defaultTransitionName * @default null */ defaultTransitionName: null, /** * Represents the currently executing composition transaction. * @property {CompositionTransaction} current */ current: compositionTransaction, /** * Registers a binding handler that will be invoked when the current composition transaction is complete. * @method addBindingHandler * @param {string} name The name of the binding handler. * @param {object} [config] The binding handler instance. If none is provided, the name will be used to look up an existing handler which will then be converted to a composition handler. * @param {function} [initOptionsFactory] If the registered binding needs to return options from its init call back to knockout, this function will server as a factory for those options. It will receive the same parameters that the init function does. */ addBindingHandler:function(name, config, initOptionsFactory){ var key, dataKey = 'composition-handler-' + name, handler; config = config || ko.bindingHandlers[name]; initOptionsFactory = initOptionsFactory || function(){ return undefined; }; handler = ko.bindingHandlers[name] = { init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { if(compositionCount > 0){ var data = { trigger:ko.observable(null) }; composition.current.complete(function(){ if(config.init){ config.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); } if(config.update){ ko.utils.domData.set(element, dataKey, config); data.trigger('trigger'); } }); ko.utils.domData.set(element, dataKey, data); }else{ ko.utils.domData.set(element, dataKey, config); if(config.init){ config.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); } } return initOptionsFactory(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); }, update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var data = ko.utils.domData.get(element, dataKey); if(data.update){ return data.update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); } if(data.trigger){ data.trigger(); } } }; for (key in config) { if (key !== "init" && key !== "update") { handler[key] = config[key]; } } }, /** * Gets an object keyed with all the elements that are replacable parts, found within the supplied elements. The key will be the part name and the value will be the element itself. * @method getParts * @param {DOMElement\DOMElement[]} elements The element(s) to search for parts. * @return {object} An object keyed by part. */ getParts: function(elements, parts, isReplacementSearch) { parts = parts || {}; if (!elements) { return parts; } if (elements.length === undefined) { elements = [elements]; } for (var i = 0, length = elements.length; i < length; i++) { var element = elements[i]; if (element.getAttribute) { if(!isReplacementSearch && hasComposition(element)){ continue; } var id = element.getAttribute(partAttributeName); if (id) { parts[id] = element; } if(!isReplacementSearch && element.hasChildNodes()){ composition.getParts(element.childNodes, parts); } } } return parts; }, cloneNodes:cloneNodes, finalize: function (context) { if(context.transition === undefined) { context.transition = this.defaultTransitionName; } if(!context.child && !context.activeView){ if (!context.cacheViews) { ko.virtualElements.emptyNode(context.parent); } context.triggerAttach(); endComposition(); cleanUp(context); }else if (shouldTransition(context)) { var transitionModuleId = this.convertTransitionToModuleId(context.transition); system.acquire(transitionModuleId).then(function (transition) { context.transition = transition; transition(context).then(function () { if (!context.cacheViews) { if(!context.child){ ko.virtualElements.emptyNode(context.parent); }else{ removePreviousView(context); } }else if(context.activeView){ var instruction = binder.getBindingInstruction(context.activeView); if(instruction && instruction.cacheViews != undefined && !instruction.cacheViews){ ko.removeNode(context.activeView); } } context.triggerAttach(); endComposition(); cleanUp(context); }); }).fail(function(err){ system.error('Failed to load transition (' + transitionModuleId + '). Details: ' + err.message); }); } else { if (context.child != context.activeView) { if (context.cacheViews && context.activeView) { var instruction = binder.getBindingInstruction(context.activeView); if(!instruction || (instruction.cacheViews != undefined && !instruction.cacheViews)){ ko.removeNode(context.activeView); }else{ hide(context.activeView); } } if (!context.child) { if (!context.cacheViews) { ko.virtualElements.emptyNode(context.parent); } } else { if (!context.cacheViews) { removePreviousView(context); } show(context.child); } } context.triggerAttach(); endComposition(); cleanUp(context); } }, bindAndShow: function (child, context, skipActivation) { context.child = child; if (context.cacheViews) { context.composingNewView = (ko.utils.arrayIndexOf(context.viewElements, child) == -1); } else { context.composingNewView = true; } tryActivate(context, function () { if (context.binding) { context.binding(context.child, context.parent, context); } if (context.preserveContext && context.bindingContext) { if (context.composingNewView) { if(context.parts){ replaceParts(context); } hide(child); ko.virtualElements.prepend(context.parent, child); binder.bindContext(context.bindingContext, child, context.model); } } else if (child) { var modelToBind = context.model || dummyModel; var currentModel = ko.dataFor(child); if (currentModel != modelToBind) { if (!context.composingNewView) { ko.removeNode(child); viewEngine.createView(child.getAttribute('data-view')).then(function(recreatedView) { composition.bindAndShow(recreatedView, context, true); }); return; } if(context.parts){ replaceParts(context); } hide(child); ko.virtualElements.prepend(context.parent, child); binder.bind(modelToBind, child); } } composition.finalize(context); }, skipActivation); }, /** * Eecutes the default view location strategy. * @method defaultStrategy * @param {object} context The composition context containing the model and possibly existing viewElements. * @return {promise} A promise for the view. */ defaultStrategy: function (context) { return viewLocator.locateViewForObject(context.model, context.area, context.viewElements); }, getSettings: function (valueAccessor, element) { var value = valueAccessor(), settings = ko.utils.unwrapObservable(value) || {}, activatorPresent = activator.isActivator(value), moduleId; if (system.isString(settings)) { if (viewEngine.isViewUrl(settings)) { settings = { view: settings }; } else { settings = { model: settings, activate: true }; } return settings; } moduleId = system.getModuleId(settings); if (moduleId) { settings = { model: settings, activate: true }; return settings; } if(!activatorPresent && settings.model) { activatorPresent = activator.isActivator(settings.model); } for (var attrName in settings) { if (ko.utils.arrayIndexOf(bindableSettings, attrName) != -1) { settings[attrName] = ko.utils.unwrapObservable(settings[attrName]); } else { settings[attrName] = settings[attrName]; } } if (activatorPresent) { settings.activate = false; } else if (settings.activate === undefined) { settings.activate = true; } return settings; }, executeStrategy: function (context) { context.strategy(context).then(function (child) { composition.bindAndShow(child, context); }); }, inject: function (context) { if (!context.model) { this.bindAndShow(null, context); return; } if (context.view) { viewLocator.locateView(context.view, context.area, context.viewElements).then(function (child) { composition.bindAndShow(child, context); }); return; } if (!context.strategy) { context.strategy = this.defaultStrategy; } if (system.isString(context.strategy)) { system.acquire(context.strategy).then(function (strategy) { context.strategy = strategy; composition.executeStrategy(context); }).fail(function(err){ system.error('Failed to load view strategy (' + context.strategy + '). Details: ' + err.message); }); } else { this.executeStrategy(context); } }, /** * Initiates a composition. * @method compose * @param {DOMElement} element The DOMElement or knockout virtual element that serves as the parent for the composition. * @param {object} settings The composition settings. * @param {object} [bindingContext] The current binding context. */ compose: function (element, settings, bindingContext, fromBinding) { compositionCount++; if(!fromBinding){ settings = composition.getSettings(function() { return settings; }, element); } if (settings.compositionComplete) { compositionCompleteCallbacks.push(function () { settings.compositionComplete(settings.child, settings.parent, settings); }); } compositionCompleteCallbacks.push(function () { if(settings.composingNewView && settings.model && settings.model.compositionComplete){ settings.model.compositionComplete(settings.child, settings.parent, settings); } }); var hostState = getHostState(element); settings.activeView = hostState.activeView; settings.parent = element; settings.triggerAttach = triggerAttach; settings.bindingContext = bindingContext; if (settings.cacheViews && !settings.viewElements) { settings.viewElements = hostState.childElements; } if (!settings.model) { if (!settings.view) { this.bindAndShow(null, settings); } else { settings.area = settings.area || 'partial'; settings.preserveContext = true; viewLocator.locateView(settings.view, settings.area, settings.viewElements).then(function (child) { composition.bindAndShow(child, settings); }); } } else if (system.isString(settings.model)) { system.acquire(settings.model).then(function (module) { settings.model = system.resolveObject(module); composition.inject(settings); }).fail(function(err){ system.error('Failed to load composed module (' + settings.model + '). Details: ' + err.message); }); } else { composition.inject(settings); } } }; ko.bindingHandlers.compose = { init: function() { return { controlsDescendantBindings: true }; }, update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var settings = composition.getSettings(valueAccessor, element); if(settings.mode){ var data = ko.utils.domData.get(element, compositionDataKey); if(!data){ var childNodes = ko.virtualElements.childNodes(element); data = {}; if(settings.mode === 'inline'){ data.view = viewEngine.ensureSingleElement(childNodes); }else if(settings.mode === 'templated'){ data.parts = cloneNodes(childNodes); } ko.virtualElements.emptyNode(element); ko.utils.domData.set(element, compositionDataKey, data); } if(settings.mode === 'inline'){ settings.view = data.view.cloneNode(true); }else if(settings.mode === 'templated'){ settings.parts = data.parts; } settings.preserveContext = true; } composition.compose(element, settings, bindingContext, true); } }; ko.virtualElements.allowedBindings.compose = true; return composition; }); /** * Durandal 2.0.1 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. * Available via the MIT license. * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. */ /** * Durandal events originate from backbone.js but also combine some ideas from signals.js as well as some additional improvements. * Events can be installed into any object and are installed into the `app` module by default for convenient app-wide eventing. * @module events * @requires system */ define('durandal/events',['durandal/system'], function (system) { var eventSplitter = /\s+/; var Events = function() { }; /** * Represents an event subscription. * @class Subscription */ var Subscription = function(owner, events) { this.owner = owner; this.events = events; }; /** * Attaches a callback to the event subscription. * @method then * @param {function} callback The callback function to invoke when the event is triggered. * @param {object} [context] An object to use as `this` when invoking the `callback`. * @chainable */ Subscription.prototype.then = function (callback, context) { this.callback = callback || this.callback; this.context = context || this.context; if (!this.callback) { return this; } this.owner.on(this.events, this.callback, this.context); return this; }; /** * Attaches a callback to the event subscription. * @method on * @param {function} [callback] The callback function to invoke when the event is triggered. If `callback` is not provided, the previous callback will be re-activated. * @param {object} [context] An object to use as `this` when invoking the `callback`. * @chainable */ Subscription.prototype.on = Subscription.prototype.then; /** * Cancels the subscription. * @method off * @chainable */ Subscription.prototype.off = function () { this.owner.off(this.events, this.callback, this.context); return this; }; /** * Creates an object with eventing capabilities. * @class Events */ /** * Creates a subscription or registers a callback for the specified event. * @method on * @param {string} events One or more events, separated by white space. * @param {function} [callback] The callback function to invoke when the event is triggered. If `callback` is not provided, a subscription instance is returned. * @param {object} [context] An object to use as `this` when invoking the `callback`. * @return {Subscription|Events} A subscription is returned if no callback is supplied, otherwise the events object is returned for chaining. */ Events.prototype.on = function(events, callback, context) { var calls, event, list; if (!callback) { return new Subscription(this, events); } else { calls = this.callbacks || (this.callbacks = {}); events = events.split(eventSplitter); while (event = events.shift()) { list = calls[event] || (calls[event] = []); list.push(callback, context); } return this; } }; /** * Removes the callbacks for the specified events. * @method off * @param {string} [events] One or more events, separated by white space to turn off. If no events are specified, then the callbacks will be removed. * @param {function} [callback] The callback function to remove. If `callback` is not provided, all callbacks for the specified events will be removed. * @param {object} [context] The object that was used as `this`. Callbacks with this context will be removed. * @chainable */ Events.prototype.off = function(events, callback, context) { var event, calls, list, i; // No events if (!(calls = this.callbacks)) { return this; } //removing all if (!(events || callback || context)) { delete this.callbacks; return this; } events = events ? events.split(eventSplitter) : system.keys(calls); // Loop through the callback list, splicing where appropriate. while (event = events.shift()) { if (!(list = calls[event]) || !(callback || context)) { delete calls[event]; continue; } for (i = list.length - 2; i >= 0; i -= 2) { if (!(callback && list[i] !== callback || context && list[i + 1] !== context)) { list.splice(i, 2); } } } return this; }; /** * Triggers the specified events. * @method trigger * @param {string} [events] One or more events, separated by white space to trigger. * @chainable */ Events.prototype.trigger = function(events) { var event, calls, list, i, length, args, all, rest; if (!(calls = this.callbacks)) { return this; } rest = []; events = events.split(eventSplitter); for (i = 1, length = arguments.length; i < length; i++) { rest[i - 1] = arguments[i]; } // For each event, walk through the list of callbacks twice, first to // trigger the event, then to trigger any `"all"` callbacks. while (event = events.shift()) { // Copy callback lists to prevent modification. if (all = calls.all) { all = all.slice(); } if (list = calls[event]) { list = list.slice(); } // Execute event callbacks. if (list) { for (i = 0, length = list.length; i < length; i += 2) { list[i].apply(list[i + 1] || this, rest); } } // Execute "all" callbacks. if (all) { args = [event].concat(rest); for (i = 0, length = all.length; i < length; i += 2) { all[i].apply(all[i + 1] || this, args); } } } return this; }; /** * Creates a function that will trigger the specified events when called. Simplifies proxying jQuery (or other) events through to the events object. * @method proxy * @param {string} events One or more events, separated by white space to trigger by invoking the returned function. * @return {function} Calling the function will invoke the previously specified events on the events object. */ Events.prototype.proxy = function(events) { var that = this; return (function(arg) { that.trigger(events, arg); }); }; /** * Creates an object with eventing capabilities. * @class EventsModule * @static */ /** * Adds eventing capabilities to the specified object. * @method includeIn * @param {object} targetObject The object to add eventing capabilities to. */ Events.includeIn = function(targetObject) { targetObject.on = Events.prototype.on; targetObject.off = Events.prototype.off; targetObject.trigger = Events.prototype.trigger; targetObject.proxy = Events.prototype.proxy; }; return Events; }); /** * Durandal 2.0.1 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. * Available via the MIT license. * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. */ /** * The app module controls app startup, plugin loading/configuration and root visual display. * @module app * @requires system * @requires viewEngine * @requires composition * @requires events * @requires jquery */ define('durandal/app',['durandal/system', 'durandal/viewEngine', 'durandal/composition', 'durandal/events', 'jquery'], function(system, viewEngine, composition, Events, $) { var app, allPluginIds = [], allPluginConfigs = []; function loadPlugins(){ return system.defer(function(dfd){ if(allPluginIds.length == 0){ dfd.resolve(); return; } system.acquire(allPluginIds).then(function(loaded){ for(var i = 0; i < loaded.length; i++){ var currentModule = loaded[i]; if(currentModule.install){ var config = allPluginConfigs[i]; if(!system.isObject(config)){ config = {}; } currentModule.install(config); system.log('Plugin:Installed ' + allPluginIds[i]); }else{ system.log('Plugin:Loaded ' + allPluginIds[i]); } } dfd.resolve(); }).fail(function(err){ system.error('Failed to load plugin(s). Details: ' + err.message); }); }).promise(); } /** * @class AppModule * @static * @uses Events */ app = { /** * The title of your application. * @property {string} title */ title: 'Application', /** * Configures one or more plugins to be loaded and installed into the application. * @method configurePlugins * @param {object} config Keys are plugin names. Values can be truthy, to simply install the plugin, or a configuration object to pass to the plugin. * @param {string} [baseUrl] The base url to load the plugins from. */ configurePlugins:function(config, baseUrl){ var pluginIds = system.keys(config); baseUrl = baseUrl || 'plugins/'; if(baseUrl.indexOf('/', baseUrl.length - 1) === -1){ baseUrl += '/'; } for(var i = 0; i < pluginIds.length; i++){ var key = pluginIds[i]; allPluginIds.push(baseUrl + key); allPluginConfigs.push(config[key]); } }, /** * Starts the application. * @method start * @return {promise} */ start: function() { system.log('Application:Starting'); if (this.title) { document.title = this.title; } return system.defer(function (dfd) { $(function() { loadPlugins().then(function(){ dfd.resolve(); system.log('Application:Started'); }); }); }).promise(); }, /** * Sets the root module/view for the application. * @method setRoot * @param {string} root The root view or module. * @param {string} [transition] The transition to use from the previous root (or splash screen) into the new root. * @param {string} [applicationHost] The application host element or id. By default the id 'applicationHost' will be used. */ setRoot: function(root, transition, applicationHost) { var hostElement, settings = { activate:true, transition: transition }; if (!applicationHost || system.isString(applicationHost)) { hostElement = document.getElementById(applicationHost || 'applicationHost'); } else { hostElement = applicationHost; } if (system.isString(root)) { if (viewEngine.isViewUrl(root)) { settings.view = root; } else { settings.model = root; } } else { settings.model = root; } composition.compose(hostElement, settings); } }; Events.includeIn(app); return app; }); requirejs.config({ paths: { 'text': '../bower_components/requirejs-text/text', 'durandal':'../bower_components/durandal/js', 'plugins' : '../bower_components/durandal/js/plugins', 'knockout': '../bower_components/knockout.js/knockout', 'jquery': '../bower_components/jquery/jquery' }, shim: { 'bootstrap': { deps: ['jquery'], exports: 'jQuery' } } }); define('main',['durandal/system', 'durandal/app', 'durandal/viewLocator'], function (system, app, viewLocator) { app.title = 'Durandal Simple Project'; app.start().then(function () { //Replace 'viewmodels' in the moduleId with 'views' to locate the view. //Look for partial views in a 'views' folder in the root. viewLocator.useConvention(); //Show the app by setting the root view model for our application. app.setRoot('shell'); }); }); /** * Durandal 2.0.1 Copyright (c) 2012 Blue Spire Consulting, Inc. All Rights Reserved. * Available via the MIT license. * see: http://durandaljs.com or https://github.com/BlueSpire/Durandal for details. */ /** * The dialog module enables the display of message boxes, custom modal dialogs and other overlays or slide-out UI abstractions. Dialogs are constructed by the composition system which interacts with a user defined dialog context. The dialog module enforced the activator lifecycle. * @module dialog * @requires system * @requires app * @requires composition * @requires activator * @requires viewEngine * @requires jquery * @requires knockout */ define('plugins/dialog',['durandal/system', 'durandal/app', 'durandal/composition', 'durandal/activator', 'durandal/viewEngine', 'jquery', 'knockout'], function (system, app, composition, activator, viewEngine, $, ko) { var contexts = {}, dialogCount = 0, dialog; /** * Models a message box's message, title and options. * @class MessageBox */ var MessageBox = function(message, title, options) { this.message = message; this.title = title || MessageBox.defaultTitle; this.options = options || MessageBox.defaultOptions; }; /** * Selects an option and closes the message box, returning the selected option through the dialog system's promise. * @method selectOption * @param {string} dialogResult The result to select. */ MessageBox.prototype.selectOption = function (dialogResult) { dialog.close(this, dialogResult); }; /** * Provides the view to the composition system. * @method getView * @return {DOMElement} The view of the message box. */ MessageBox.prototype.getView = function(){ return viewEngine.processMarkup(MessageBox.defaultViewMarkup); }; /** * Configures a custom view to use when displaying message boxes. * @method setViewUrl * @param {string} viewUrl The view url relative to the base url which the view locator will use to find the message box's view. * @static */ MessageBox.setViewUrl = function(viewUrl){ delete MessageBox.prototype.getView; MessageBox.prototype.viewUrl = viewUrl; }; /** * The title to be used for the message box if one is not provided. * @property {string} defaultTitle * @default Application * @static */ MessageBox.defaultTitle = app.title || 'Application'; /** * The options to display in the message box of none are specified. * @property {string[]} defaultOptions * @default ['Ok'] * @static */ MessageBox.defaultOptions = ['Ok']; /** * The markup for the message box's view. * @property {string} defaultViewMarkup * @static */ MessageBox.defaultViewMarkup = [ '<div data-view="plugins/messageBox" class="messageBox">', '<div class="modal-header">', '<h3 data-bind="text: title"></h3>', '</div>', '<div class="modal-body">', '<p class="message" data-bind="text: message"></p>', '</div>', '<div class="modal-footer" data-bind="foreach: options">', '<button class="btn" data-bind="click: function () { $parent.selectOption($data); }, text: $data, css: { \'btn-primary\': $index() == 0, autofocus: $index() == 0 }"></button>', '</div>', '</div>' ].join('\n'); function ensureDialogInstance(objOrModuleId) { return system.defer(function(dfd) { if (system.isString(objOrModuleId)) { system.acquire(objOrModuleId).then(function (module) { dfd.resolve(system.resolveObject(module)); }).fail(function(err){ system.error('Failed to load dialog module (' + objOrModuleId + '). Details: ' + err.message); }); } else { dfd.resolve(objOrModuleId); } }).promise(); } /** * @class DialogModule * @static */ dialog = { /** * The constructor function used to create message boxes. * @property {MessageBox} MessageBox */ MessageBox:MessageBox, /** * The css zIndex that the last dialog was displayed at. * @property {number} currentZIndex */ currentZIndex: 1050, /** * Gets the next css zIndex at which a dialog should be displayed. * @method getNextZIndex * @return {number} The next usable zIndex. */ getNextZIndex: function () { return ++this.currentZIndex; }, /** * Determines whether or not there are any dialogs open. * @method isOpen * @return {boolean} True if a dialog is open. false otherwise. */ isOpen: function() { return dialogCount > 0; }, /** * Gets the dialog context by name or returns the default context if no name is specified. * @method getContext * @param {string} [name] The name of the context to retrieve. * @return {DialogContext} True context. */ getContext: function(name) { return contexts[name || 'default']; }, /** * Adds (or replaces) a dialog context. * @method addContext * @param {string} name The name of the context to add. * @param {DialogContext} dialogContext The context to add. */ addContext: function(name, dialogContext) { dialogContext.name = name; contexts[name] = dialogContext; var helperName = 'show' + name.substr(0, 1).toUpperCase() + name.substr(1); this[helperName] = function (obj, activationData) { return this.show(obj, activationData, name); }; }, createCompositionSettings: function(obj, dialogContext) { var settings = { model:obj, activate:false, transition: false }; if (dialogContext.attached) { settings.attached = dialogContext.attached; } if (dialogContext.compositionComplete) { settings.compositionComplete = dialogContext.compositionComplete; } return settings; }, /** * Gets the dialog model that is associated with the specified object. * @method getDialog * @param {object} obj The object for whom to retrieve the dialog. * @return {Dialog} The dialog model. */ getDialog:function(obj){ if(obj){ return obj.__dialog__; } return undefined; }, /** * Closes the dialog associated with the specified object. * @method close * @param {object} obj The object whose dialog should be closed. * @param {object} results* The results to return back to the dialog caller after closing. */ close:function(obj){ var theDialog = this.getDialog(obj); if(theDialog){ var rest = Array.prototype.slice.call(arguments, 1); theDialog.close.apply(theDialog, rest); } }, /** * Shows a dialog. * @method show * @param {object|string} obj The object (or moduleId) to display as a dialog. * @param {object} [activationData] The data that should be passed to the object upon activation. * @param {string} [context] The name of the dialog context to use. Uses the default context if none is specified. * @return {Promise} A promise that resolves when the dialog is closed and returns any data passed at the time of closing. */ show: function(obj, activationData, context) { var that = this; var dialogContext = contexts[context || 'default']; return system.defer(function(dfd) { ensureDialogInstance(obj).then(function(instance) { var dialogActivator = activator.create(); dialogActivator.activateItem(instance, activationData).then(function (success) { if (success) { var theDialog = instance.__dialog__ = { owner: instance, context: dialogContext, activator: dialogActivator, close: function () { var args = arguments; dialogActivator.deactivateItem(instance, true).then(function (closeSuccess) { if (closeSuccess) { dialogCount--; dialogContext.removeHost(theDialog); delete instance.__dialog__; if (args.length === 0) { dfd.resolve(); } else if (args.length === 1) { dfd.resolve(args[0]); } else { dfd.resolve.apply(dfd, args); } } }); } }; theDialog.settings = that.createCompositionSettings(instance, dialogContext); dialogContext.addHost(theDialog); dialogCount++; composition.compose(theDialog.host, theDialog.settings); } else { dfd.resolve(false); } }); }); }).promise(); }, /** * Shows a message box. * @method showMessage * @param {string} message The message to display in the dialog. * @param {string} [title] The title message. * @param {string[]} [options] The options to provide to the user. * @return {Promise} A promise that resolves when the message box is closed and returns the selected option. */ showMessage:function(message, title, options){ if(system.isString(this.MessageBox)){ return dialog.show(this.MessageBox, [ message, title || MessageBox.defaultTitle, options || MessageBox.defaultOptions ]); } return dialog.show(new this.MessageBox(message, title, options)); }, /** * Installs this module into Durandal; called by the framework. Adds `app.showDialog` and `app.showMessage` convenience methods. * @method install * @param {object} [config] Add a `messageBox` property to supply a custom message box constructor. Add a `messageBoxView` property to supply custom view markup for the built-in message box. */ install:function(config){ app.showDialog = function(obj, activationData, context) { return dialog.show(obj, activationData, context); }; app.showMessage = function(message, title, options) { return dialog.showMessage(message, title, options); }; if(config.messageBox){ dialog.MessageBox = config.messageBox; } if(config.messageBoxView){ dialog.MessageBox.prototype.getView = function(){ return config.messageBoxView; }; } } }; /** * @class DialogContext */ dialog.addContext('default', { blockoutOpacity: .2, removeDelay: 200, /** * In this function, you are expected to add a DOM element to the tree which will serve as the "host" for the modal's composed view. You must add a property called host to the modalWindow object which references the dom element. It is this host which is passed to the composition module. * @method addHost * @param {Dialog} theDialog The dialog model. */ addHost: function(theDialog) { var body = $('body'); var blockout = $('<div class="modalBlockout"></div>') .css({ 'z-index': dialog.getNextZIndex(), 'opacity': this.blockoutOpacity }) .appendTo(body); var host = $('<div class="modalHost"></div>') .css({ 'z-index': dialog.getNextZIndex() }) .appendTo(body); theDialog.host = host.get(0); theDialog.blockout = blockout.get(0); if (!dialog.isOpen()) { theDialog.oldBodyMarginRight = body.css("margin-right"); theDialog.oldInlineMarginRight = body.get(0).style.marginRight; var html = $("html"); var oldBodyOuterWidth = body.outerWidth(true); var oldScrollTop = html.scrollTop(); $("html").css("overflow-y", "hidden"); var newBodyOuterWidth = $("body").outerWidth(true); body.css("margin-right", (newBodyOuterWidth - oldBodyOuterWidth + parseInt(theDialog.oldBodyMarginRight, 10)) + "px"); html.scrollTop(oldScrollTop); // necessary for Firefox } }, /** * This function is expected to remove any DOM machinery associated with the specified dialog and do any other necessary cleanup. * @method removeHost * @param {Dialog} theDialog The dialog model. */ removeHost: function(theDialog) { $(theDialog.host).css('opacity', 0); $(theDialog.blockout).css('opacity', 0); setTimeout(function() { ko.removeNode(theDialog.host); ko.removeNode(theDialog.blockout); }, this.removeDelay); if (!dialog.isOpen()) { var html = $("html"); var oldScrollTop = html.scrollTop(); // necessary for Firefox. html.css("overflow-y", "").scrollTop(oldScrollTop); if(theDialog.oldInlineMarginRight) { $("body").css("margin-right", theDialog.oldBodyMarginRight); } else { $("body").css("margin-right", ''); } } }, attached: function (view) { //To prevent flickering in IE8, we set visibility to hidden first, and later restore it $(view).css("visibility", "hidden"); }, /** * This function is called after the modal is fully composed into the DOM, allowing your implementation to do any final modifications, such as positioning or animation. You can obtain the original dialog object by using `getDialog` on context.model. * @method compositionComplete * @param {DOMElement} child The dialog view. * @param {DOMElement} parent The parent view. * @param {object} context The composition context. */ compositionComplete: function (child, parent, context) { var theDialog = dialog.getDialog(context.model); var $child = $(child); var loadables = $child.find("img").filter(function () { //Remove images with known width and height var $this = $(this); return !(this.style.width && this.style.height) && !($this.attr("width") && $this.attr("height")); }); $child.data("predefinedWidth", $child.get(0).style.width); var setDialogPosition = function () { //Setting a short timeout is need in IE8, otherwise we could do this straight away setTimeout(function () { //We will clear and then set width for dialogs without width set if (!$child.data("predefinedWidth")) { $child.css({ width: '' }); //Reset width } var width = $child.outerWidth(false); var height = $child.outerHeight(false); var windowHeight = $(window).height(); var constrainedHeight = Math.min(height, windowHeight); $child.css({ 'margin-top': (-constrainedHeight / 2).toString() + 'px', 'margin-left': (-width / 2).toString() + 'px' }); if (!$child.data("predefinedWidth")) { //Ensure the correct width after margin-left has been set $child.outerWidth(width); } if (height > windowHeight) { $child.css("overflow-y", "auto"); } else { $child.css("overflow-y", ""); } $(theDialog.host).css('opacity', 1); $child.css("visibility", "visible"); $child.find('.autofocus').first().focus(); }, 1); }; setDialogPosition(); loadables.load(setDialogPosition); if ($child.hasClass('autoclose')) { $(theDialog.blockout).click(function () { theDialog.close(); }); } } }); return dialog; }); define('shell',['require','knockout','plugins/dialog'],function (require) { var ko = require('knockout'), dialog = require('plugins/dialog'); return { name: ko.observable(), sayHello: function() { dialog.showMessage('Hello ' + this.name() + '! Nice to meet you.', 'Greetings'); } }; }); /** * @license RequireJS text 2.0.3 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/requirejs/text for details */ /*jslint regexp: true */ /*global require: false, XMLHttpRequest: false, ActiveXObject: false, define: false, window: false, process: false, Packages: false, java: false, location: false */ define('text',['module'], function (module) { var text, fs, progIds = ['Msxml2.XMLHTTP', 'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.4.0'], xmlRegExp = /^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, bodyRegExp = /<body[^>]*>\s*([\s\S]+)\s*<\/body>/im, hasLocation = typeof location !== 'undefined' && location.href, defaultProtocol = hasLocation && location.protocol && location.protocol.replace(/\:/, ''), defaultHostName = hasLocation && location.hostname, defaultPort = hasLocation && (location.port || undefined), buildMap = [], masterConfig = (module.config && module.config()) || {}; text = { version: '2.0.3', strip: function (content) { //Strips <?xml ...?> declarations so that external SVG and XML //documents can be added to a document without worry. Also, if the string //is an HTML document, only the part inside the body tag is returned. if (content) { content = content.replace(xmlRegExp, ""); var matches = content.match(bodyRegExp); if (matches) { content = matches[1]; } } else { content = ""; } return content; }, jsEscape: function (content) { return content.replace(/(['\\])/g, '\\$1') .replace(/[\f]/g, "\\f") .replace(/[\b]/g, "\\b") .replace(/[\n]/g, "\\n") .replace(/[\t]/g, "\\t") .replace(/[\r]/g, "\\r") .replace(/[\u2028]/g, "\\u2028") .replace(/[\u2029]/g, "\\u2029"); }, createXhr: masterConfig.createXhr || function () { //Would love to dump the ActiveX crap in here. Need IE 6 to die first. var xhr, i, progId; if (typeof XMLHttpRequest !== "undefined") { return new XMLHttpRequest(); } else if (typeof ActiveXObject !== "undefined") { for (i = 0; i < 3; i += 1) { progId = progIds[i]; try { xhr = new ActiveXObject(progId); } catch (e) {} if (xhr) { progIds = [progId]; // so faster next time break; } } } return xhr; }, /** * Parses a resource name into its component parts. Resource names * look like: module/name.ext!strip, where the !strip part is * optional. * @param {String} name the resource name * @returns {Object} with properties "moduleName", "ext" and "strip" * where strip is a boolean. */ parseName: function (name) { var strip = false, index = name.indexOf("."), modName = name.substring(0, index), ext = name.substring(index + 1, name.length); index = ext.indexOf("!"); if (index !== -1) { //Pull off the strip arg. strip = ext.substring(index + 1, ext.length); strip = strip === "strip"; ext = ext.substring(0, index); } return { moduleName: modName, ext: ext, strip: strip }; }, xdRegExp: /^((\w+)\:)?\/\/([^\/\\]+)/, /** * Is an URL on another domain. Only works for browser use, returns * false in non-browser environments. Only used to know if an * optimized .js version of a text resource should be loaded * instead. * @param {String} url * @returns Boolean */ useXhr: function (url, protocol, hostname, port) { var uProtocol, uHostName, uPort, match = text.xdRegExp.exec(url); if (!match) { return true; } uProtocol = match[2]; uHostName = match[3]; uHostName = uHostName.split(':'); uPort = uHostName[1]; uHostName = uHostName[0]; return (!uProtocol || uProtocol === protocol) && (!uHostName || uHostName.toLowerCase() === hostname.toLowerCase()) && ((!uPort && !uHostName) || uPort === port); }, finishLoad: function (name, strip, content, onLoad) { content = strip ? text.strip(content) : content; if (masterConfig.isBuild) { buildMap[name] = content; } onLoad(content); }, load: function (name, req, onLoad, config) { //Name has format: some.module.filext!strip //The strip part is optional. //if strip is present, then that means only get the string contents //inside a body tag in an HTML string. For XML/SVG content it means //removing the <?xml ...?> declarations so the content can be inserted //into the current doc without problems. // Do not bother with the work if a build and text will // not be inlined. if (config.isBuild && !config.inlineText) { onLoad(); return; } masterConfig.isBuild = config.isBuild; var parsed = text.parseName(name), nonStripName = parsed.moduleName + '.' + parsed.ext, url = req.toUrl(nonStripName), useXhr = (masterConfig.useXhr) || text.useXhr; //Load the text. Use XHR if possible and in a browser. if (!hasLocation || useXhr(url, defaultProtocol, defaultHostName, defaultPort)) { text.get(url, function (content) { text.finishLoad(name, parsed.strip, content, onLoad); }, function (err) { if (onLoad.error) { onLoad.error(err); } }); } else { //Need to fetch the resource across domains. Assume //the resource has been optimized into a JS module. Fetch //by the module name + extension, but do not include the //!strip part to avoid file system issues. req([nonStripName], function (content) { text.finishLoad(parsed.moduleName + '.' + parsed.ext, parsed.strip, content, onLoad); }); } }, write: function (pluginName, moduleName, write, config) { if (buildMap.hasOwnProperty(moduleName)) { var content = text.jsEscape(buildMap[moduleName]); write.asModule(pluginName + "!" + moduleName, "define(function () { return '" + content + "';});\n"); } }, writeFile: function (pluginName, moduleName, req, write, config) { var parsed = text.parseName(moduleName), nonStripName = parsed.moduleName + '.' + parsed.ext, //Use a '.js' file name so that it indicates it is a //script that can be loaded across domains. fileName = req.toUrl(parsed.moduleName + '.' + parsed.ext) + '.js'; //Leverage own load() method to load plugin value, but only //write out values that do not have the strip argument, //to avoid any potential issues with ! in file names. text.load(nonStripName, req, function (value) { //Use own write() method to construct full module value. //But need to create shell that translates writeFile's //write() to the right interface. var textWrite = function (contents) { return write(fileName, contents); }; textWrite.asModule = function (moduleName, contents) { return write.asModule(moduleName, fileName, contents); }; text.write(pluginName, nonStripName, textWrite, config); }, config); } }; if (masterConfig.env === 'node' || (!masterConfig.env && typeof process !== "undefined" && process.versions && !!process.versions.node)) { //Using special require.nodeRequire, something added by r.js. fs = require.nodeRequire('fs'); text.get = function (url, callback) { var file = fs.readFileSync(url, 'utf8'); //Remove BOM (Byte Mark Order) from utf8 files if it is there. if (file.indexOf('\uFEFF') === 0) { file = file.substring(1); } callback(file); }; } else if (masterConfig.env === 'xhr' || (!masterConfig.env && text.createXhr())) { text.get = function (url, callback, errback) { var xhr = text.createXhr(); xhr.open('GET', url, true); //Allow overrides specified in config if (masterConfig.onXhr) { masterConfig.onXhr(xhr, url); } xhr.onreadystatechange = function (evt) { var status, err; //Do not explicitly handle errors, those should be //visible via console output in the browser. if (xhr.readyState === 4) { status = xhr.status; if (status > 399 && status < 600) { //An http 4xx or 5xx error. Signal an error. err = new Error(url + ' HTTP status: ' + status); err.xhr = xhr; errback(err); } else { callback(xhr.responseText); } } }; xhr.send(null); }; } else if (masterConfig.env === 'rhino' || (!masterConfig.env && typeof Packages !== 'undefined' && typeof java !== 'undefined')) { //Why Java, why is this so awkward? text.get = function (url, callback) { var stringBuffer, line, encoding = "utf-8", file = new java.io.File(url), lineSeparator = java.lang.System.getProperty("line.separator"), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), content = ''; try { stringBuffer = new java.lang.StringBuffer(); line = input.readLine(); // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 // http://www.unicode.org/faq/utf_bom.html // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 if (line && line.length() && line.charAt(0) === 0xfeff) { // Eat the BOM, since we've already found the encoding on this file, // and we plan to concatenating this buffer with others; the BOM should // only appear at the top of a file. line = line.substring(1); } stringBuffer.append(line); while ((line = input.readLine()) !== null) { stringBuffer.append(lineSeparator); stringBuffer.append(line); } //Make sure we return a JavaScript string and not a Java string. content = String(stringBuffer.toString()); //String } finally { input.close(); } callback(content); }; } return text; }); define('text!shell.html',[],function () { return '<section>\r\n <h2>Hello! What is your name?</h2>\r\n <form class="form-inline">\r\n <fieldset>\r\n <label>Name</label>\r\n <input type="text" data-bind="value: name, valueUpdate: \'afterkeydown\'"/>\r\n <button type="submit" class="btn" data-bind="click: sayHello, enable: name">Click Me</button>\r\n </fieldset>\r\n </form>\r\n</section>';}); require(["main"]); }()); //# sourceMappingURL=main.js.map
{ "content_hash": "e1c3d1d84e10e8007b642eb38c2fd7db", "timestamp": "", "source": "github", "line_count": 13462, "max_line_length": 597, "avg_line_length": 33.42831674342594, "alnum_prop": 0.5873065607139365, "repo_name": "welldone-software/grunt-durandaljs", "id": "835875a0cdad63735e09c3174ad5898436cf3fa6", "size": "450199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/expected/pathTestSimple2/main.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "8994410" } ], "symlink_target": "" }
package handler import ( "encoding/json" "io/ioutil" "net/http" "os" "strings" "github.com/golang/glog" "golang.org/x/text/language" ) const defaultDir = "./public/en" // Localization is a spec for the localization configuration of dashboard. type Localization struct { Translations []Translation `json:"translations"` } // Translation is a single translation definition spec. type Translation struct { File string `json:"file"` Key string `json:"key"` } // LocaleHandler serves different localized versions of the frontend application // based on the Accept-Language header. type LocaleHandler struct { SupportedLocales []language.Tag } // CreateLocaleHandler loads the localization configuration and constructs a LocaleHandler. func CreateLocaleHandler() *LocaleHandler { locales, err := getSupportedLocales("./locale_conf.json") if err != nil { glog.Warningf("Error when loading the localization configuration. Dashboard will not be localized. %s", err) locales = []language.Tag{} } return &LocaleHandler{SupportedLocales: locales} } func getSupportedLocales(configFile string) ([]language.Tag, error) { // read config file localesFile, err := ioutil.ReadFile(configFile) if err != nil { return []language.Tag{}, err } // unmarshall localization := Localization{} err = json.Unmarshal(localesFile, &localization) if err != nil { glog.Warningf("%s %s", string(localesFile), err) } // filter locale keys result := []language.Tag{} for _, translation := range localization.Translations { result = append(result, language.Make(translation.Key)) } return result, nil } // LocaleHandler serves different html versions based on the Accept-Language header. func (handler *LocaleHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.URL.EscapedPath() == "/" || r.URL.EscapedPath() == "/index.html" { // Do not store the html page in the cache. If the user is to click on 'switch language', // we want a different index.html (for the right locale) to be served when the page refreshes. w.Header().Add("Cache-Control", "no-store") } acceptLanguage := r.Header.Get("Accept-Language") dirName := handler.determineLocalizedDir(acceptLanguage) http.FileServer(http.Dir(dirName)).ServeHTTP(w, r) } func (handler *LocaleHandler) determineLocalizedDir(locale string) string { tags, _, err := language.ParseAcceptLanguage(locale) if (err != nil) || (len(tags) == 0) { return defaultDir } locales := handler.SupportedLocales tag, _, confidence := language.NewMatcher(locales).Match(tags...) matchedLocale := strings.ToLower(tag.String()) if confidence != language.Exact { matchedLocale = "" for _, l := range locales { base, _ := tag.Base() if l.String() == base.String() { matchedLocale = l.String() } } } localeDir := "./public/" + matchedLocale if matchedLocale != "" && handler.dirExists(localeDir) { return localeDir } return defaultDir } func (handler *LocaleHandler) dirExists(name string) bool { if _, err := os.Stat(name); err != nil { if os.IsNotExist(err) { glog.Warningf(name) return false } } return true }
{ "content_hash": "c43c21e4807c7ee62c13fa6f1ef20faa", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 110, "avg_line_length": 28.18918918918919, "alnum_prop": 0.7123681687440077, "repo_name": "cnwalker/dashboard", "id": "43de9e6e84a0ed30ef3fa531c61f8554e997ab3e", "size": "3740", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/backend/handler/localehandler.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "65541" }, { "name": "Go", "bytes": "965896" }, { "name": "HTML", "bytes": "465784" }, { "name": "JavaScript", "bytes": "1531590" }, { "name": "Shell", "bytes": "7094" }, { "name": "XSLT", "bytes": "2542" } ], "symlink_target": "" }
package org.keycloak.adapters.saml.config.parsers; /** * @author <a href="mailto:bill@burkecentral.com">Bill Burke</a> * @version $Revision: 1 $ */ public class ConfigXmlConstants { public static final String KEYCLOAK_SAML_ADAPTER = "keycloak-saml-adapter"; public static final String SP_ELEMENT = "SP"; public static final String ENTITY_ID_ATTR = "entityID"; public static final String SSL_POLICY_ATTR = "sslPolicy"; public static final String NAME_ID_POLICY_FORMAT_ATTR = "nameIDPolicyFormat"; public static final String FORCE_AUTHENTICATION_ATTR = "forceAuthentication"; public static final String IS_PASSIVE_ATTR = "isPassive"; public static final String TURN_OFF_CHANGE_SESSSION_ID_ON_LOGIN_ATTR = "turnOffChangeSessionIdOnLogin"; public static final String SIGNATURE_ALGORITHM_ATTR = "signatureAlgorithm"; public static final String SIGNATURE_CANONICALIZATION_METHOD_ATTR = "signatureCanonicalizationMethod"; public static final String LOGOUT_PAGE_ATTR = "logoutPage"; public static final String KEYS_ELEMENT = "Keys"; public static final String KEY_ELEMENT = "Key"; public static final String SIGNING_ATTR = "signing"; public static final String ENCRYPTION_ATTR = "encryption"; public static final String CERTIFICATE_PEM_ELEMENT = "CertificatePem"; public static final String PRIVATE_KEY_PEM_ELEMENT = "PrivateKeyPem"; public static final String PUBLIC_KEY_PEM_ELEMENT = "PublicKeyPem"; public static final String FILE_ATTR = "file"; public static final String TYPE_ATTR = "type"; public static final String RESOURCE_ATTR = "resource"; public static final String PASSWORD_ATTR = "password"; public static final String ALIAS_ATTR = "alias"; public static final String KEYS_STORE_ELEMENT = "KeyStore"; public static final String CERTIFICATE_ELEMENT = "Certificate"; public static final String PRIVATE_KEY_ELEMENT = "PrivateKey"; public static final String PRINCIPAL_NAME_MAPPING_ELEMENT = "PrincipalNameMapping"; public static final String POLICY_ATTR = "policy"; public static final String ATTRIBUTE_ATTR = "attribute"; public static final String ROLE_IDENTIFIERS_ELEMENT = "RoleIdentifiers"; public static final String ATTRIBUTE_ELEMENT = "Attribute"; public static final String NAME_ATTR = "name"; public static final String IDP_ELEMENT = "IDP"; public static final String SIGNATURES_REQUIRED_ATTR = "signaturesRequired"; public static final String SINGLE_SIGN_ON_SERVICE_ELEMENT = "SingleSignOnService"; public static final String SINGLE_LOGOUT_SERVICE_ELEMENT = "SingleLogoutService"; public static final String SIGN_REQUEST_ATTR = "signRequest"; public static final String SIGN_RESPONSE_ATTR = "signResponse"; public static final String REQUEST_BINDING_ATTR = "requestBinding"; public static final String RESPONSE_BINDING_ATTR = "responseBinding"; public static final String BINDING_URL_ATTR = "bindingUrl"; public static final String VALIDATE_RESPONSE_SIGNATURE_ATTR = "validateResponseSignature"; public static final String VALIDATE_REQUEST_SIGNATURE_ATTR = "validateRequestSignature"; public static final String POST_BINDING_URL_ATTR = "postBindingUrl"; public static final String REDIRECT_BINDING_URL_ATTR = "redirectBindingUrl"; }
{ "content_hash": "3299434528dec2562b9a031331349bfe", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 107, "avg_line_length": 56.559322033898304, "alnum_prop": 0.751573269403656, "repo_name": "jean-merelis/keycloak", "id": "886620350986c4852dbb6068330ab6335bfec60a", "size": "4011", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "adapters/saml/core/src/main/java/org/keycloak/adapters/saml/config/parsers/ConfigXmlConstants.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "3104" }, { "name": "ApacheConf", "bytes": "22819" }, { "name": "Batchfile", "bytes": "2114" }, { "name": "CSS", "bytes": "345395" }, { "name": "FreeMarker", "bytes": "63757" }, { "name": "HTML", "bytes": "452064" }, { "name": "Java", "bytes": "10984710" }, { "name": "JavaScript", "bytes": "737973" }, { "name": "Shell", "bytes": "11085" }, { "name": "XSLT", "bytes": "116830" } ], "symlink_target": "" }
package org.springframework.boot.test; import java.util.HashMap; import java.util.Map; import org.junit.Test; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.StandardEnvironment; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link EnvironmentTestUtils}. * * @author Stephane Nicoll */ public class EnvironmentTestUtilsTests { private final ConfigurableEnvironment environment = new StandardEnvironment(); @Test public void addSimplePairEqual() { testAddSimplePair("my.foo", "bar", "="); } @Test public void addSimplePairColon() { testAddSimplePair("my.foo", "bar", ":"); } @Test public void addSimplePairEqualWithEqualInValue() { testAddSimplePair("my.foo", "b=ar", "="); } @Test public void addSimplePairEqualWithColonInValue() { testAddSimplePair("my.foo", "b:ar", "="); } @Test public void addSimplePairColonWithColonInValue() { testAddSimplePair("my.foo", "b:ar", ":"); } @Test public void addSimplePairColonWithEqualInValue() { testAddSimplePair("my.foo", "b=ar", ":"); } @Test public void addPairNoValue() { String propertyName = "my.foo+bar"; assertThat(this.environment.containsProperty(propertyName)).isFalse(); EnvironmentTestUtils.addEnvironment(this.environment, propertyName); assertThat(this.environment.containsProperty(propertyName)).isTrue(); assertThat(this.environment.getProperty(propertyName)).isEqualTo(""); } private void testAddSimplePair(String key, String value, String delimiter) { assertThat(this.environment.containsProperty(key)).isFalse(); EnvironmentTestUtils.addEnvironment(this.environment, key + delimiter + value); assertThat(this.environment.getProperty(key)).isEqualTo(value); } @Test public void testConfigHasHigherPrecedence() { Map<String, Object> map = new HashMap<String, Object>(); map.put("my.foo", "bar"); MapPropertySource source = new MapPropertySource("sample", map); this.environment.getPropertySources().addFirst(source); assertThat(this.environment.getProperty("my.foo")).isEqualTo("bar"); EnvironmentTestUtils.addEnvironment(this.environment, "my.foo=bar2"); assertThat(this.environment.getProperty("my.foo")).isEqualTo("bar2"); } }
{ "content_hash": "008925be2d20224ad1a74d5976ff972e", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 81, "avg_line_length": 28.51851851851852, "alnum_prop": 0.7519480519480519, "repo_name": "joansmith/spring-boot", "id": "fe9f330444d0b2d6e88d3558f6b453ba857aab44", "size": "2930", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spring-boot/src/test/java/org/springframework/boot/test/EnvironmentTestUtilsTests.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "6954" }, { "name": "CSS", "bytes": "5769" }, { "name": "FreeMarker", "bytes": "2116" }, { "name": "Groovy", "bytes": "39777" }, { "name": "HTML", "bytes": "69819" }, { "name": "Java", "bytes": "7739568" }, { "name": "JavaScript", "bytes": "37789" }, { "name": "Ruby", "bytes": "1305" }, { "name": "SQLPL", "bytes": "20085" }, { "name": "Shell", "bytes": "20227" }, { "name": "Smarty", "bytes": "3276" }, { "name": "XSLT", "bytes": "33894" } ], "symlink_target": "" }
<div class="commune_descr limited"> <p> Pougny est un village situé dans le département de l'Ain en Rhône-Alpes. On dénombrait 731 habitants en 2008.</p> <p>La commune propose quelques aménagements, elle propose entre autres un terrain de sport.</p> <p>Si vous envisagez de emmenager à Pougny, vous pourrez aisément trouver une maison à vendre. </p> <p>À Pougny, la valorisation moyenne à l'achat d'un appartement s'évalue à 2&nbsp;963 &euro; du m² en vente. Le prix moyen d'une maison à l'achat se situe à 2&nbsp;713 &euro; du m². À la location la valorisation moyenne se situe à 16,34 &euro; du m² par mois.</p> <p>Le parc de logements, à Pougny, était réparti en 2011 en 71 appartements et 329 maisons soit un marché relativement équilibré.</p> <p>À coté de Pougny sont localisées les communes de <a href="{{VLROOT}}/immobilier/chenex_74069/">Chênex</a> située à 5&nbsp;km, 456 habitants, <a href="{{VLROOT}}/immobilier/valleiry_74288/">Valleiry</a> située à 3&nbsp;km, 2&nbsp;868 habitants, <a href="{{VLROOT}}/immobilier/vulbens_74314/">Vulbens</a> localisée à 4&nbsp;km, 839 habitants, <a href="{{VLROOT}}/immobilier/farges_01158/">Farges</a> située à 4&nbsp;km, 795 habitants, <a href="{{VLROOT}}/immobilier/collonges_01109/">Collonges</a> à 3&nbsp;km, 1&nbsp;221 habitants, <a href="{{VLROOT}}/immobilier/challex_01078/">Challex</a> localisée à 6&nbsp;km, 1&nbsp;059 habitants, entre autres. De plus, Pougny est située à seulement 29&nbsp;km de <a href="{{VLROOT}}/immobilier/annecy_74010/">Annecy</a>.</p> </div>
{ "content_hash": "37d310f73c5b80f49f8f1d477b9a765d", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 263, "avg_line_length": 81.10526315789474, "alnum_prop": 0.7287475665152499, "repo_name": "donaldinou/frontend", "id": "372db6128c55abeb5deff21fcfd4ab44a79e783f", "size": "1583", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Viteloge/CoreBundle/Resources/descriptions/01308.html", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "CSS", "bytes": "111338" }, { "name": "HTML", "bytes": "58634405" }, { "name": "JavaScript", "bytes": "88564" }, { "name": "PHP", "bytes": "841919" } ], "symlink_target": "" }
package com.divinitor.discord.vahrhedralbot.serverstorage; import java.util.Map; public interface ServerStorage { void put(String key, Object value); void put(String key, String value); <T> T get(String key, Class<T> clazz); String getString(String key); Map<String, String> getAll(); void delete(String key); }
{ "content_hash": "7f72816036e6d845905dbf4079132b60", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 58, "avg_line_length": 19.11111111111111, "alnum_prop": 0.6976744186046512, "repo_name": "vincentzhang96/VahrhedralBot", "id": "d3f7f27badb3346f25ba99c98646f3c4df51524b", "size": "344", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/divinitor/discord/vahrhedralbot/serverstorage/ServerStorage.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "530274" } ], "symlink_target": "" }
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <!DOCTYPE html> <html lang="es"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap.css"); ?>" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap-switch.min.css"); ?>" /> <link rel="stylesheet" href="<?php echo base_url("assets/css/bootstrap-select.css"); ?>" /> <script type="text/javascript" charset="UTF-8" src="<?php echo base_url("assets/js/jquery-3.1.0.min.js"); ?>"></script> <script type="text/javascript" charset="UTF-8" src="<?php echo base_url("assets/js/bootstrap.js"); ?>"></script> <script type="text/javascript" charset="UTF-8" src="<?php echo base_url("assets/js/bootstrap-switch.min.js"); ?>"></script> <script type="text/javascript" charset="UTF-8" src="<?php echo base_url("assets/js/jquery.numbers.min.js"); ?>"></script> <script type="text/javascript" src="<?php echo base_url("assets/js/bootstrap-select.js"); ?>"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/2.0.6/numeral.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.4.0/bootbox.min.js"></script> <script> function verifyTab(){ if (window.sessionStorage) { //verifico si hay localstorage if(localStorage.activo){ //verifico sesion //si ya tengo sesion significa que ando en la misma tab if(!sessionStorage.newtab){ //si no tengo sesion significa que es una tab nueva alert("Ya tienes una ventana abierta."); window.open("http://localhost/cdig/index.php/Errors/error_msg","_self"); } } //si no hay localstorage, creo uno y tambien creo una sesion else{ localStorage.setItem('activo',true); sessionStorage.setItem('newtab',true); } } else { alert("Tu navegador no soporta HTML5, actualizalo para usar nuestros servicios."); window.open("http://localhost/cdig/index.php/Errors/error980","_self"); } } $(document).ready(function(){ if( $("#wrapper").css('padding-left') == '225px') $(".seeMen").css('display','block'); $(".seeMen").click(function(){ $(".lateral").toggle(); if( $("#wrapper").css('padding-left') == '225px') $("#wrapper").css('padding-left',15); else $("#wrapper").css('padding-left',225); }); $(".modulos").click(function(){ var id = $(this).attr('id'); $('.'+id).toggle(); }); }); </script> <title>EDS Palonegro</title> </head> <body onload="verifyTab();"> <div class="modal fade bs-example-modal-sm" id="modalChose" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static"> <div class="modal-dialog modal-sm"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Elija entidad</h4> </div> <div class="modal-body"> <div class="input-group"> <select class="form-control" id="idChose"> <?php if($this->session->has_userdata('nom_entidades')){ $nomes=$this->session->userdata('nom_entidades'); $ides=$this->session->userdata('id_entidades'); for($i=0;$i<count($nomes);$i++){ echo "<option value='".$ides[$i]."'>".$nomes[$i]."</option>"; } } ?> </select> <span class="input-group-btn"><button class="btn btn-info" id="confirmEnti">Elegir</button></span> </div> </div> <div class="modal-footer"> <button type="button" id="closeChose" class="btn btn-default" data-dismiss="modal">Cerrar</button> </div> </div> </div> </div> <div id="wrapper"> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="#">EDS Palonegro</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav"> <li><a class='seeMen' href="#" style="display:none;"><span class="fa fa-list"></span></a></li> <li class="active"><a href="<?php echo base_url('index.php/panel_usr'); ?>">Inicio<span class="sr-only">(current)</span></a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> Entidades <span class="caret"></span> </a> <?php if($this->session->has_userdata('nom_entidades')) { echo "<ul class='dropdown-menu'>"; $nom=$this->session->userdata('nom_entidades'); $id=$this->session->userdata('id_entidades'); for ($i=0; $i < count($id); $i++) { echo "<li><a href='".base_url('index.php/panel_enti/datenti/'.$id[$i])."'><span class='fa fa-home'></span> ".$nom[$i]."</a></li>"; } echo '</ul>'; } ?> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="fa fa-user text-success"></span> <?php echo $this->session->userdata('real_name'); ?> <span class="caret"></span> </a> <ul class="dropdown-menu"> <li> <?php $atts = array('location'=> 'no','width'=> 840,'height'=> 600,'scrollbars'=>'no','status'=>'yes','resizable'=>'no','screenx'=> 0,'screeny'=> 0,'window_name'=>'_blank');?> <?php echo anchor_popup('sys_adm/Sys_profile',"<span class='fa fa-id-card-o text-primary'></span>&nbsp;Perfil", $atts); ?> </li> <li><a href="#"><span class="fa fa-support text-info"></span>&nbsp;Ayuda</a></li> <li role="separator" class="divider"></li> <li><?php echo anchor(base_url('index.php/log_usr/log_out'), '<span class="fa fa-sign-out text-danger"></span>&nbsp;Cerrar sesión'); ?></li> </ul> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <?php if($this->session->has_userdata('act_enti')){ ?> <?php $atts = array('location'=> 'no','width'=> 840,'height'=> 400,'scrollbars'=>'no','status'=>'yes','resizable'=>'no','screenx'=> 0,'screeny'=> 0,'window_name'=>'_blank');?> <?php echo anchor_popup('sys_contable/Sys_seguicaja',"<span class='fa fa-archive text-success'></span>&nbsp;Caja", $atts); ?> <?php } ?> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <span class="fa fa-commenting text-primary"></span> Mensajes <span class="label label-info">3</span> </a> <ul class="dropdown-menu"> <li><a href="#"><h5><span class="fa fa-envelope-o text-success"></span>&nbsp;Despertar a usuario de 402<br><small><span class="fa fa-clock-o text-success"></span>&nbsp;Hoy 4:00 PM</small></h5></a></li> <li><a href="#"><h5><span class="fa fa-envelope-o text-success"></span>&nbsp;Pagar recibo de la luz<br><small><span class="fa fa-clock-o text-success"></span>&nbsp;Hoy 4:00 PM</small></h5></a></li> <li role="separator" class="divider"></li> <li><?php echo anchor('#', '<span class="fa fa-envelope text-primary"></span>&nbsp;ver todos'); ?></li> </ul> </li> </ul> <ul class="nav navbar-nav side-nav lateral"> <?php echo getsidemenu() ?> </ul> </div> </div> </nav>
{ "content_hash": "8ca0e0c8097126e9b14c507b524a8f63", "timestamp": "", "source": "github", "line_count": 211, "max_line_length": 215, "avg_line_length": 43.345971563981045, "alnum_prop": 0.534769298053794, "repo_name": "diegoacs/cdig", "id": "77fa752be8402fb5ea72edd54599445939d39160", "size": "9147", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/main/head.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "24240" }, { "name": "HTML", "bytes": "8282603" }, { "name": "JavaScript", "bytes": "586756" }, { "name": "PHP", "bytes": "6070015" } ], "symlink_target": "" }
package gbagretsov.ghsearch.app; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Toast; import java.util.*; /** * Фрагмент-вкладка с параметрами поиска. Также содержит floating action button, * по нажатию на которую и происходит поиск. */ public class SearchStartFragment extends Fragment { private AutoCompleteTextView queryEditText; // Поле для ввода запроса SharedPreferences sharedPref; SharedPreferences.Editor editor; public SearchStartFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_search_start, container, false); FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab); fab.setOnClickListener(fabClickListener); queryEditText = (AutoCompleteTextView) view.findViewById(R.id.query); return view; } @Override public void onResume() { super.onResume(); // Получаем настройки, в которых будем хранить и из которых будем брать историю поиска sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); // Получаем историю поиска Map<String, Long> prefsCopy = new HashMap<>(((Map<String, Long>) sharedPref.getAll())); prefsCopy = sortByValueDesc(prefsCopy); String[] history = prefsCopy.keySet().toArray(new String[prefsCopy.values().size()]); // В дополнение к показу вариантов при вводе символа добавлен listener на клик, // чтобы выпадающий список показывался сразу же final ArrayAdapter<String> adapter = new ArrayAdapter<> (getContext(), android.R.layout.simple_dropdown_item_1line, history); queryEditText.setAdapter(adapter); queryEditText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { queryEditText.showDropDown(); } }); } // Обработка нажатия на floating action button (сам listener устанавливается в методе onCreateView) private View.OnClickListener fabClickListener = new View.OnClickListener() { @Override public void onClick(View v) { // TODO: Добавлять дополнительные параметры к запросу String q = queryEditText.getText().toString(); final Context context = v.getContext(); if (q.isEmpty()) { Toast.makeText(context, getText(R.string.query_is_empty), Toast.LENGTH_SHORT).show(); return; } // Сохраняем запрос в историю вместе с меткой времени (при повторном сохранении того же ключа // сохранится последняя запись с самой новой меткой) editor = sharedPref.edit(); editor.putLong(q, Calendar.getInstance().getTimeInMillis()); editor.apply(); // Запускаем новую Activity и передаём запрос Intent intent = new Intent(context, SearchResultsActivity.class); intent.putExtra(SearchResultsActivity.QUERY, q); startActivity(intent); } }; // Сортировка HashMap по убыванию значений. Используется для вывода истории. // Взято здесь: http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java private static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDesc(Map<K, V> map ) { List<Map.Entry<K, V>> list = new LinkedList<>( map.entrySet() ); Collections.sort( list, new Comparator<Map.Entry<K, V>>() { @Override public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ) { return ( o2.getValue() ).compareTo( o1.getValue() ); } } ); Map<K, V> result = new LinkedHashMap<>(); for (Map.Entry<K, V> entry : list) { result.put( entry.getKey(), entry.getValue() ); } return result; } }
{ "content_hash": "a5a98e683f4739a8e98a2967868f4ec7", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 105, "avg_line_length": 36.110236220472444, "alnum_prop": 0.6522023549934584, "repo_name": "gbagretsov/android-gh-search", "id": "b7aadefd8977d6b1f84aae03928c0606303215d2", "size": "5167", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/gbagretsov/ghsearch/app/SearchStartFragment.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "40495" } ], "symlink_target": "" }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. /*============================================================================= AsyncLoading.h: Unreal async loading definitions. =============================================================================*/ #pragma once #include "AsyncPackage.h" #define PERF_TRACK_DETAILED_ASYNC_STATS (0) /** * Structure containing intermediate data required for async loading of all imports and exports of a * FLinkerLoad. */ struct FAsyncPackage { /** * Constructor */ FAsyncPackage(const FAsyncPackageDesc& InDesc); ~FAsyncPackage(); /** * Ticks the async loading code. * * @param InbUseTimeLimit Whether to use a time limit * @param InbUseFullTimeLimit If true use the entire time limit, even if you have to block on IO * @param InTimeLimit Soft limit to time this function may take * * @return true if package has finished loading, false otherwise */ EAsyncPackageState::Type Tick( bool bUseTimeLimit, bool bInbUseFullTimeLimit, float& InOutTimeLimit ); /** * @return Estimated load completion percentage. */ FORCEINLINE float GetLoadPercentage() const { return LoadPercentage; } /** * @return Time load begun. This is NOT the time the load was requested in the case of other pending requests. */ double GetLoadStartTime() const; /** * Emulates ResetLoaders for the package's Linker objects, hence deleting it. */ void ResetLoader(); /** * Disassociates linker from this package */ void DetachLinker(); /** * Returns the name of the package to load. */ FORCEINLINE const FName& GetPackageName() const { return Desc.Name; } void AddCompletionCallback(const FLoadPackageAsyncDelegate& Callback, bool bInternal); /** Gets the number of references to this package from other packages in the dependency tree. */ FORCEINLINE int32 GetDependencyRefCount() const { return DependencyRefCount.GetValue(); } /** Returns true if the package has finished loading. */ FORCEINLINE bool HasFinishedLoading() const { return bLoadHasFinished; } /** Returns package loading priority. */ FORCEINLINE uint32 GetPriority() const { return Desc.Priority; } /** Returns true if loading has failed */ FORCEINLINE bool HasLoadFailed() const { return bLoadHasFailed; } /** Adds new request ID to the existing package */ void AddRequestID(int32 Id); /** * Cancel loading this package. */ void Cancel(); /** * Set the package that spawned this package as a dependency. */ void SetDependencyRootPackage(FAsyncPackage* InDependencyRootPackage) { DependencyRootPackage = InDependencyRootPackage; } private: struct FCompletionCallback { bool bIsInternal; FLoadPackageAsyncDelegate Callback; FCompletionCallback() { } FCompletionCallback(bool bInInternal, FLoadPackageAsyncDelegate InCallback) : bIsInternal(bInInternal) , Callback(InCallback) { } }; /** Basic information associated with this package */ FAsyncPackageDesc Desc; /** Linker which is going to have its exports and imports loaded */ FLinkerLoad* Linker; /** Package which is going to have its exports and imports loaded */ UPackage* LinkerRoot; /** Call backs called when we finished loading this package */ TArray<FCompletionCallback> CompletionCallbacks; /** Pending Import packages - we wait until all of them have been fully loaded. */ TArray<FAsyncPackage*> PendingImportedPackages; /** Referenced imports - list of packages we need until we finish loading this package. */ TArray<FAsyncPackage*> ReferencedImports; /** Root package if this package was loaded as a dependency of another. NULL otherwise */ FAsyncPackage* DependencyRootPackage; /** Number of references to this package from other packages in the dependency tree. */ FThreadSafeCounter DependencyRefCount; /** Current index into linkers import table used to spread creation over several frames */ int32 LoadImportIndex; /** Current index into linkers import table used to spread creation over several frames */ int32 ImportIndex; /** Current index into linkers export table used to spread creation over several frames */ int32 ExportIndex; /** Current index into GObjLoaded array used to spread routing PreLoad over several frames */ static int32 PreLoadIndex; /** Current index into GObjLoaded array used to spread routing PostLoad over several frames */ static int32 PostLoadIndex; /** Current index into DeferredPostLoadObjects array used to spread routing PostLoad over several frames */ int32 DeferredPostLoadIndex; /** Currently used time limit for this tick. */ float TimeLimit; /** Whether we are using a time limit for this tick. */ bool bUseTimeLimit; /** Whether we should use the entire time limit, even if we're blocked on I/O */ bool bUseFullTimeLimit; /** Whether we already exceed the time limit this tick. */ bool bTimeLimitExceeded; /** True if our load has failed */ bool bLoadHasFailed; /** True if our load has finished */ bool bLoadHasFinished; /** The time taken when we started the tick. */ double TickStartTime; /** Last object work was performed on. Used for debugging/ logging purposes. */ UObject* LastObjectWorkWasPerformedOn; /** Last type of work performed on object. */ const TCHAR* LastTypeOfWorkPerformed; /** Time load begun. This is NOT the time the load was requested in the case of pending requests. */ double LoadStartTime; /** Estimated load percentage. */ float LoadPercentage; /** Objects to be post loaded on the game thread */ TArray<UObject*> DeferredPostLoadObjects; /** Objects to be finalized on the game thread */ TArray<UObject*> DeferredFinalizeObjects; /** List of all request handles */ TArray<int32> RequestIDs; /** Cached async loading thread object this package was created by */ class FAsyncLoadingThread& AsyncLoadingThread; public: #if PERF_TRACK_DETAILED_ASYNC_STATS /** Number of times Tick function has been called. */ int32 TickCount; /** Number of iterations in loop inside Tick. */ int32 TickLoopCount; /** Number of iterations for CreateLinker. */ int32 CreateLinkerCount; /** Number of iterations for FinishLinker. */ int32 FinishLinkerCount; /** Number of iterations for CreateImports. */ int32 CreateImportsCount; /** Number of iterations for CreateExports. */ int32 CreateExportsCount; /** Number of iterations for PreLoadObjects. */ int32 PreLoadObjectsCount; /** Number of iterations for PostLoadObjects. */ int32 PostLoadObjectsCount; /** Number of iterations for FinishObjects. */ int32 FinishObjectsCount; /** Total time spent in Tick. */ double TickTime; /** Total time spent in CreateLinker. */ double CreateLinkerTime; /** Total time spent in FinishLinker. */ double FinishLinkerTime; /** Total time spent in CreateImports. */ double CreateImportsTime; /** Total time spent in CreateExports. */ double CreateExportsTime; /** Total time spent in PreLoadObjects. */ double PreLoadObjectsTime; /** Total time spent in PostLoadObjects. */ double PostLoadObjectsTime; /** Total time spent in FinishObjects. */ double FinishObjectsTime; #endif void CallCompletionCallbacks(bool bInternalOnly, EAsyncLoadingResult::Type LoadingResult); /** * Route PostLoad to deferred objects. * * @return true if we finished calling PostLoad on all loaded objects and no new ones were created, false otherwise */ EAsyncPackageState::Type PostLoadDeferredObjects(double InTickStartTime, bool bInUseTimeLimit, float& InOutTimeLimit); private: /** * Gives up time slice if time limit is enabled. * * @return true if time slice can be given up, false otherwise */ bool GiveUpTimeSlice(); /** * Returns whether time limit has been exceeded. * * @return true if time limit has been exceeded (and is used), false otherwise */ bool IsTimeLimitExceeded(); /** * Begin async loading process. Simulates parts of BeginLoad. * * Objects created during BeginAsyncLoad and EndAsyncLoad will have RF_AsyncLoading set */ void BeginAsyncLoad(); /** * End async loading process. Simulates parts of EndLoad(). FinishObjects * simulates some further parts once we're fully done loading the package. */ void EndAsyncLoad(); /** * Create linker async. Linker is not finalized at this point. * * @return true */ EAsyncPackageState::Type CreateLinker(); /** * Finalizes linker creation till time limit is exceeded. * * @return true if linker is finished being created, false otherwise */ EAsyncPackageState::Type FinishLinker(); /** * Loads imported packages.. * * @return true if we finished loading all imports, false otherwise */ EAsyncPackageState::Type LoadImports(); /** * Create imports till time limit is exceeded. * * @return true if we finished creating all imports, false otherwise */ EAsyncPackageState::Type CreateImports(); /** * Checks if all async texture allocations for this package have been completed. * * @return true if all texture allocations have been completed, false otherwise */ EAsyncPackageState::Type FinishTextureAllocations(); /** * Create exports till time limit is exceeded. * * @return true if we finished creating and preloading all exports, false otherwise. */ EAsyncPackageState::Type CreateExports(); /** * Preloads aka serializes all loaded objects. * * @return true if we finished serializing all loaded objects, false otherwise. */ EAsyncPackageState::Type PreLoadObjects(); /** * Route PostLoad to all loaded objects. This might load further objects! * * @return true if we finished calling PostLoad on all loaded objects and no new ones were created, false otherwise */ EAsyncPackageState::Type PostLoadObjects(); /** * Finish up objects and state, which means clearing the RF_AsyncLoading flag on newly created ones * * @return true */ EAsyncPackageState::Type FinishObjects(); /** * Function called when pending import package has been loaded. */ void ImportFullyLoadedCallback(const FName& PackageName, UPackage* LoadedPackage, EAsyncLoadingResult::Type Result); /** * Adds dependency tree to the list if packages to wait for until their linkers have been created. * * @param ImportedPackage Package imported either directly or by one of the imported packages */ void AddDependencyTree(int32 CurrentPackageIndex, FAsyncPackage& ImportedPackage, TSet<FAsyncPackage*>& SearchedPackages); /** * Adds a unique package to the list of packages to wait for until their linkers have been created. * * @param PendingImport Package imported either directly or by one of the imported packages */ bool AddUniqueLinkerDependencyPackage(int32 CurrentPackageIndex, FAsyncPackage& PendingImport); /** * Adds a package to the list of pending import packages. * * @param PendingImport Name of the package imported either directly or by one of the imported packages */ void AddImportDependency(int32 CurrentPackageIndex, const FName& PendingImport); /** * Removes references to any imported packages. */ void FreeReferencedImports(); /** * Updates load percentage stat */ void UpdateLoadPercentage(); #if PERF_TRACK_DETAILED_ASYNC_STATS /** Add this time taken for object of class Class to have CreateExport called, to the stats we track. */ void TrackCreateExportTimeForClass(const UClass* Class, double Time); /** Add this time taken for object of class Class to have PostLoad called, to the stats we track. */ void TrackPostLoadTimeForClass(const UClass* Class, double Time); #endif // PERF_TRACK_DETAILED_ASYNC_STATS };
{ "content_hash": "45e85c62ead8e2270cc13b7f82c6a4e5", "timestamp": "", "source": "github", "line_count": 353, "max_line_length": 123, "avg_line_length": 34.388101983002834, "alnum_prop": 0.7013757311145893, "repo_name": "PopCap/GameIdea", "id": "29ba0d19c58e36904e22bf63ca293a903f166ea8", "size": "12139", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Engine/Source/Runtime/CoreUObject/Public/Serialization/AsyncLoading.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "ASP", "bytes": "238055" }, { "name": "Assembly", "bytes": "184134" }, { "name": "Batchfile", "bytes": "116983" }, { "name": "C", "bytes": "84264210" }, { "name": "C#", "bytes": "9612596" }, { "name": "C++", "bytes": "242290999" }, { "name": "CMake", "bytes": "548754" }, { "name": "CSS", "bytes": "134910" }, { "name": "GLSL", "bytes": "96780" }, { "name": "HLSL", "bytes": "124014" }, { "name": "HTML", "bytes": "4097051" }, { "name": "Java", "bytes": "757767" }, { "name": "JavaScript", "bytes": "2742822" }, { "name": "Makefile", "bytes": "1976144" }, { "name": "Objective-C", "bytes": "75778979" }, { "name": "Objective-C++", "bytes": "312592" }, { "name": "PAWN", "bytes": "2029" }, { "name": "PHP", "bytes": "10309" }, { "name": "PLSQL", "bytes": "130426" }, { "name": "Pascal", "bytes": "23662" }, { "name": "Perl", "bytes": "218656" }, { "name": "Python", "bytes": "21593012" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "2889614" }, { "name": "Tcl", "bytes": "1452" } ], "symlink_target": "" }
<?php /** * BaseGeolocatableArticle_CityStateZip * * This class has been auto-generated by the Doctrine ORM Framework * * @property string $name * @property string $city * @property string $state * @property string $zip * * @method string getName() Returns the current record's "name" value * @method string getCity() Returns the current record's "city" value * @method string getState() Returns the current record's "state" value * @method string getZip() Returns the current record's "zip" value * @method GeolocatableArticle_CityStateZip setName() Sets the current record's "name" value * @method GeolocatableArticle_CityStateZip setCity() Sets the current record's "city" value * @method GeolocatableArticle_CityStateZip setState() Sets the current record's "state" value * @method GeolocatableArticle_CityStateZip setZip() Sets the current record's "zip" value * * @package skeleton * @subpackage model * @author Your name here * @version SVN: $Id: Builder.php 6820 2009-11-30 17:27:49Z jwage $ */ abstract class BaseGeolocatableArticle_CityStateZip extends sfDoctrineRecord { public function setTableDefinition() { $this->setTableName('geolocatable_article__city_state_zip'); $this->hasColumn('name', 'string', 255, array( 'type' => 'string', 'length' => '255', )); $this->hasColumn('city', 'string', 255, array( 'type' => 'string', 'length' => '255', )); $this->hasColumn('state', 'string', 25, array( 'type' => 'string', 'length' => '25', )); $this->hasColumn('zip', 'string', 25, array( 'type' => 'string', 'length' => '25', )); } public function setUp() { parent::setUp(); $geolocatable0 = new Doctrine_Template_Geolocatable(array( 'fields' => array( 0 => 'city', 1 => 'state', 2 => 'zip', ), )); $this->actAs($geolocatable0); } }
{ "content_hash": "88a6e18f13d1583ac1d3f8cd6a4ce51a", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 97, "avg_line_length": 35.3968253968254, "alnum_prop": 0.5538116591928252, "repo_name": "Symfony-Plugins/csDoctrineActAsGeolocatablePlugin", "id": "9ed44ffc27edefe7c974be878287bb4f49925f2e", "size": "2230", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "test/fixtures/project/lib/model/base/BaseGeolocatableArticle_CityStateZip.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "17063" } ], "symlink_target": "" }
[Google Cloud Speech API][Product Documentation]: Google Cloud Speech API. - [Client Library Documentation][] - [Product Documentation][] ## Quick Start In order to use this library, you first need to go through the following steps: 1. [Select or create a Cloud Platform project.](https://console.cloud.google.com/project) 2. [Enable billing for your project.](https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project) 3. [Enable the Google Cloud Speech API.](https://console.cloud.google.com/apis/api/speech) 4. [Setup Authentication.](https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud/master/guides/authentication) ### Installation ``` $ gem install google-cloud-speech ``` ### Preview #### SpeechClient ```rb require "google/cloud/speech" speech_client = Google::Cloud::Speech.new language_code = "en-US" sample_rate_hertz = 44100 encoding = :FLAC config = { language_code: language_code, sample_rate_hertz: sample_rate_hertz, encoding: encoding } uri = "gs://gapic-toolkit/hello.flac" audio = { uri: uri } response = speech_client.recognize(config, audio) ``` ### Next Steps - Read the [Client Library Documentation][] for Google Cloud Speech API to see other available methods on the client. - Read the [Google Cloud Speech API Product documentation][Product Documentation] to learn more about the product and see How-to Guides. - View this [repository's main README](https://github.com/GoogleCloudPlatform/google-cloud-ruby/blob/master/README.md) to see the full list of Cloud APIs that we cover. [Client Library Documentation]: https://googlecloudplatform.github.io/google-cloud-ruby/#/docs/google-cloud-speech/latest/google/cloud/speech/v1 [Product Documentation]: https://cloud.google.com/speech
{ "content_hash": "129cbf49bc344515cbd1d7da2cb0c37c", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 144, "avg_line_length": 37.8936170212766, "alnum_prop": 0.7585626052779337, "repo_name": "CloudVLab/google-cloud-ruby", "id": "02f3f848d987f0c10a00b4bbe370dfa5a03a0813", "size": "1903", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "google-cloud-speech/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "25312" }, { "name": "CSS", "bytes": "1422" }, { "name": "DIGITAL Command Language", "bytes": "2216" }, { "name": "HTML", "bytes": "10040" }, { "name": "JavaScript", "bytes": "1862" }, { "name": "Ruby", "bytes": "13009495" }, { "name": "Shell", "bytes": "786" } ], "symlink_target": "" }
from netforce.model import Model, fields, get_model import time import re from netforce.access import get_active_company, get_active_user, check_permission_other class SplitProduction(Model): _name = "split.production" _transient = True _fields = { "order_id": fields.Many2One("production.order", "Production Order", required=True), "order_to_id": fields.Many2One("production.order", "To Production Order", required=True), "product_list": fields.Json("Product List"), "order_to_list": fields.Json("Production To List"), "product_id": fields.Many2One("product", "Product"), "planned_qty": fields.Decimal("Planned Qty", readonly=True), "actual_qty": fields.Decimal("Actual Qty", readonly=True), "split_qty": fields.Decimal("Split Qty"), "split_qty2": fields.Decimal("Split Secondary Qty"), "team_id": fields.Many2One("mfg.team", "Production Team"), "remark": fields.Char("Remark"), "ratio_method": fields.Selection([["planned", "Planned Qty"], ["actual", "Actual Qty"]], "Ratio Method", required=True), "journal_id": fields.Many2One("stock.journal", "Journal", required=True, condition=[["type", "=", "internal"]]), "container_id": fields.Many2One("stock.container", "Container"), "lines": fields.One2Many("split.production.line", "wizard_id", "Lines"), "remain_planned_qty": fields.Decimal("Remain Planned Qty", function="get_remain_planned_qty"), "remain_actual_qty": fields.Decimal("Remain Actual Qty", function="get_remain_actual_qty"), "approved_by_id": fields.Many2One("base.user", "Approved By", readonly=True), } def _get_planned_qty(self, context={}): order_id = int(context["refer_id"]) order = get_model("production.order").browse(order_id) return order.qty_planned def _get_actual_qty(self, context={}): order_id = int(context["refer_id"]) order = get_model("production.order").browse(order_id) return order.qty_received def _get_product(self, context={}): order_id = int(context["refer_id"]) order = get_model("production.order").browse(order_id) return order.product_id.id def _get_container_id(self, context={}): order_id = int(context["refer_id"]) order = get_model("production.order").browse(order_id) return order.container_id.id def _get_product_ids(self, context={}): order_id = int(context["refer_id"]) order = get_model("production.order").browse(order_id) prods = [] for comp in order.components: prods.append(comp.product_id.id) prods.append(order.product_id.id) return prods def _get_order_to_ids(self, context={}): order_id = int(context["refer_id"]) order = get_model("production.order").browse(order_id) order_to_ids = self.get_order_to_list(order.id) return order_to_ids _defaults = { "order_id": lambda self, ctx: int(ctx["refer_id"]), "planned_qty": _get_planned_qty, "actual_qty": _get_actual_qty, "product_id": _get_product, "product_list": _get_product_ids, "order_to_list": _get_order_to_ids, #"split_parents": True, "split_qty": 0, "container_id": _get_container_id, "ratio_method": "actual", "remain_planned_qty": _get_planned_qty, "remain_actual_qty": _get_actual_qty } def get_product_list(self, order_id): prods = [] order = get_model("production.order").browse(order_id) if order: for comp in order.components: prods.append(comp.product_id.id) prods.append(order.product_id.id) return prods def get_product_ids(self, ids, context={}): res = {} prods = [] obj = self.browse(ids)[0] order = obj.order_id if order: for comp in order.components: prods.append(comp.product_id.id) prods.append(order.product_id.id) res[obj.id] = prods return res def get_order_to_list(self, order_id): order_to_ids = [order_id] order = get_model("production.order").browse(order_id) order_parent = order.parent_id while order_parent: order_to_ids.append(order_parent.id) order_parent = order_parent.parent_id order_to_ids = list(set(order_to_ids)) return order_to_ids def get_order_to_ids(self, ids, context={}): res = {} obj = self.browse(ids)[0] order_id = obj.order_id.id res[obj.id] = self.get_order_to_list(order_id) return res def get_remain_actual_qty(self, ids, context={}): res = {} obj = self.browse(ids)[0] if obj.ratio_method == "actual": total_qty = 0 for line in obj.lines: total_qty += line.qty res[obj.id] = obj.actual_qty - total_qty else: res[obj.id] = obj.actual_qty return res def get_remain_planned_qty(self, ids, context={}): res = {} obj = self.browse(ids)[0] if obj.ratio_method == "planned": total_qty = 0 for line in obj.lines: total_qty += line.qty res[obj.id] = obj.planned_qty - total_qty else: res[obj.id] = obj.planned_qty return res def onchange_order(self, context={}): data = context["data"] order_id = data["order_id"] order = get_model("production.order").browse(order_id) data["product_list"] = self.get_product_list(order_id) data["product_id"] = order.product_id.id data["order_to_list"] = self.get_order_to_list(order_id) data["order_to_id"] = None self.onchange_product(context) return data def get_split_num(self, root_num, context={}): root_num = re.sub("-P[0-9][0-9]$", "", root_num) for i in range(2, 100): num = root_num + "-P%.2d" % i res = get_model("production.order").search([["number", "=", num]]) if not res: return num raise Exception("Failed to generate production order number (root=%s)" % root_num) def get_split_container(self, prev_cont_num, order_num, context={}): part_no = order_num.rpartition("-")[2] if not part_no or not part_no.startswith("P") or not len(part_no) == 3: raise Exception("Can not find split part number of production order %s" % order_num) new_cont_num = prev_cont_num + "-" + part_no res = get_model("stock.container").search([["number", "=", new_cont_num]]) if res: new_cont_id = res[0] else: vals = { "number": new_cont_num, } new_cont_id = get_model("stock.container").create(vals) return new_cont_id def check_split_container(self, order_comp_id): return True def get_lot(self, new_lot_num, context={}): res = get_model("stock.lot").search([["number", "=", new_lot_num]]) if res: new_lot_id = res[0] else: vals = { "number": new_lot_num, } new_lot_id = get_model("stock.lot").create(vals) return new_lot_id def copy_order(self, order_id, qty, team_id, remark): order = get_model("production.order").browse(order_id) old_order_num = order.number new_order_num = self.get_split_num(old_order_num) vals = { "number": new_order_num, "order_date": time.strftime("%Y-%m-%d"), "due_date": order.due_date, "ref": order.ref, "sale_id": order.sale_id.id, "parent_id": order.parent_id.id, "product_id": order.product_id.id, "qty_planned": qty, "uom_id": order.uom_id.id, "bom_id": order.bom_id.id, "routing_id": order.routing_id.id, "production_location_id": order.production_location_id.id, "location_id": order.location_id.id, "team_id": team_id, "remark": remark, "state": order.state, "components": [], "operations": [], "qc_tests": [], } if order.container_id: vals["container_id"] = self.get_split_container(order.container_id.number, new_order_num) if order.lot_id and order.lot_id.number == old_order_num: # XXX vals["lot_id"] = self.get_lot(new_order_num) ratio = qty / order.qty_planned for comp in order.components: comp_vals = { "product_id": comp.product_id.id, "qty_planned": round(comp.qty_planned * ratio, 2), "uom_id": comp.uom_id.id, "location_id": comp.location_id.id, "issue_method": comp.issue_method, "container_id": comp.container_id.id, } if comp.container_id and self.check_split_container(comp.id): # MTS need no need to split scrap box comp_vals["container_id"] = self.get_split_container(comp.container_id.number, new_order_num) # if comp.lot_id and comp.lot_id.number==old_order_num: # XXX # comp_vals["lot_id"]=self.get_lot(new_order_num) comp_vals["lot_id"] = comp.lot_id.id # Should be old number vals["components"].append(("create", comp_vals)) for op in order.operations: op_vals = { "workcenter_id": op.workcenter_id.id, "employee_id": op.employee_id.id, "planned_duration": op.planned_duration * ratio, } vals["operations"].append(("create", op_vals)) for qc in order.qc_tests: qc_vals = { "test_id": qc.test_id.id, } vals["qc_tests"].append(("create", qc_vals)) new_id = get_model("production.order").create(vals) return new_id def modif_order(self, order_id, qty, team_id, remark): order = get_model("production.order").browse(order_id) ratio = qty / order.qty_planned old_order_num = order.number new_order_num = old_order_num + "-P01" vals = { "number": new_order_num, "qty_planned": round(order.qty_planned * ratio, 2), "team_id": team_id, "remark": remark, } if order.container_id: vals["container_id"] = self.get_split_container(order.container_id.number, new_order_num) if order.lot_id and order.lot_id.number == old_order_num: # XXX vals["lot_id"] = self.get_lot(new_order_num) order.write(vals) for comp in order.components: vals = { "qty_planned": round(comp.qty_planned * ratio, 2), } if comp.container_id and self.check_split_container(comp.id): # MTS no need to split scrap box vals["container_id"] = self.get_split_container(comp.container_id.number, new_order_num) # if comp.lot_id and comp.lot_id.number==old_order_num: # XXX # vals["lot_id"]=self.get_lot(new_order_num) vals["lot_id"] = comp.lot_id.id # Should be old number comp.write(vals) for op in order.operations: vals = { "planned_duration": op.planned_duration * ratio, } op.write(vals) def split_order(self, order_id, ratios): order = get_model("production.order").browse(order_id) if order.state not in ("draft", "waiting_confirm", "waiting_material", "waiting_suborder", "ready", "in_progress"): raise Exception("Invalid state to split order (%s)" % order.number) for r in ratios[:1]: split_ids = [(r[2], order_id)] for r in ratios[1:]: split_qty = order.qty_planned * r[0] team_id = r[1] remark = r[3] split_id = self.copy_order(order.id, split_qty, team_id, remark) split_ids.append((r[2], split_id)) r = ratios[0] split_qty = order.qty_planned * r[0] team_id = r[1] remark = r[3] self.modif_order(order.id, split_qty, team_id, remark) for sub in order.sub_orders: if sub.state not in ("draft", "waiting_confirm", "waiting_material", "waiting_suborder", "ready", "in_progress"): continue sub_split_ids = self.split_order(sub.id, ratios) if sub.sub_orders: split_ids += sub_split_ids for i in range(len(sub_split_ids)): sub_split_id = sub_split_ids[i][1] split_id = split_ids[i][1] get_model("production.order").write([sub_split_id], {"parent_id": split_id}) return split_ids def do_split(self, ids, context={}): obj = self.browse(ids)[0] if not obj.approved_by_id: raise Exception("Split order has to be approved first") order = obj.order_id if len(obj.lines) < 2: raise Exception("Split needs at least 2 lines") total_qty = sum(l.qty for l in obj.lines) if not obj.ratio_method: raise Exception("Please select ratio method") if obj.ratio_method == "planned" and abs(total_qty - obj.planned_qty) > 0.01: raise Exception("Total split qty has to be equal to planned qty") if obj.ratio_method == "actual" and abs(total_qty - obj.actual_qty) > 0.01: raise Exception("Total split qty has to be equal to actual qty") ratios = [] if obj.ratio_method == "planned": for line in obj.lines: ratios.append((line.qty / obj.planned_qty, line.team_id.id, line.id, line.remark)) elif obj.ratio_method == "actual": for line in obj.lines: ratios.append((line.qty / obj.actual_qty, line.team_id.id, line.id, line.remark)) split_order = order if obj.order_to_id: # if obj.split_parents: while split_order.parent_id: split_order = split_order.parent_id if split_order.id == obj.order_to_id.id: break split_order_ids = self.split_order(split_order.id, ratios) # Combine Split Order end_order = obj.order_id.parent_id if obj.order_to_id and obj.order_to_id.parent_id: end_order = obj.order_to_id.parent_id if end_order: comps = [] for end_sub in end_order.sub_orders: for comp in end_order.components: if comp.product_id.id == end_sub.product_id.id: comps.append((comp.product_id.id, comp.location_id.id, comp.issued_method)) comp.delete() comps = list(set(comps)) for prod_id, loc_id, issued_method in comps: for end_sub in end_order.sub_orders: if end_sub.product_id.id == prod_id: vals = { "order_id": end_order.id, "product_id": end_sub.product_id.id, "qty_planned": end_sub.qty_planned, "uom_id": end_sub.uom_id.id, "location_id": loc_id, "issue_method": issued_method, "lot_id": end_sub.lot_id.id, "container_id": end_sub.container_id.id, } get_model("production.component").create(vals) if obj.ratio_method == "actual": self.split_transfer(split_order_ids=split_order_ids, split_prod_id=obj.id) return { "next": { "name": "production", }, "flash": "Order split successfully", } def split_transfer(self, split_order_ids, split_prod_id): split_prod = get_model("split.production").browse(split_prod_id) pick_vals = { "type": "internal", "journal_id": split_prod.journal_id.id, "lines": [], "done_approved_by_id": split_prod.approved_by_id.id } for split_line, split_order_id in split_order_ids: split_order = get_model("production.order").browse(split_order_id) for line in split_prod.lines: cont_to_id = None lot_id = None if line.id == split_line: if split_prod.product_id.id == split_order.product_id.id: lot_id = split_order.lot_id.id cont_to_id = split_order.container_id.id else: for comp in split_order.components: if split_prod.product_id.id == comp.product_id.id: lot_id = comp.lot_id.id cont_to_id = comp.container_id.id if cont_to_id: break if cont_to_id: move_vals = { "product_id": split_prod.product_id.id, "qty": line.qty, "uom_id": split_prod.product_id.uom_id.id, "qty2": line.qty2, "lot_id": lot_id, "location_from_id": split_prod.order_id.location_id.id, "location_to_id": split_prod.order_id.location_id.id, "container_from_id": split_prod.container_id.id, "container_to_id": cont_to_id, } pick_vals["lines"].append(("create", move_vals)) if len(pick_vals["lines"]) > 0: pick_id = get_model("stock.picking").create(pick_vals, context=pick_vals) get_model("stock.picking").set_done([pick_id]) split_order_ids.reverse() for order_id in split_order_ids: order = get_model("production.order").browse(order_id[1]) if order.parent_id: order.parent_id.update_status() def approve(self, ids, context={}): if not check_permission_other("production_approve_split"): raise Exception("Permission denied") obj = self.browse(ids)[0] user_id = get_active_user() obj.write({"approved_by_id": user_id}) return { "next": { "name": "split_production", "active_id": obj.id, }, "flash": "Split order approved successfully", } def onchange_product(self, context={}): data = context["data"] order_id = data["order_id"] order = get_model("production.order").browse(order_id) prod_id = data["product_id"] data["planned_qty"] = 0 data["actual_qty"] = 0 if order.product_id.id == prod_id: data["planned_qty"] = order.qty_planned data["actual_qty"] = order.qty_received data["container_id"] = order.container_id.id else: for comp in order.components: if comp.product_id.id == prod_id: data["planned_qty"] = comp.qty_planned data["actual_qty"] = comp.qty_stock data["container_id"] = comp.container_id.id data["remain_planned_qty"] = data["planned_qty"] data["remain_actual_qty"] = data["actual_qty"] return data def add_lines(self, ids, context={}): obj = self.browse(ids)[0] if not obj.ratio_method: raise Exception("Invalid Ratio Method") remain = obj.remain_planned_qty if obj.ratio_method == "planned" else obj.remain_actual_qty total_qty = 0 for line in obj.lines: if line.product_id.id != obj.product_id.id \ or line.ratio_method != obj.ratio_method: line.delete() for line in obj.lines: total_qty += line.qty if obj.split_qty != 0 and remain + 0.001 >= obj.split_qty: # part_no=len(obj.lines)+1 # cont_num=obj.container_id.number+"-P%.2d"%part_no vals = { "wizard_id": obj.id, "ratio_method": obj.ratio_method, "product_id": obj.product_id.id, "qty": obj.split_qty, "qty2": obj.split_qty2, "team_id": obj.team_id.id, "remark": obj.remark, #"container_num": cont_num, } get_model("split.production.line").create(vals) # part_no=1 # for line in obj.lines: # cont_num=obj.container_id.number+"-P%.2d"%part_no #line.write({"container_num": cont_num}) # part_no+=1 obj.split_qty = 0 obj.team_id = None else: raise Exception("Split Qty is too high!") return { "flash": "Add line success", "focus_field": "split_qty" } def clear_lines(self, ids, context={}): obj = self.browse(ids)[0] obj.write({"lines": [("delete_all",)]}) return { "flash": "Clear all split lines", "focus_field": "split_qty" } SplitProduction.register()
{ "content_hash": "d8d4c68fcb8df3ef0b3838525376dcc8", "timestamp": "", "source": "github", "line_count": 508, "max_line_length": 128, "avg_line_length": 42.47047244094488, "alnum_prop": 0.533117033603708, "repo_name": "nfco/netforce", "id": "921aed028b5b3c1bed3479dc5b38adedc9daa296", "size": "22680", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "netforce_mfg/netforce_mfg/models/split_production.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "73" }, { "name": "CSS", "bytes": "407336" }, { "name": "HTML", "bytes": "478918" }, { "name": "Java", "bytes": "11870" }, { "name": "JavaScript", "bytes": "3712147" }, { "name": "Makefile", "bytes": "353" }, { "name": "PHP", "bytes": "2274" }, { "name": "Python", "bytes": "3469515" }, { "name": "Roff", "bytes": "15858" }, { "name": "Shell", "bytes": "117" } ], "symlink_target": "" }
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new rra\TestBundle\rraTestBundle(), new Knp\Bundle\PaginatorBundle\KnpPaginatorBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
{ "content_hash": "b436d404de51c2ae4b35a15e989735c2", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 89, "avg_line_length": 38.833333333333336, "alnum_prop": 0.6680972818311874, "repo_name": "rura/TestProject", "id": "b53682b74b46dd02ac4022b948f1d8fa3d0e17ce", "size": "1398", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/AppKernel.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "407" }, { "name": "JavaScript", "bytes": "1965" }, { "name": "PHP", "bytes": "53938" } ], "symlink_target": "" }
set -e set -x # Update the entire system to the latest releases apt-get update -qq apt-get dist-upgrade -qqy # install git apt-get install --yes git # Set Go environment variables needed by other scripts export GOPATH="/opt/gopath" #install golang #apt-get install --yes golang mkdir -p $GOPATH MACHINE=`uname -m` if [ x$MACHINE = xs390x ] then apt-get install --yes golang export GOROOT="/usr/lib/go-1.6" elif [ x$MACHINE = xppc64 ] then echo "TODO: Add PPC support" exit elif [ x$MACHINE = xx86_64 ] then export GOROOT="/opt/go" #ARCH=`uname -m | sed 's|i686|386|' | sed 's|x86_64|amd64|'` ARCH=amd64 GO_VER=1.6 cd /tmp wget --quiet --no-check-certificate https://storage.googleapis.com/golang/go$GO_VER.linux-${ARCH}.tar.gz tar -xvf go$GO_VER.linux-${ARCH}.tar.gz mv go $GOROOT chmod 775 $GOROOT rm go$GO_VER.linux-${ARCH}.tar.gz fi PATH=$GOROOT/bin:$GOPATH/bin:$PATH cat <<EOF >/etc/profile.d/goroot.sh export GOROOT=$GOROOT export GOPATH=$GOPATH export PATH=\$PATH:$GOROOT/bin:$GOPATH/bin EOF # Install NodeJS if [ x$MACHINE = xs390x ] then apt-get install --yes nodejs else NODE_VER=0.12.7 NODE_PACKAGE=node-v$NODE_VER-linux-x64.tar.gz TEMP_DIR=/tmp SRC_PATH=$TEMP_DIR/$NODE_PACKAGE # First remove any prior packages downloaded in case of failure cd $TEMP_DIR rm -f node*.tar.gz wget --quiet https://nodejs.org/dist/v$NODE_VER/$NODE_PACKAGE cd /usr/local && sudo tar --strip-components 1 -xzf $SRC_PATH fi # Install GRPC # ---------------------------------------------------------------- # NOTE: For instructions, see https://github.com/google/protobuf # # ---------------------------------------------------------------- # First install protoc cd /tmp wget --quiet https://github.com/google/protobuf/archive/v3.0.0.tar.gz tar xpzf v3.0.0.tar.gz cd protobuf-3.0.0 apt-get install -y autoconf automake libtool curl make g++ unzip apt-get install -y build-essential ./autogen.sh # NOTE: By default, the package will be installed to /usr/local. However, on many platforms, /usr/local/lib is not part of LD_LIBRARY_PATH. # You can add it, but it may be easier to just install to /usr instead. # # To do this, invoke configure as follows: # # ./configure --prefix=/usr # #./configure ./configure --prefix=/usr if [ x$MACHINE = xs390x ] then echo FIXME: protobufs wont compile on 390, missing atomic call else make make check make install fi export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH cd ~/ # Install rocksdb apt-get install -y libsnappy-dev zlib1g-dev libbz2-dev cd /tmp git clone https://github.com/facebook/rocksdb.git cd rocksdb git checkout tags/v4.1 if [ x$MACHINE = xs390x ] then echo There were some bugs in 4.1 for x/p, dev stream has the fix, living dangereously, fixing in place sed -i -e "s/-march=native/-march=z196/" build_tools/build_detect_platform sed -i -e "s/-momit-leaf-frame-pointer/-DDUMBDUMMY/" Makefile fi PORTABLE=1 make shared_lib INSTALL_PATH=/usr/local make install-shared ldconfig cd ~/ # Make our versioning persistent echo $BASEIMAGE_RELEASE > /etc/hyperledger-baseimage-release # clean up our environment apt-get -y autoremove apt-get clean rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
{ "content_hash": "2a5c8d0882c32d902c1e6f7435f38f60", "timestamp": "", "source": "github", "line_count": 129, "max_line_length": 139, "avg_line_length": 25.27906976744186, "alnum_prop": 0.6780128794848206, "repo_name": "gabre/fabric", "id": "b62d4be4dca23db6c19ba30263e93039880e32b1", "size": "3592", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "images/base/scripts/common/setup.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Cucumber", "bytes": "84042" }, { "name": "Gnuplot", "bytes": "1827" }, { "name": "Go", "bytes": "2092863" }, { "name": "Java", "bytes": "86505" }, { "name": "JavaScript", "bytes": "52464" }, { "name": "Makefile", "bytes": "14421" }, { "name": "Protocol Buffer", "bytes": "45450" }, { "name": "Python", "bytes": "81060" }, { "name": "Ruby", "bytes": "3180" }, { "name": "Shell", "bytes": "49612" }, { "name": "TypeScript", "bytes": "127713" } ], "symlink_target": "" }
#include <OgreRoot.h> #include "OgreOctreeZonePlugin.h" #include "OgrePCZSceneManager.h" namespace Ogre { const String sPluginName = "Octree Zone Factory"; //--------------------------------------------------------------------- OctreeZonePlugin::OctreeZonePlugin() :mOctreeZoneFactory(0) { } //--------------------------------------------------------------------- const String& OctreeZonePlugin::getName() const { return sPluginName; } //--------------------------------------------------------------------- void OctreeZonePlugin::install() { // Create objects mOctreeZoneFactory = OGRE_NEW OctreeZoneFactory(); } //--------------------------------------------------------------------- void OctreeZonePlugin::initialise() { // Register PCZoneFactoryManager & pczfm = PCZoneFactoryManager::getSingleton(); pczfm.registerPCZoneFactory(mOctreeZoneFactory); } //--------------------------------------------------------------------- void OctreeZonePlugin::shutdown() { // Unregister PCZoneFactoryManager & pczfm = PCZoneFactoryManager::getSingleton(); pczfm.unregisterPCZoneFactory(mOctreeZoneFactory); } //--------------------------------------------------------------------- void OctreeZonePlugin::uninstall() { // destroy OGRE_DELETE mOctreeZoneFactory; mOctreeZoneFactory = 0; } }
{ "content_hash": "1afa69e475a74872c132c0a9578d4f09", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 72, "avg_line_length": 26.274509803921568, "alnum_prop": 0.503731343283582, "repo_name": "largerussiangames/ogre", "id": "def9a9b7e3182b89e27f01c4451be3a0f8b54f03", "size": "3062", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "PlugIns/OctreeZone/src/OgreOctreeZonePlugin.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "3297565" }, { "name": "C++", "bytes": "18380381" }, { "name": "Objective-C", "bytes": "478206" }, { "name": "Python", "bytes": "421604" }, { "name": "Shell", "bytes": "19001" }, { "name": "Visual Basic", "bytes": "1095" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_43) on Tue Apr 09 16:55:13 ICT 2013 --> <TITLE> Uses of Class org.apache.hadoop.examples.SecondarySort.FirstPartitioner (Hadoop 1.0.4-SNAPSHOT API) </TITLE> <META NAME="date" CONTENT="2013-04-09"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class org.apache.hadoop.examples.SecondarySort.FirstPartitioner (Hadoop 1.0.4-SNAPSHOT API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/examples/SecondarySort.FirstPartitioner.html" title="class in org.apache.hadoop.examples"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/hadoop/examples//class-useSecondarySort.FirstPartitioner.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SecondarySort.FirstPartitioner.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.hadoop.examples.SecondarySort.FirstPartitioner</B></H2> </CENTER> No usage of org.apache.hadoop.examples.SecondarySort.FirstPartitioner <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/hadoop/examples/SecondarySort.FirstPartitioner.html" title="class in org.apache.hadoop.examples"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?org/apache/hadoop/examples//class-useSecondarySort.FirstPartitioner.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SecondarySort.FirstPartitioner.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; 2009 The Apache Software Foundation </BODY> </HTML>
{ "content_hash": "ddb02bd259e953b344d94331b0e3263d", "timestamp": "", "source": "github", "line_count": 144, "max_line_length": 240, "avg_line_length": 43.06944444444444, "alnum_prop": 0.627378265075782, "repo_name": "jrnz/hadoop", "id": "1e68d3659338e7b331b674c9b5bcc6f1966da79c", "size": "6202", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "build/docs/api/org/apache/hadoop/examples/class-use/SecondarySort.FirstPartitioner.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "401082" }, { "name": "C++", "bytes": "403118" }, { "name": "Java", "bytes": "16204516" }, { "name": "JavaScript", "bytes": "132758" }, { "name": "Objective-C", "bytes": "119767" }, { "name": "PHP", "bytes": "152555" }, { "name": "Perl", "bytes": "149888" }, { "name": "Python", "bytes": "1533822" }, { "name": "Ruby", "bytes": "28485" }, { "name": "Shell", "bytes": "2460133" }, { "name": "Smalltalk", "bytes": "56562" }, { "name": "XML", "bytes": "235590" } ], "symlink_target": "" }
require_relative '../../minitest_helper' require 'bmff/box' require 'stringio' class TestBMFFBoxSubSampleInformation < Minitest::Test def test_parse_v0 io = StringIO.new("", "r+:ascii-8bit") io.extend(BMFF::BinaryAccessor) io.write_uint32(0) io.write_ascii("subs") io.write_uint8(0) # version io.write_uint24(0) # flags io.write_uint32(3) # entry_count # entry 3.times do |i| io.write_uint32(i) # sample_delta io.write_uint16(2) # subsample_count 2.times do |j| io.write_uint16(j) # subsample_size io.write_uint8(10 + j) # subsample_priority io.write_uint8(0) # discardable io.write_uint32(0) # reserved1 end end size = io.pos io.pos = 0 io.write_uint32(size) io.pos = 0 box = BMFF::Box.get_box(io, nil) assert_instance_of(BMFF::Box::SubSampleInformation, box) assert_equal(size, box.actual_size) assert_equal("subs", box.type) assert_equal(0, box.version) assert_equal(0, box.flags) assert_equal(3, box.entry_count) assert_equal([0, 1, 2], box.sample_delta) assert_equal([2, 2, 2], box.subsample_count) 3.times do |i| assert_equal([0, 1], box.subsamples[i].subsample_size) assert_equal([10, 11], box.subsamples[i].subsample_priority) assert_equal([0, 0], box.subsamples[i].discardable) assert_equal([0, 0], box.subsamples[i].reserved1) end end def test_parse_v1 io = StringIO.new("", "r+:ascii-8bit") io.extend(BMFF::BinaryAccessor) io.write_uint32(0) io.write_ascii("subs") io.write_uint8(1) # version io.write_uint24(0) # flags io.write_uint32(3) # entry_count # entry 3.times do |i| io.write_uint32(i) # sample_delta io.write_uint16(2) # subsample_count 2.times do |j| io.write_uint32(j) # subsample_size io.write_uint8(10 + j) # subsample_priority io.write_uint8(0) # discardable io.write_uint32(0) # reserved1 end end size = io.pos io.pos = 0 io.write_uint32(size) io.pos = 0 box = BMFF::Box.get_box(io, nil) assert_instance_of(BMFF::Box::SubSampleInformation, box) assert_equal(size, box.actual_size) assert_equal("subs", box.type) assert_equal(1, box.version) assert_equal(0, box.flags) assert_equal(3, box.entry_count) assert_equal([0, 1, 2], box.sample_delta) assert_equal([2, 2, 2], box.subsample_count) 3.times do |i| assert_equal([0, 1], box.subsamples[i].subsample_size) assert_equal([10, 11], box.subsamples[i].subsample_priority) assert_equal([0, 0], box.subsamples[i].discardable) assert_equal([0, 0], box.subsamples[i].reserved1) end end end
{ "content_hash": "e39e4437345cc0107213f15505c580ab", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 66, "avg_line_length": 31.402298850574713, "alnum_prop": 0.6255490483162518, "repo_name": "zuku/bmff", "id": "6f460c5c9c985872ad5fe58399dea108b71ce8fc", "size": "2819", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/bmff/box/test_sub_sample_information.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "234623" } ], "symlink_target": "" }
ActiveRecord::Schema.define(:version => 20120819175835) do create_table "adesoes", :force => true do |t| t.integer "topico_id", :null => false t.integer "user_id", :null => false t.datetime "created_at" t.datetime "updated_at" end add_index "adesoes", ["created_at"], :name => "index_adesoes_on_created_at" add_index "adesoes", ["topico_id", "user_id"], :name => "index_adesoes_on_topico_id_and_user_id", :unique => true add_index "adesoes", ["topico_id"], :name => "index_adesoes_on_topico_id" add_index "adesoes", ["user_id"], :name => "index_adesoes_on_user_id" create_table "bairros", :force => true do |t| t.string "nome" t.integer "cidade_id" t.datetime "created_at" t.datetime "updated_at" t.integer "relevancia", :default => 0 end add_index "bairros", ["cidade_id", "nome"], :name => "index_bairros_on_cidade_id_and_nome" add_index "bairros", ["relevancia"], :name => "index_bairros_on_relevancia" create_table "cidades", :force => true do |t| t.string "nome" t.integer "estado_id" t.string "slug" t.datetime "created_at" t.datetime "updated_at" t.integer "relevancia", :default => 0 end add_index "cidades", ["estado_id", "nome"], :name => "index_cidades_on_estado_id_and_nome" add_index "cidades", ["relevancia"], :name => "index_cidades_on_relevancia" add_index "cidades", ["slug"], :name => "index_cidades_on_slug" create_table "comments", :force => true do |t| t.integer "commentable_id", :default => 0 t.string "commentable_type", :limit => 15, :default => "" t.text "body" t.integer "user_id", :default => 0, :null => false t.integer "parent_id" t.integer "lft" t.integer "rgt" t.string "tipo", :limit => 20, :default => "" t.datetime "created_at" t.datetime "updated_at" end add_index "comments", ["commentable_id", "commentable_type"], :name => "index_comments_on_commentable_id_and_commentable_type" add_index "comments", ["commentable_id"], :name => "index_comments_on_commentable_id" add_index "comments", ["user_id"], :name => "index_comments_on_user_id" create_table "estados", :force => true do |t| t.string "nome" t.string "abrev" t.datetime "created_at" t.datetime "updated_at" t.integer "relevancia", :default => 0 end add_index "estados", ["abrev"], :name => "index_estados_on_abrev" add_index "estados", ["relevancia"], :name => "index_estados_on_relevancia" create_table "historico_de_logins", :force => true do |t| t.integer "user_id" t.datetime "created_at" t.string "ip" end add_index "historico_de_logins", ["created_at"], :name => "index_historico_de_logins_on_created_at" add_index "historico_de_logins", ["user_id"], :name => "index_historico_de_logins_on_user_id" create_table "imagens", :force => true do |t| t.integer "responsavel_id" t.string "responsavel_type" t.integer "size" t.string "content_type" t.string "filename" t.integer "height" t.integer "width" t.integer "parent_id" t.string "thumbnail" t.integer "position" t.string "legenda" t.datetime "created_at" t.datetime "updated_at" end add_index "imagens", ["responsavel_id", "responsavel_type"], :name => "by_responsavel_id_and_type" create_table "links", :force => true do |t| t.string "nome" t.string "url" t.integer "position" t.integer "topico_id" t.datetime "created_at" t.datetime "updated_at" end add_index "links", ["topico_id", "position"], :name => "index_links_on_topico_id_and_position" create_table "locais", :force => true do |t| t.integer "responsavel_id" t.string "responsavel_type" t.integer "bairro_id" t.integer "cidade_id" t.decimal "lat", :precision => 15, :scale => 10 t.decimal "lng", :precision => 15, :scale => 10 t.datetime "created_at" t.datetime "updated_at" t.string "cep", :limit => 10 t.integer "estado_id" t.integer "pais_id" end add_index "locais", ["bairro_id"], :name => "index_locais_on_bairro_id" add_index "locais", ["cidade_id"], :name => "index_locais_on_cidade_id" add_index "locais", ["estado_id"], :name => "index_locais_on_estado_id" add_index "locais", ["pais_id"], :name => "index_locais_on_pais_id" add_index "locais", ["responsavel_id", "responsavel_type"], :name => "index_locais_on_responsavel_id_and_responsavel_type" create_table "nings", :force => true do |t| t.integer "user_id" t.integer "source_id" t.string "owner_id" t.string "apps_id" t.datetime "created_at" t.datetime "updated_at" end create_table "observatorios", :force => true do |t| t.integer "user_id" t.string "nome" t.boolean "receber_email", :default => true t.datetime "created_at" t.datetime "updated_at" end add_index "observatorios", ["user_id"], :name => "index_observatorios_on_user_id" create_table "observatorios_tem_tags", :id => false, :force => true do |t| t.integer "observatorio_id" t.integer "tag_id" end add_index "observatorios_tem_tags", ["observatorio_id", "tag_id"], :name => "index_observatorios_tem_tags_on_observatorio_id_and_tag_id", :unique => true create_table "paises", :force => true do |t| t.string "iso", :limit => 2 t.string "nome" t.datetime "created_at" t.datetime "updated_at" end create_table "plugin_schema_migrations", :id => false, :force => true do |t| t.string "plugin_name" t.string "version" end create_table "seguidos", :force => true do |t| t.integer "topico_id", :null => false t.integer "user_id", :null => false t.datetime "created_at" t.datetime "updated_at" end add_index "seguidos", ["user_id", "topico_id"], :name => "index_seguidos_on_user_id_and_topico_id", :unique => true create_table "sessions", :force => true do |t| t.string "session_id", :null => false t.text "data" t.datetime "created_at" t.datetime "updated_at" end add_index "sessions", ["session_id"], :name => "index_sessions_on_session_id" add_index "sessions", ["updated_at"], :name => "index_sessions_on_updated_at" create_table "settings", :force => true do |t| t.string "var", :null => false t.text "value" t.datetime "created_at" t.datetime "updated_at" end add_index "settings", ["var"], :name => "index_settings_on_var" create_table "taggings", :force => true do |t| t.integer "tag_id" t.integer "taggable_id" t.integer "tagger_id" t.string "tagger_type" t.string "taggable_type", :limit => 20 t.string "context", :limit => 40 t.datetime "created_at" t.string "tagger_site" end add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id" add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "tag_tag_tag_context" create_table "tags", :force => true do |t| t.string "name" t.integer "relevancia", :default => 0 end add_index "tags", ["name"], :name => "index_tags_on_name" add_index "tags", ["relevancia"], :name => "index_tags_on_relevancia" create_table "topicos", :force => true do |t| t.string "type", :limit => 20 t.integer "user_id", :null => false t.string "titulo" t.text "descricao" t.text "complementar" t.integer "parent_id" t.string "slug" t.datetime "created_at" t.datetime "updated_at" t.integer "comments_count", :default => 0 t.integer "adesoes_count", :default => 0 t.integer "relevancia", :default => 0 t.integer "seguidores_count", :default => 0 t.string "site" end add_index "topicos", ["adesoes_count"], :name => "index_topicos_on_adesoes_count" add_index "topicos", ["comments_count"], :name => "index_topicos_on_comments_count" add_index "topicos", ["parent_id"], :name => "index_topicos_on_parent_id" add_index "topicos", ["relevancia"], :name => "index_topicos_on_relevancia" add_index "topicos", ["seguidores_count"], :name => "index_topicos_on_seguidores_count" add_index "topicos", ["slug"], :name => "index_topicos_on_slug" add_index "topicos", ["type"], :name => "index_topicos_on_type" add_index "topicos", ["user_id"], :name => "index_topicos_on_user_id" create_table "user_dados", :force => true do |t| t.integer "user_id", :null => false t.string "nome", :limit => 100 t.string "fone", :limit => 20 t.string "email_de_contato", :limit => 60 t.string "site_url" t.text "descricao" t.string "sexo", :limit => 1, :default => "" t.date "aniversario" t.string "fax", :limit => 20 t.datetime "created_at" t.datetime "updated_at" end add_index "user_dados", ["nome"], :name => "index_user_dados_on_nome" add_index "user_dados", ["user_id"], :name => "index_user_dados_on_user_id", :unique => true create_table "users", :force => true do |t| t.string "login", :limit => 100 t.string "name", :limit => 100, :default => "" t.string "email", :limit => 100 t.string "crypted_password", :limit => 40 t.string "salt", :limit => 40 t.datetime "created_at" t.datetime "updated_at" t.string "remember_token", :limit => 40 t.datetime "remember_token_expires_at" t.string "activation_code", :limit => 40 t.datetime "activated_at" t.string "state", :default => "passive" t.datetime "deleted_at" t.string "type", :limit => 20 t.integer "parent_id" t.string "slug" t.integer "topicos_count", :default => 0 t.integer "comments_count", :default => 0 t.integer "adesoes_count", :default => 0 t.integer "relevancia", :default => 0 end add_index "users", ["adesoes_count"], :name => "index_users_on_adesoes_count" add_index "users", ["comments_count"], :name => "index_users_on_comments_count" add_index "users", ["email"], :name => "index_users_on_email", :unique => true add_index "users", ["login"], :name => "index_users_on_login", :unique => true add_index "users", ["parent_id"], :name => "index_users_on_parent_id" add_index "users", ["relevancia"], :name => "index_users_on_relevancia" add_index "users", ["slug"], :name => "index_users_on_slug" add_index "users", ["state"], :name => "users_state", :length => {"state"=>12} add_index "users", ["topicos_count"], :name => "index_users_on_topicos_count" add_index "users", ["type"], :name => "index_users_on_type" end
{ "content_hash": "6393864079fbbe835568bd0045fd6909", "timestamp": "", "source": "github", "line_count": 290, "max_line_length": 155, "avg_line_length": 38.6, "alnum_prop": 0.5804002144005718, "repo_name": "cidadedemocratica/USPocupa", "id": "dd47d2112fb2295a4269140e20a15cabb87e8d3a", "size": "11910", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/schema.rb", "mode": "33261", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "90222" }, { "name": "Ruby", "bytes": "289385" } ], "symlink_target": "" }
package com.metaui.core.datasource.classpath; import com.metaui.core.datasource.ResourceItem; import com.metaui.core.util.UFile; import com.metaui.core.util.UIO; import java.io.File; import java.io.InputStream; import java.net.URI; /** * 类路径资源 * * @author wei_jc * @since 1.0.0 */ public class ClassPathResourceItem extends ResourceItem { private String type; private String baseDir; private URI uri; public ClassPathResourceItem(String type, String baseDir) { this.type = type; this.baseDir = baseDir; } @Override public String getContent() throws Exception { if ("jar".equals(type) || "classpath".equals(type)) { InputStream is = UIO.getInputStream("/" + getId(), UIO.FROM.CP); return UFile.readString(is, "UTF-8"); } else if ("file".equals(type)) { File file = new File(baseDir, getId()); return UFile.readString(file); } return null; } @Override public InputStream getInputStream() throws Exception { return UIO.getInputStream("/" + getId(), UIO.FROM.CP); } @Override public URI getURI() throws Exception { return uri; } public void setURI(URI uri) { this.uri = uri; } }
{ "content_hash": "3f0fee3e680652aaff81bc7bf464d431", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 76, "avg_line_length": 24.0188679245283, "alnum_prop": 0.6252945797329144, "repo_name": "weijiancai/metaui", "id": "650fc84a5beec62ce4b268d96130bbc000684be6", "size": "1283", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "core/src/main/java/com/metaui/core/datasource/classpath/ClassPathResourceItem.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1349801" }, { "name": "FreeMarker", "bytes": "46494" }, { "name": "HTML", "bytes": "1748286" }, { "name": "Java", "bytes": "2374709" }, { "name": "JavaScript", "bytes": "3735303" }, { "name": "Less", "bytes": "301939" }, { "name": "Objective-C", "bytes": "4410" }, { "name": "Pug", "bytes": "2132" }, { "name": "Python", "bytes": "5734" }, { "name": "Ruby", "bytes": "1183" }, { "name": "SCSS", "bytes": "75079" }, { "name": "Shell", "bytes": "876" }, { "name": "Starlark", "bytes": "1649" } ], "symlink_target": "" }
A next generation JavaScript debugger
{ "content_hash": "15c634857851eeee1da71bf696f4f5df", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 37, "avg_line_length": 38, "alnum_prop": 0.868421052631579, "repo_name": "basarat/jsdebug", "id": "bf7b7de3f5c66797925f68e3463edbc5cae47d9f", "size": "48", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. export class Player { userId: string; gamertag: string; country: string; customTag: string; } export class Group { name: string; customType: string; description: string; } export class LeaderboardScore { gamertag: string; score: number; }
{ "content_hash": "4b5c54451c8c7882d7a963437be60822", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 101, "avg_line_length": 21.45, "alnum_prop": 0.696969696969697, "repo_name": "stuartleeks/nether", "id": "7cf870aa701fb075164aa085f043e4bd9dc9f1d4", "size": "431", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/Nether.Web/wwwroot/Features/AdminWebUI/app/model.ts", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "487765" }, { "name": "CSS", "bytes": "3692" }, { "name": "HTML", "bytes": "15467" }, { "name": "JavaScript", "bytes": "11597" }, { "name": "PowerShell", "bytes": "22807" }, { "name": "Shell", "bytes": "4976" }, { "name": "TypeScript", "bytes": "34050" } ], "symlink_target": "" }
.class public Landroid/os/CommonTimeConfig; .super Ljava/lang/Object; .source "CommonTimeConfig.java" # annotations .annotation system Ldalvik/annotation/MemberClasses; value = { Landroid/os/CommonTimeConfig$OnServerDiedListener;, Landroid/os/CommonTimeConfig$1; } .end annotation # static fields .field public static final ERROR:I = -0x1 .field public static final ERROR_BAD_VALUE:I = -0x4 .field public static final ERROR_DEAD_OBJECT:I = -0x7 .field public static final INVALID_GROUP_ID:J = -0x1L .field private static final METHOD_FORCE_NETWORKLESS_MASTER_MODE:I = 0x11 .field private static final METHOD_GET_AUTO_DISABLE:I = 0xf .field private static final METHOD_GET_CLIENT_SYNC_INTERVAL:I = 0xb .field private static final METHOD_GET_INTERFACE_BINDING:I = 0x7 .field private static final METHOD_GET_MASTER_ANNOUNCE_INTERVAL:I = 0x9 .field private static final METHOD_GET_MASTER_ELECTION_ENDPOINT:I = 0x3 .field private static final METHOD_GET_MASTER_ELECTION_GROUP_ID:I = 0x5 .field private static final METHOD_GET_MASTER_ELECTION_PRIORITY:I = 0x1 .field private static final METHOD_GET_PANIC_THRESHOLD:I = 0xd .field private static final METHOD_SET_AUTO_DISABLE:I = 0x10 .field private static final METHOD_SET_CLIENT_SYNC_INTERVAL:I = 0xc .field private static final METHOD_SET_INTERFACE_BINDING:I = 0x8 .field private static final METHOD_SET_MASTER_ANNOUNCE_INTERVAL:I = 0xa .field private static final METHOD_SET_MASTER_ELECTION_ENDPOINT:I = 0x4 .field private static final METHOD_SET_MASTER_ELECTION_GROUP_ID:I = 0x6 .field private static final METHOD_SET_MASTER_ELECTION_PRIORITY:I = 0x2 .field private static final METHOD_SET_PANIC_THRESHOLD:I = 0xe .field public static final SERVICE_NAME:Ljava/lang/String; = "common_time.config" .field public static final SUCCESS:I # instance fields .field private mDeathHandler:Landroid/os/IBinder$DeathRecipient; .field private mInterfaceDesc:Ljava/lang/String; .field private final mListenerLock:Ljava/lang/Object; .field private mRemote:Landroid/os/IBinder; .field private mServerDiedListener:Landroid/os/CommonTimeConfig$OnServerDiedListener; .field private mUtils:Landroid/os/CommonTimeUtils; # direct methods .method static synthetic -get0(Landroid/os/CommonTimeConfig;)Ljava/lang/Object; .locals 1 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mListenerLock:Ljava/lang/Object; return-object v0 .end method .method static synthetic -get1(Landroid/os/CommonTimeConfig;)Landroid/os/CommonTimeConfig$OnServerDiedListener; .locals 1 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mServerDiedListener:Landroid/os/CommonTimeConfig$OnServerDiedListener; return-object v0 .end method .method public constructor <init>()V .locals 3 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue const/4 v1, 0x0 .line 63 invoke-direct {p0}, Ljava/lang/Object;-><init>()V .line 414 new-instance v0, Ljava/lang/Object; invoke-direct {v0}, Ljava/lang/Object;-><init>()V iput-object v0, p0, Landroid/os/CommonTimeConfig;->mListenerLock:Ljava/lang/Object; .line 415 iput-object v1, p0, Landroid/os/CommonTimeConfig;->mServerDiedListener:Landroid/os/CommonTimeConfig$OnServerDiedListener; .line 417 iput-object v1, p0, Landroid/os/CommonTimeConfig;->mRemote:Landroid/os/IBinder; .line 418 const-string/jumbo v0, "" iput-object v0, p0, Landroid/os/CommonTimeConfig;->mInterfaceDesc:Ljava/lang/String; .line 421 new-instance v0, Landroid/os/CommonTimeConfig$1; invoke-direct {v0, p0}, Landroid/os/CommonTimeConfig$1;-><init>(Landroid/os/CommonTimeConfig;)V iput-object v0, p0, Landroid/os/CommonTimeConfig;->mDeathHandler:Landroid/os/IBinder$DeathRecipient; .line 65 const-string/jumbo v0, "common_time.config" invoke-static {v0}, Landroid/os/ServiceManager;->getService(Ljava/lang/String;)Landroid/os/IBinder; move-result-object v0 iput-object v0, p0, Landroid/os/CommonTimeConfig;->mRemote:Landroid/os/IBinder; .line 66 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mRemote:Landroid/os/IBinder; if-nez v0, :cond_0 .line 67 new-instance v0, Landroid/os/RemoteException; invoke-direct {v0}, Landroid/os/RemoteException;-><init>()V throw v0 .line 69 :cond_0 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mRemote:Landroid/os/IBinder; invoke-interface {v0}, Landroid/os/IBinder;->getInterfaceDescriptor()Ljava/lang/String; move-result-object v0 iput-object v0, p0, Landroid/os/CommonTimeConfig;->mInterfaceDesc:Ljava/lang/String; .line 70 new-instance v0, Landroid/os/CommonTimeUtils; iget-object v1, p0, Landroid/os/CommonTimeConfig;->mRemote:Landroid/os/IBinder; iget-object v2, p0, Landroid/os/CommonTimeConfig;->mInterfaceDesc:Ljava/lang/String; invoke-direct {v0, v1, v2}, Landroid/os/CommonTimeUtils;-><init>(Landroid/os/IBinder;Ljava/lang/String;)V iput-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; .line 71 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mRemote:Landroid/os/IBinder; iget-object v1, p0, Landroid/os/CommonTimeConfig;->mDeathHandler:Landroid/os/IBinder$DeathRecipient; const/4 v2, 0x0 invoke-interface {v0, v1, v2}, Landroid/os/IBinder;->linkToDeath(Landroid/os/IBinder$DeathRecipient;I)V .line 64 return-void .end method .method private checkDeadServer()Z .locals 2 .prologue const/4 v0, 0x1 .line 406 iget-object v1, p0, Landroid/os/CommonTimeConfig;->mRemote:Landroid/os/IBinder; if-eqz v1, :cond_0 iget-object v1, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; if-nez v1, :cond_1 :cond_0 :goto_0 return v0 :cond_1 const/4 v0, 0x0 goto :goto_0 .end method .method public static create()Landroid/os/CommonTimeConfig; .locals 2 .prologue .line 81 :try_start_0 new-instance v1, Landroid/os/CommonTimeConfig; invoke-direct {v1}, Landroid/os/CommonTimeConfig;-><init>()V :try_end_0 .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0 .line 87 :goto_0 return-object v1 .line 83 :catch_0 move-exception v0 .line 84 .local v0, "e":Landroid/os/RemoteException; const/4 v1, 0x0 .local v1, "retVal":Landroid/os/CommonTimeConfig; goto :goto_0 .end method .method private throwOnDeadServer()V .locals 1 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue .line 410 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->checkDeadServer()Z move-result v0 if-eqz v0, :cond_0 .line 411 new-instance v0, Landroid/os/RemoteException; invoke-direct {v0}, Landroid/os/RemoteException;-><init>()V throw v0 .line 409 :cond_0 return-void .end method # virtual methods .method protected finalize()V .locals 0 .annotation system Ldalvik/annotation/Throws; value = { Ljava/lang/Throwable; } .end annotation .prologue .line 403 invoke-virtual {p0}, Landroid/os/CommonTimeConfig;->release()V return-void .end method .method public forceNetworklessMasterMode()I .locals 6 .prologue .line 359 invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel; move-result-object v0 .line 360 .local v0, "data":Landroid/os/Parcel; invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel; move-result-object v2 .line 363 .local v2, "reply":Landroid/os/Parcel; :try_start_0 iget-object v3, p0, Landroid/os/CommonTimeConfig;->mInterfaceDesc:Ljava/lang/String; invoke-virtual {v0, v3}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V .line 364 iget-object v3, p0, Landroid/os/CommonTimeConfig;->mRemote:Landroid/os/IBinder; const/16 v4, 0x11 const/4 v5, 0x0 invoke-interface {v3, v4, v0, v2, v5}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z .line 366 invoke-virtual {v2}, Landroid/os/Parcel;->readInt()I :try_end_0 .catch Landroid/os/RemoteException; {:try_start_0 .. :try_end_0} :catch_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 move-result v3 .line 372 invoke-virtual {v2}, Landroid/os/Parcel;->recycle()V .line 373 invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V .line 366 return v3 .line 368 :catch_0 move-exception v1 .line 369 .local v1, "e":Landroid/os/RemoteException; const/4 v3, -0x7 .line 372 invoke-virtual {v2}, Landroid/os/Parcel;->recycle()V .line 373 invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V .line 369 return v3 .line 371 .end local v1 # "e":Landroid/os/RemoteException; :catchall_0 move-exception v3 .line 372 invoke-virtual {v2}, Landroid/os/Parcel;->recycle()V .line 373 invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V .line 371 throw v3 .end method .method public getAutoDisable()Z .locals 3 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue const/4 v0, 0x1 .line 321 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->throwOnDeadServer()V .line 322 iget-object v1, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/16 v2, 0xf invoke-virtual {v1, v2, v0}, Landroid/os/CommonTimeUtils;->transactGetInt(II)I move-result v1 if-ne v0, v1, :cond_0 :goto_0 return v0 :cond_0 const/4 v0, 0x0 goto :goto_0 .end method .method public getClientSyncInterval()I .locals 3 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue .line 265 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->throwOnDeadServer()V .line 266 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/16 v1, 0xb const/4 v2, -0x1 invoke-virtual {v0, v1, v2}, Landroid/os/CommonTimeUtils;->transactGetInt(II)I move-result v0 return v0 .end method .method public getInterfaceBinding()Ljava/lang/String; .locals 4 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue const/4 v3, 0x0 .line 201 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->throwOnDeadServer()V .line 203 iget-object v1, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/4 v2, 0x7 invoke-virtual {v1, v2, v3}, Landroid/os/CommonTimeUtils;->transactGetString(ILjava/lang/String;)Ljava/lang/String; move-result-object v0 .line 205 .local v0, "ifaceName":Ljava/lang/String; if-eqz v0, :cond_0 invoke-virtual {v0}, Ljava/lang/String;->length()I move-result v1 if-nez v1, :cond_0 .line 206 return-object v3 .line 208 :cond_0 return-object v0 .end method .method public getMasterAnnounceInterval()I .locals 3 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue .line 238 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->throwOnDeadServer()V .line 239 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/16 v1, 0x9 const/4 v2, -0x1 invoke-virtual {v0, v1, v2}, Landroid/os/CommonTimeUtils;->transactGetInt(II)I move-result v0 return v0 .end method .method public getMasterElectionEndpoint()Ljava/net/InetSocketAddress; .locals 2 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue .line 146 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->throwOnDeadServer()V .line 147 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/4 v1, 0x3 invoke-virtual {v0, v1}, Landroid/os/CommonTimeUtils;->transactGetSockaddr(I)Ljava/net/InetSocketAddress; move-result-object v0 return-object v0 .end method .method public getMasterElectionGroupId()J .locals 4 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue .line 174 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->throwOnDeadServer()V .line 175 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/4 v1, 0x5 const-wide/16 v2, -0x1 invoke-virtual {v0, v1, v2, v3}, Landroid/os/CommonTimeUtils;->transactGetLong(IJ)J move-result-wide v0 return-wide v0 .end method .method public getMasterElectionPriority()B .locals 3 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue .line 119 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->throwOnDeadServer()V .line 120 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/4 v1, 0x1 const/4 v2, -0x1 invoke-virtual {v0, v1, v2}, Landroid/os/CommonTimeUtils;->transactGetInt(II)I move-result v0 int-to-byte v0, v0 return v0 .end method .method public getPanicThreshold()I .locals 3 .annotation system Ldalvik/annotation/Throws; value = { Landroid/os/RemoteException; } .end annotation .prologue .line 293 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->throwOnDeadServer()V .line 294 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/16 v1, 0xd const/4 v2, -0x1 invoke-virtual {v0, v1, v2}, Landroid/os/CommonTimeUtils;->transactGetInt(II)I move-result v0 return v0 .end method .method public release()V .locals 5 .prologue const/4 v4, 0x0 .line 100 iget-object v1, p0, Landroid/os/CommonTimeConfig;->mRemote:Landroid/os/IBinder; if-eqz v1, :cond_0 .line 102 :try_start_0 iget-object v1, p0, Landroid/os/CommonTimeConfig;->mRemote:Landroid/os/IBinder; iget-object v2, p0, Landroid/os/CommonTimeConfig;->mDeathHandler:Landroid/os/IBinder$DeathRecipient; const/4 v3, 0x0 invoke-interface {v1, v2, v3}, Landroid/os/IBinder;->unlinkToDeath(Landroid/os/IBinder$DeathRecipient;I)Z :try_end_0 .catch Ljava/util/NoSuchElementException; {:try_start_0 .. :try_end_0} :catch_0 .line 105 :goto_0 iput-object v4, p0, Landroid/os/CommonTimeConfig;->mRemote:Landroid/os/IBinder; .line 107 :cond_0 iput-object v4, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; .line 99 return-void .line 104 :catch_0 move-exception v0 .local v0, "e":Ljava/util/NoSuchElementException; goto :goto_0 .end method .method public setAutoDisable(Z)I .locals 3 .param p1, "autoDisable" # Z .prologue .line 337 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->checkDeadServer()Z move-result v0 if-eqz v0, :cond_0 .line 338 const/4 v0, -0x7 return v0 .line 340 :cond_0 iget-object v1, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; if-eqz p1, :cond_1 const/4 v0, 0x1 :goto_0 const/16 v2, 0x10 invoke-virtual {v1, v2, v0}, Landroid/os/CommonTimeUtils;->transactSetInt(II)I move-result v0 return v0 :cond_1 const/4 v0, 0x0 goto :goto_0 .end method .method public setClientSyncInterval(I)I .locals 2 .param p1, "interval" # I .prologue .line 278 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->checkDeadServer()Z move-result v0 if-eqz v0, :cond_0 .line 279 const/4 v0, -0x7 return v0 .line 280 :cond_0 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/16 v1, 0xc invoke-virtual {v0, v1, p1}, Landroid/os/CommonTimeUtils;->transactSetInt(II)I move-result v0 return v0 .end method .method public setMasterAnnounceInterval(I)I .locals 2 .param p1, "interval" # I .prologue .line 251 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->checkDeadServer()Z move-result v0 if-eqz v0, :cond_0 .line 252 const/4 v0, -0x7 return v0 .line 253 :cond_0 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/16 v1, 0xa invoke-virtual {v0, v1, p1}, Landroid/os/CommonTimeUtils;->transactSetInt(II)I move-result v0 return v0 .end method .method public setMasterElectionEndpoint(Ljava/net/InetSocketAddress;)I .locals 2 .param p1, "ep" # Ljava/net/InetSocketAddress; .prologue .line 161 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->checkDeadServer()Z move-result v0 if-eqz v0, :cond_0 .line 162 const/4 v0, -0x7 return v0 .line 163 :cond_0 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/4 v1, 0x4 invoke-virtual {v0, v1, p1}, Landroid/os/CommonTimeUtils;->transactSetSockaddr(ILjava/net/InetSocketAddress;)I move-result v0 return v0 .end method .method public setMasterElectionGroupId(J)I .locals 3 .param p1, "id" # J .prologue .line 186 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->checkDeadServer()Z move-result v0 if-eqz v0, :cond_0 .line 187 const/4 v0, -0x7 return v0 .line 188 :cond_0 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/4 v1, 0x6 invoke-virtual {v0, v1, p1, p2}, Landroid/os/CommonTimeUtils;->transactSetLong(IJ)I move-result v0 return v0 .end method .method public setMasterElectionPriority(B)I .locals 2 .param p1, "priority" # B .prologue .line 132 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->checkDeadServer()Z move-result v0 if-eqz v0, :cond_0 .line 133 const/4 v0, -0x7 return v0 .line 134 :cond_0 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/4 v1, 0x2 invoke-virtual {v0, v1, p1}, Landroid/os/CommonTimeUtils;->transactSetInt(II)I move-result v0 return v0 .end method .method public setNetworkBinding(Ljava/lang/String;)I .locals 2 .param p1, "ifaceName" # Ljava/lang/String; .prologue .line 222 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->checkDeadServer()Z move-result v0 if-eqz v0, :cond_0 .line 223 const/4 v0, -0x7 return v0 .line 225 :cond_0 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; .line 226 if-nez p1, :cond_1 const-string/jumbo p1, "" .line 225 .end local p1 # "ifaceName":Ljava/lang/String; :cond_1 const/16 v1, 0x8 invoke-virtual {v0, v1, p1}, Landroid/os/CommonTimeUtils;->transactSetString(ILjava/lang/String;)I move-result v0 return v0 .end method .method public setPanicThreshold(I)I .locals 2 .param p1, "threshold" # I .prologue .line 308 invoke-direct {p0}, Landroid/os/CommonTimeConfig;->checkDeadServer()Z move-result v0 if-eqz v0, :cond_0 .line 309 const/4 v0, -0x7 return v0 .line 310 :cond_0 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mUtils:Landroid/os/CommonTimeUtils; const/16 v1, 0xe invoke-virtual {v0, v1, p1}, Landroid/os/CommonTimeUtils;->transactSetInt(II)I move-result v0 return v0 .end method .method public setServerDiedListener(Landroid/os/CommonTimeConfig$OnServerDiedListener;)V .locals 2 .param p1, "listener" # Landroid/os/CommonTimeConfig$OnServerDiedListener; .prologue .line 398 iget-object v0, p0, Landroid/os/CommonTimeConfig;->mListenerLock:Ljava/lang/Object; monitor-enter v0 .line 399 :try_start_0 iput-object p1, p0, Landroid/os/CommonTimeConfig;->mServerDiedListener:Landroid/os/CommonTimeConfig$OnServerDiedListener; :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 monitor-exit v0 .line 397 return-void .line 398 :catchall_0 move-exception v1 monitor-exit v0 throw v1 .end method
{ "content_hash": "6e898498404a31d7f05b2a38a22e627f", "timestamp": "", "source": "github", "line_count": 925, "max_line_length": 125, "avg_line_length": 22.747027027027027, "alnum_prop": 0.6821919110308445, "repo_name": "libnijunior/patchrom_bullhead", "id": "cf65ab36c2cc5934f18d8e3b460694de1d1128cc", "size": "21041", "binary": false, "copies": "2", "ref": "refs/heads/mtc20k", "path": "framework.jar.out/smali/android/os/CommonTimeConfig.smali", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "3334" }, { "name": "Groff", "bytes": "8687" }, { "name": "Makefile", "bytes": "2098" }, { "name": "Shell", "bytes": "26769" }, { "name": "Smali", "bytes": "172301453" } ], "symlink_target": "" }
package org.apache.ignite.internal.portable.api; import org.apache.ignite.IgniteException; import org.jetbrains.annotations.Nullable; /** * Exception indicating portable object serialization error. */ public class PortableException extends IgniteException { /** */ private static final long serialVersionUID = 0L; /** * Creates portable exception with error message. * * @param msg Error message. */ public PortableException(String msg) { super(msg); } /** * Creates portable exception with {@link Throwable} as a cause. * * @param cause Cause. */ public PortableException(Throwable cause) { super(cause); } /** * Creates portable exception with error message and {@link Throwable} as a cause. * * @param msg Error message. * @param cause Cause. */ public PortableException(String msg, @Nullable Throwable cause) { super(msg, cause); } }
{ "content_hash": "c37453c9599cc8403b383af8c60ed9ca", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 86, "avg_line_length": 23.30952380952381, "alnum_prop": 0.6455566905005107, "repo_name": "agoncharuk/ignite", "id": "f2301820203d0f70498e38edea48ba8426911c50", "size": "1781", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "modules/core/src/main/java/org/apache/ignite/internal/portable/api/PortableException.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "31300" }, { "name": "C", "bytes": "3323" }, { "name": "C#", "bytes": "2610422" }, { "name": "C++", "bytes": "864786" }, { "name": "CSS", "bytes": "17517" }, { "name": "Groovy", "bytes": "15092" }, { "name": "HTML", "bytes": "4649" }, { "name": "Java", "bytes": "20788412" }, { "name": "JavaScript", "bytes": "1085" }, { "name": "PHP", "bytes": "11079" }, { "name": "Scala", "bytes": "653733" }, { "name": "Shell", "bytes": "398313" } ], "symlink_target": "" }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ var GoogleMaps = { set_first_marker: true, set_marker_onclick: true, inputObject: null, map: null, geocoder: null, mainMarker: null, initializeGeocoder:function(){ GoogleMaps.geocoder = new google.maps.Geocoder(); }, initialize: function(element) { var mapOptions = { zoom: 5, //17 mapTypeId: google.maps.MapTypeId.ROADMAP }; GoogleMaps.initializeGeocoder(); GoogleMaps.map = new google.maps.Map(document.getElementById(element), mapOptions); var position = new google.maps.LatLng(4.302591077119676, -74.11376953125); GoogleMaps.map.setCenter(position); if (GoogleMaps.set_first_marker) { GoogleMaps.mainMarker = new google.maps.Marker({ map: GoogleMaps.map, draggable: false, position: position }); google.maps.event.addListener(GoogleMaps.map, 'click', function(event) { if (GoogleMaps.set_marker_onclick) { GoogleMaps.mainMarker.setPosition(event.latLng); GoogleMaps.map.setCenter(event.latLng); } }); } }, codeAddress: function(adress) { var address = adress; GoogleMaps.geocoder.geocode({'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { GoogleMaps.setMapLocation(results[0].geometry.location); /* * this.map.setCenter(); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); */ } else { alert('Geocode was not successful for the following reason: ' + status); } }); }, codeLatLng: function(pos) { var latlng = GoogleMaps.parsePosition(pos); GoogleMaps.geocoder.geocode({'latLng': latlng}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[1]) { GoogleMaps.map.setZoom(11); infowindow = new google.maps.InfoWindow({ position: latlng, map: GoogleMaps.map, content: results[0].formatted_address }); //infowindow.setContent(results[1].formatted_address); //infowindow.open(map, marker); } } else { alert("Geocoder failed due to: " + status); } }); }, fundCurrentGeolocationToTarget: function(target) { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); target(pos); }, function() { handleNoGeolocation(true); }); } else { // Browser doesn't support Geolocation handleNoGeolocation(false); } }, findCurrentAddresToTarget: function(target) { var latlng = GoogleMaps.getCurrentPosition(); GoogleMaps.geocoder.geocode({'latLng': latlng}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[1]) { target(results); } } else { alert("Geocoder failed due to: " + status); } }); }, geolocateCurrentAddressToTarget: function(target) { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); GoogleMaps.geocoder.geocode({'latLng': pos}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[1]) { target(results); } } else { alert("Geocoder failed due to: " + status); } }); }, function() { handleNoGeolocation(true); }); } else { // Browser doesn't support Geolocation handleNoGeolocation(false); } }, setNewMarker: function(options) { return new google.maps.Marker(options); }, setNewInfoBox: function(options) { return new google.maps.InfoWindow(options); }, saveInputLocation: function() { if (GoogleMaps.inputObject == null) { return; } var lat = this.getCurrentPosition(); GoogleMaps.inputObject.value = lat.lat() + ', ' + lat.lng(); }, loadInputLocation: function() { if (GoogleMaps.inputObject == null) { return; } var position = GoogleMaps.inputObject.value; if (position == null || position == "") { return; } //console.log(p2); GoogleMaps.setLocation(position); }, setInputElement: function(input) { GoogleMaps.inputObject = document.getElementById(input); }, parsePosition: function(position) { var pos = null; var p1 = parseFloat(position.split(",")[0]); var p2 = parseFloat(position.split(",")[1]); pos = new google.maps.LatLng(p1, p2); return pos; }, setLocation: function(position) { var pos = GoogleMaps.parsePosition(position); GoogleMaps.setMapLocation(pos); GoogleMaps.map.setZoom(15); }, setZoom: function(zoom) { GoogleMaps.map.setZoom(zoom); }, setCenter: function(pos) { GoogleMaps.map.setCenter(pos); }, setMapLocation: function(pos) { GoogleMaps.map.setCenter(pos); GoogleMaps.mainMarker.setPosition(pos); }, setMarkInGeolocation: function() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); var infowindow = new google.maps.InfoWindow({ map: GoogleMaps.map, position: pos, content: '<h3>Esta es su ubicación fisica</h3>' }); GoogleMaps.setLocation(pos); }, function() { handleNoGeolocation(true); }); } else { // Browser doesn't support Geolocation handleNoGeolocation(false); } }, getCurrentPosition: function() { return GoogleMaps.mainMarker.getPosition(); }, getCurrentPositionString: function() { return (GoogleMaps.getCurrentPosition() + "").match(/\((.*)\)/)[1]; }, handleNoGeolocation: function(errorFlag) { if (errorFlag) { var content = 'Error: The Geolocation service failed.'; } else { var content = 'Error: Your browser doesn\'t support geolocation.'; } var options = { map: GoogleMaps.map, position: new google.maps.LatLng(60, 105), content: content }; var infowindow = new google.maps.InfoWindow(options); GoogleMaps.map.setCenter(options.position); } };
{ "content_hash": "7496b5314c12d41d89a7244615335306", "timestamp": "", "source": "github", "line_count": 206, "max_line_length": 91, "avg_line_length": 37.45145631067961, "alnum_prop": 0.5350615683732988, "repo_name": "SFSUser/IPS", "id": "9b739907e51bad19d69bfb9fa5d9f57036367ed3", "size": "7716", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "web/bundles/acmesfs/js/google_maps.js", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "85072" }, { "name": "ApacheConf", "bytes": "2647" }, { "name": "CSS", "bytes": "599214" }, { "name": "HTML", "bytes": "1074646" }, { "name": "JavaScript", "bytes": "1867378" }, { "name": "PHP", "bytes": "1324574" }, { "name": "Shell", "bytes": "559" } ], "symlink_target": "" }
:mod:`zlib` --- Compression compatible with :program:`gzip` =========================================================== .. module:: zlib :synopsis: Low-level interface to compression and decompression routines compatible with gzip. -------------- For applications that require data compression, the functions in this module allow compression and decompression, using the zlib library. The zlib library has its own home page at http://www.zlib.net. There are known incompatibilities between the Python module and versions of the zlib library earlier than 1.1.3; 1.1.3 has a security vulnerability, so we recommend using 1.1.4 or later. zlib's functions have many options and often need to be used in a particular order. This documentation doesn't attempt to cover all of the permutations; consult the zlib manual at http://www.zlib.net/manual.html for authoritative information. For reading and writing ``.gz`` files see the :mod:`gzip` module. The available exception and functions in this module are: .. exception:: error Exception raised on compression and decompression errors. .. function:: adler32(data[, value]) Computes an Adler-32 checksum of *data*. (An Adler-32 checksum is almost as reliable as a CRC32 but can be computed much more quickly.) The result is an unsigned 32-bit integer. If *value* is present, it is used as the starting value of the checksum; otherwise, a default value of 1 is used. Passing in *value* allows computing a running checksum over the concatenation of several inputs. The algorithm is not cryptographically strong, and should not be used for authentication or digital signatures. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. .. versionchanged:: 3.0 Always returns an unsigned value. To generate the same numeric value across all Python versions and platforms, use ``adler32(data) & 0xffffffff``. .. function:: compress(data, level=-1) Compresses the bytes in *data*, returning a bytes object containing compressed data. *level* is an integer from ``0`` to ``9`` or ``-1`` controlling the level of compression; ``1`` (Z_BEST_SPEED) is fastest and produces the least compression, ``9`` (Z_BEST_COMPRESSION) is slowest and produces the most. ``0`` (Z_NO_COMPRESSION) is no compression. The default value is ``-1`` (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default compromise between speed and compression (currently equivalent to level 6). Raises the :exc:`error` exception if any error occurs. .. versionchanged:: 3.6 *level* can now be used as a keyword parameter. .. function:: compressobj(level=-1, method=DEFLATED, wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=Z_DEFAULT_STRATEGY[, zdict]) Returns a compression object, to be used for compressing data streams that won't fit into memory at once. *level* is the compression level -- an integer from ``0`` to ``9`` or ``-1``. A value of ``1`` (Z_BEST_SPEED) is fastest and produces the least compression, while a value of ``9`` (Z_BEST_COMPRESSION) is slowest and produces the most. ``0`` (Z_NO_COMPRESSION) is no compression. The default value is ``-1`` (Z_DEFAULT_COMPRESSION). Z_DEFAULT_COMPRESSION represents a default compromise between speed and compression (currently equivalent to level 6). *method* is the compression algorithm. Currently, the only supported value is :const:`DEFLATED`. The *wbits* argument controls the size of the history buffer (or the "window size") used when compressing data, and whether a header and trailer is included in the output. It can take several ranges of values, defaulting to ``15`` (MAX_WBITS): * +9 to +15: The base-two logarithm of the window size, which therefore ranges between 512 and 32768. Larger values produce better compression at the expense of greater memory usage. The resulting output will include a zlib-specific header and trailer. * −9 to −15: Uses the absolute value of *wbits* as the window size logarithm, while producing a raw output stream with no header or trailing checksum. * +25 to +31 = 16 + (9 to 15): Uses the low 4 bits of the value as the window size logarithm, while including a basic :program:`gzip` header and trailing checksum in the output. The *memLevel* argument controls the amount of memory used for the internal compression state. Valid values range from ``1`` to ``9``. Higher values use more memory, but are faster and produce smaller output. *strategy* is used to tune the compression algorithm. Possible values are :const:`Z_DEFAULT_STRATEGY`, :const:`Z_FILTERED`, :const:`Z_HUFFMAN_ONLY`, :const:`Z_RLE` (zlib 1.2.0.1) and :const:`Z_FIXED` (zlib 1.2.2.2). *zdict* is a predefined compression dictionary. This is a sequence of bytes (such as a :class:`bytes` object) containing subsequences that are expected to occur frequently in the data that is to be compressed. Those subsequences that are expected to be most common should come at the end of the dictionary. .. versionchanged:: 3.3 Added the *zdict* parameter and keyword argument support. .. function:: crc32(data[, value]) .. index:: single: Cyclic Redundancy Check single: checksum; Cyclic Redundancy Check Computes a CRC (Cyclic Redundancy Check) checksum of *data*. The result is an unsigned 32-bit integer. If *value* is present, it is used as the starting value of the checksum; otherwise, a default value of 0 is used. Passing in *value* allows computing a running checksum over the concatenation of several inputs. The algorithm is not cryptographically strong, and should not be used for authentication or digital signatures. Since the algorithm is designed for use as a checksum algorithm, it is not suitable for use as a general hash algorithm. .. versionchanged:: 3.0 Always returns an unsigned value. To generate the same numeric value across all Python versions and platforms, use ``crc32(data) & 0xffffffff``. .. function:: decompress(data, wbits=MAX_WBITS, bufsize=DEF_BUF_SIZE) Decompresses the bytes in *data*, returning a bytes object containing the uncompressed data. The *wbits* parameter depends on the format of *data*, and is discussed further below. If *bufsize* is given, it is used as the initial size of the output buffer. Raises the :exc:`error` exception if any error occurs. .. _decompress-wbits: The *wbits* parameter controls the size of the history buffer (or "window size"), and what header and trailer format is expected. It is similar to the parameter for :func:`compressobj`, but accepts more ranges of values: * +8 to +15: The base-two logarithm of the window size. The input must include a zlib header and trailer. * 0: Automatically determine the window size from the zlib header. Only supported since zlib 1.2.3.5. * −8 to −15: Uses the absolute value of *wbits* as the window size logarithm. The input must be a raw stream with no header or trailer. * +24 to +31 = 16 + (8 to 15): Uses the low 4 bits of the value as the window size logarithm. The input must include a gzip header and trailer. * +40 to +47 = 32 + (8 to 15): Uses the low 4 bits of the value as the window size logarithm, and automatically accepts either the zlib or gzip format. When decompressing a stream, the window size must not be smaller than the size originally used to compress the stream; using a too-small value may result in an :exc:`error` exception. The default *wbits* value corresponds to the largest window size and requires a zlib header and trailer to be included. *bufsize* is the initial size of the buffer used to hold decompressed data. If more space is required, the buffer size will be increased as needed, so you don't have to get this value exactly right; tuning it will only save a few calls to :c:func:`malloc`. .. versionchanged:: 3.6 *wbits* and *bufsize* can be used as keyword arguments. .. function:: decompressobj(wbits=MAX_WBITS[, zdict]) Returns a decompression object, to be used for decompressing data streams that won't fit into memory at once. The *wbits* parameter controls the size of the history buffer (or the "window size"), and what header and trailer format is expected. It has the same meaning as `described for decompress() <#decompress-wbits>`__. The *zdict* parameter specifies a predefined compression dictionary. If provided, this must be the same dictionary as was used by the compressor that produced the data that is to be decompressed. .. note:: If *zdict* is a mutable object (such as a :class:`bytearray`), you must not modify its contents between the call to :func:`decompressobj` and the first call to the decompressor's ``decompress()`` method. .. versionchanged:: 3.3 Added the *zdict* parameter. Compression objects support the following methods: .. method:: Compress.compress(data) Compress *data*, returning a bytes object containing compressed data for at least part of the data in *data*. This data should be concatenated to the output produced by any preceding calls to the :meth:`compress` method. Some input may be kept in internal buffers for later processing. .. method:: Compress.flush([mode]) All pending input is processed, and a bytes object containing the remaining compressed output is returned. *mode* can be selected from the constants :const:`Z_NO_FLUSH`, :const:`Z_PARTIAL_FLUSH`, :const:`Z_SYNC_FLUSH`, :const:`Z_FULL_FLUSH`, :const:`Z_BLOCK` (zlib 1.2.3.4), or :const:`Z_FINISH`, defaulting to :const:`Z_FINISH`. Except :const:`Z_FINISH`, all constants allow compressing further bytestrings of data, while :const:`Z_FINISH` finishes the compressed stream and prevents compressing any more data. After calling :meth:`flush` with *mode* set to :const:`Z_FINISH`, the :meth:`compress` method cannot be called again; the only realistic action is to delete the object. .. method:: Compress.copy() Returns a copy of the compression object. This can be used to efficiently compress a set of data that share a common initial prefix. Decompression objects support the following methods and attributes: .. attribute:: Decompress.unused_data A bytes object which contains any bytes past the end of the compressed data. That is, this remains ``b""`` until the last byte that contains compression data is available. If the whole bytestring turned out to contain compressed data, this is ``b""``, an empty bytes object. .. attribute:: Decompress.unconsumed_tail A bytes object that contains any data that was not consumed by the last :meth:`decompress` call because it exceeded the limit for the uncompressed data buffer. This data has not yet been seen by the zlib machinery, so you must feed it (possibly with further data concatenated to it) back to a subsequent :meth:`decompress` method call in order to get correct output. .. attribute:: Decompress.eof A boolean indicating whether the end of the compressed data stream has been reached. This makes it possible to distinguish between a properly-formed compressed stream, and an incomplete or truncated one. .. versionadded:: 3.3 .. method:: Decompress.decompress(data, max_length=0) Decompress *data*, returning a bytes object containing the uncompressed data corresponding to at least part of the data in *string*. This data should be concatenated to the output produced by any preceding calls to the :meth:`decompress` method. Some of the input data may be preserved in internal buffers for later processing. If the optional parameter *max_length* is non-zero then the return value will be no longer than *max_length*. This may mean that not all of the compressed input can be processed; and unconsumed data will be stored in the attribute :attr:`unconsumed_tail`. This bytestring must be passed to a subsequent call to :meth:`decompress` if decompression is to continue. If *max_length* is zero then the whole input is decompressed, and :attr:`unconsumed_tail` is empty. .. versionchanged:: 3.6 *max_length* can be used as a keyword argument. .. method:: Decompress.flush([length]) All pending input is processed, and a bytes object containing the remaining uncompressed output is returned. After calling :meth:`flush`, the :meth:`decompress` method cannot be called again; the only realistic action is to delete the object. The optional parameter *length* sets the initial size of the output buffer. .. method:: Decompress.copy() Returns a copy of the decompression object. This can be used to save the state of the decompressor midway through the data stream in order to speed up random seeks into the stream at a future point. Information about the version of the zlib library in use is available through the following constants: .. data:: ZLIB_VERSION The version string of the zlib library that was used for building the module. This may be different from the zlib library actually used at runtime, which is available as :const:`ZLIB_RUNTIME_VERSION`. .. data:: ZLIB_RUNTIME_VERSION The version string of the zlib library actually loaded by the interpreter. .. versionadded:: 3.3 .. seealso:: Module :mod:`gzip` Reading and writing :program:`gzip`\ -format files. http://www.zlib.net The zlib library home page. http://www.zlib.net/manual.html The zlib manual explains the semantics and usage of the library's many functions.
{ "content_hash": "afd2049ce3990f65cd2688797902939a", "timestamp": "", "source": "github", "line_count": 330, "max_line_length": 131, "avg_line_length": 42.13333333333333, "alnum_prop": 0.7246835443037974, "repo_name": "FFMG/myoddweb.piger", "id": "8a531c92b8ff154157cec6c34c89d62ecdd2fed4", "size": "13912", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "monitor/api/python/Python-3.7.2/Doc/library/zlib.rst", "mode": "33188", "license": "mit", "language": [ { "name": "Ada", "bytes": "89079" }, { "name": "Assembly", "bytes": "399228" }, { "name": "Batchfile", "bytes": "93889" }, { "name": "C", "bytes": "32256857" }, { "name": "C#", "bytes": "197461" }, { "name": "C++", "bytes": "200544641" }, { "name": "CMake", "bytes": "192771" }, { "name": "CSS", "bytes": "441704" }, { "name": "CWeb", "bytes": "174166" }, { "name": "Common Lisp", "bytes": "24481" }, { "name": "Cuda", "bytes": "52444" }, { "name": "DIGITAL Command Language", "bytes": "33549" }, { "name": "DTrace", "bytes": "2157" }, { "name": "Fortran", "bytes": "1856" }, { "name": "HTML", "bytes": "181677643" }, { "name": "IDL", "bytes": "14" }, { "name": "Inno Setup", "bytes": "9647" }, { "name": "JavaScript", "bytes": "705756" }, { "name": "Lex", "bytes": "1231" }, { "name": "Lua", "bytes": "3332" }, { "name": "M4", "bytes": "259214" }, { "name": "Makefile", "bytes": "1262318" }, { "name": "Max", "bytes": "36857" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "Objective-C", "bytes": "2167778" }, { "name": "Objective-C++", "bytes": "630" }, { "name": "PHP", "bytes": "59030" }, { "name": "PLSQL", "bytes": "22886" }, { "name": "Pascal", "bytes": "75208" }, { "name": "Perl", "bytes": "42080" }, { "name": "PostScript", "bytes": "13803" }, { "name": "PowerShell", "bytes": "11781" }, { "name": "Python", "bytes": "30377308" }, { "name": "QML", "bytes": "593" }, { "name": "QMake", "bytes": "16692" }, { "name": "Rebol", "bytes": "354" }, { "name": "Rich Text Format", "bytes": "6743" }, { "name": "Roff", "bytes": "55661" }, { "name": "Ruby", "bytes": "5532" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "783974" }, { "name": "TSQL", "bytes": "1201" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "32117" }, { "name": "Visual Basic", "bytes": "70" }, { "name": "XSLT", "bytes": "552736" }, { "name": "Yacc", "bytes": "19623" } ], "symlink_target": "" }
package models // GENERATED BY XO. DO NOT EDIT. import ( "database/sql" "errors" "time" ) // Environment represents a row from 'public.environments'. type Environment struct { ID int `json:"id"` // id ApplicationID sql.NullInt64 `json:"application_id"` // application_id Name string `json:"name"` // name Slug string `json:"slug"` // slug CreatedAt time.Time `json:"created_at"` // created_at // xo fields _exists, _deleted bool } // Exists determines if the Environment exists in the database. func (e *Environment) Exists() bool { return e._exists } // Deleted provides information if the Environment has been deleted from the database. func (e *Environment) Deleted() bool { return e._deleted } // Insert inserts the Environment to the database. func (e *Environment) Insert(db XODB) error { var err error // if already exist, bail if e._exists { return errors.New("insert failed: already exists") } // sql insert query, primary key provided by sequence const sqlstr = `INSERT INTO public.environments (` + `application_id, name, slug, created_at` + `) VALUES (` + `$1, $2, $3, $4` + `) RETURNING id` // run query XOLog(sqlstr, e.ApplicationID, e.Name, e.Slug, e.CreatedAt) err = db.QueryRow(sqlstr, e.ApplicationID, e.Name, e.Slug, e.CreatedAt).Scan(&e.ID) if err != nil { return err } // set existence e._exists = true return nil } // Update updates the Environment in the database. func (e *Environment) Update(db XODB) error { var err error // if doesn't exist, bail if !e._exists { return errors.New("update failed: does not exist") } // if deleted, bail if e._deleted { return errors.New("update failed: marked for deletion") } // sql query const sqlstr = `UPDATE public.environments SET (` + `application_id, name, slug, created_at` + `) = ( ` + `$1, $2, $3, $4` + `) WHERE id = $5` // run query XOLog(sqlstr, e.ApplicationID, e.Name, e.Slug, e.CreatedAt, e.ID) _, err = db.Exec(sqlstr, e.ApplicationID, e.Name, e.Slug, e.CreatedAt, e.ID) return err } // Save saves the Environment to the database. func (e *Environment) Save(db XODB) error { if e.Exists() { return e.Update(db) } return e.Insert(db) } // Upsert performs an upsert for Environment. // // NOTE: PostgreSQL 9.5+ only func (e *Environment) Upsert(db XODB) error { var err error // if already exist, bail if e._exists { return errors.New("insert failed: already exists") } // sql query const sqlstr = `INSERT INTO public.environments (` + `id, application_id, name, slug, created_at` + `) VALUES (` + `$1, $2, $3, $4, $5` + `) ON CONFLICT (id) DO UPDATE SET (` + `id, application_id, name, slug, created_at` + `) = (` + `EXCLUDED.id, EXCLUDED.application_id, EXCLUDED.name, EXCLUDED.slug, EXCLUDED.created_at` + `)` // run query XOLog(sqlstr, e.ID, e.ApplicationID, e.Name, e.Slug, e.CreatedAt) _, err = db.Exec(sqlstr, e.ID, e.ApplicationID, e.Name, e.Slug, e.CreatedAt) if err != nil { return err } // set existence e._exists = true return nil } // Delete deletes the Environment from the database. func (e *Environment) Delete(db XODB) error { var err error // if doesn't exist, bail if !e._exists { return nil } // if deleted, bail if e._deleted { return nil } // sql query const sqlstr = `DELETE FROM public.environments WHERE id = $1` // run query XOLog(sqlstr, e.ID) _, err = db.Exec(sqlstr, e.ID) if err != nil { return err } // set deleted e._deleted = true return nil } // Application returns the Application associated with the Environment's ApplicationID (application_id). // // Generated from foreign key 'environments_application_id_fkey'. func (e *Environment) Application(db XODB) (*Application, error) { return ApplicationByID(db, int(e.ApplicationID.Int64)) } // EnvironmentByApplicationIDName retrieves a row from 'public.environments' as a Environment. // // Generated from index 'environments_application_id_name_key'. func EnvironmentByApplicationIDName(db XODB, applicationID sql.NullInt64, name string) (*Environment, error) { var err error // sql query const sqlstr = `SELECT ` + `id, application_id, name, slug, created_at ` + `FROM public.environments ` + `WHERE application_id = $1 AND name = $2` // run query XOLog(sqlstr, applicationID, name) e := Environment{ _exists: true, } err = db.QueryRow(sqlstr, applicationID, name).Scan(&e.ID, &e.ApplicationID, &e.Name, &e.Slug, &e.CreatedAt) if err != nil { return nil, err } return &e, nil } // EnvironmentByApplicationIDSlug retrieves a row from 'public.environments' as a Environment. // // Generated from index 'environments_application_id_slug_key'. func EnvironmentByApplicationIDSlug(db XODB, applicationID sql.NullInt64, slug string) (*Environment, error) { var err error // sql query const sqlstr = `SELECT ` + `id, application_id, name, slug, created_at ` + `FROM public.environments ` + `WHERE application_id = $1 AND slug = $2` // run query XOLog(sqlstr, applicationID, slug) e := Environment{ _exists: true, } err = db.QueryRow(sqlstr, applicationID, slug).Scan(&e.ID, &e.ApplicationID, &e.Name, &e.Slug, &e.CreatedAt) if err != nil { return nil, err } return &e, nil } // EnvironmentByID retrieves a row from 'public.environments' as a Environment. // // Generated from index 'environments_pkey'. func EnvironmentByID(db XODB, id int) (*Environment, error) { var err error // sql query const sqlstr = `SELECT ` + `id, application_id, name, slug, created_at ` + `FROM public.environments ` + `WHERE id = $1` // run query XOLog(sqlstr, id) e := Environment{ _exists: true, } err = db.QueryRow(sqlstr, id).Scan(&e.ID, &e.ApplicationID, &e.Name, &e.Slug, &e.CreatedAt) if err != nil { return nil, err } return &e, nil }
{ "content_hash": "d8d38764fb45dfad8c7327fbb9c96dd1", "timestamp": "", "source": "github", "line_count": 246, "max_line_length": 110, "avg_line_length": 24.03252032520325, "alnum_prop": 0.6649188092016238, "repo_name": "adhocteam/soapbox", "id": "805fdf57297b036ee5b2dbd9f24afb068ea16bce", "size": "5970", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/environment.xo.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5288" }, { "name": "CoffeeScript", "bytes": "211" }, { "name": "Dockerfile", "bytes": "1456" }, { "name": "Go", "bytes": "131075" }, { "name": "HCL", "bytes": "20874" }, { "name": "HTML", "bytes": "40145" }, { "name": "JavaScript", "bytes": "12586" }, { "name": "Makefile", "bytes": "1098" }, { "name": "Ruby", "bytes": "56433" }, { "name": "Shell", "bytes": "8064" }, { "name": "Smarty", "bytes": "13090" } ], "symlink_target": "" }
std::shared_ptr<MayaObject> MayaScene::getObject(MObject obj) { std::shared_ptr<MayaObject> mo = nullptr; size_t numobjects = this->objectList.size(); for (size_t objId = 0; objId < numobjects; objId++) { if (this->objectList[objId]->mobject == obj) return this->objectList[objId]; } return mo; } std::shared_ptr<MayaObject> MayaScene::getObject(MDagPath dp) { std::shared_ptr<MayaObject> mo = nullptr; size_t numobjects = this->objectList.size(); for (size_t objId = 0; objId < numobjects; objId++) { if (this->objectList[objId]->dagPath == dp) return this->objectList[objId]; } return mo; } void MayaScene::clearObjList(std::vector<std::shared_ptr<MayaObject>> & objList) { objList.clear(); } void MayaScene::clearObjList(std::vector<std::shared_ptr<MayaObject>> & objList, std::shared_ptr<MayaObject> notThisOne) { size_t numElements = objList.size(); std::shared_ptr<MayaObject> tmpCopy; for (size_t i = 0; i < numElements; i++) { if (objList[i] == notThisOne) tmpCopy = objList[i]; } objList.clear(); objList.push_back(notThisOne); notThisOne->index = 0; } // the camera from the UI is set via render command void MayaScene::setCurrentCamera(MDagPath camDagPath) { this->uiCamera = camDagPath; } std::vector<std::shared_ptr<MayaObject>> parentList; void MayaScene::checkParent(std::shared_ptr<MayaObject> obj) { std::vector<std::shared_ptr<MayaObject>>::iterator iter; MFnDagNode node(obj->mobject); if (node.parentCount() == 0) { obj->parent = nullptr; return; } MObject parent = node.parent(0); for (iter = parentList.begin(); iter != parentList.end(); iter++) { if (parent == (*iter)->mobject) { obj->parent = *iter; break; } } } MDagPath MayaScene::getWorld() { MItDag dagIterator(MItDag::kDepthFirst, MFn::kInvalid); MDagPath dagPath; for (dagIterator.reset(); (!dagIterator.isDone()); dagIterator.next()) { dagIterator.getPath(dagPath); if (dagPath.apiType() == MFn::kWorld) break; } return dagPath; } bool MayaScene::isGeo(MObject obj) { if (obj.hasFn(MFn::kMesh)) return true; if (obj.hasFn(MFn::kNurbsSurface)) return true; if (obj.hasFn(MFn::kParticle)) return true; if (obj.hasFn(MFn::kSubSurface)) return true; if (obj.hasFn(MFn::kNurbsCurve)) return true; if (obj.hasFn(MFn::kHairSystem)) return true; MFnDependencyNode depFn(obj); uint nodeId = depFn.typeId().id(); for (uint lId = 0; lId < this->objectIdentifier.size(); lId++) { if (nodeId == this->objectIdentifier[lId]) { Logging::debug(MString("Found external objtype: ") + depFn.name()); return true; } } return false; } bool MayaScene::isLight(MObject obj) { if (obj.hasFn(MFn::kLight)) return true; MFnDependencyNode depFn(obj); uint nodeId = depFn.typeId().id(); for (uint lId = 0; lId < this->lightIdentifier.size(); lId++) { if (nodeId == this->lightIdentifier[lId]) { Logging::debug(MString("Found external lighttype: ") + depFn.name()); return true; } } return false; } void MayaScene::classifyMayaObject(std::shared_ptr<MayaObject> obj) { if (isCamera(obj->mobject)) { this->camList.push_back(obj); return; } if (this->isLight(obj->mobject)) { this->lightList.push_back(obj); return; } if (obj->mobject.hasFn(MFn::kInstancer)) { instancerDagPathList.push_back(obj->dagPath); return; } this->objectList.push_back(obj); } MString MayaScene::getExportPath(MString ext, MString rendererName) { std::string currentFile = MFileIO::currentFile().asChar(); std::vector<std::string> parts; pystring::split(currentFile, parts, "/"); currentFile = pystring::replace(parts.back(), ".ma", ""); currentFile = pystring::replace(currentFile, ".mb", ""); MString scenePath = MayaTo::getWorldPtr()->worldRenderGlobalsPtr->basePath + "/" + rendererName + "/" + currentFile.c_str() + "." + ext; return scenePath; } MString MayaScene::getFileName() { std::string currentFile = MFileIO::currentFile().asChar(); std::vector<std::string> parts; pystring::split(currentFile, parts, "/"); currentFile = pystring::replace(parts.back(), ".ma", ""); currentFile = pystring::replace(currentFile, ".mb", ""); return MString(currentFile.c_str()); } bool MayaScene::canDoIPR() { return this->cando_ipr; } void MayaScene::setRenderType(RenderType rtype) { this->renderType = rtype; }
{ "content_hash": "d15dd97345871003c24c54706bfe4a5d", "timestamp": "", "source": "github", "line_count": 185, "max_line_length": 137, "avg_line_length": 23.38918918918919, "alnum_prop": 0.6829211925121331, "repo_name": "haggi/OpenMaya", "id": "056c57e2fedfdb1edc485724333e1c1f849de175", "size": "4665", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/common/cpp/mayaSceneUtils.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "AMPL", "bytes": "5333" }, { "name": "Batchfile", "bytes": "587" }, { "name": "C", "bytes": "246300" }, { "name": "C++", "bytes": "4178594" }, { "name": "Mathematica", "bytes": "12660820" }, { "name": "Objective-C", "bytes": "316" }, { "name": "Python", "bytes": "1583249" } ], "symlink_target": "" }
<img src="https://github.com/Rickedb/OpenProtocolInterpreter/blob/master/media/logo.png?raw=true" width="550" alt="Open Protocol Interpreter" /> <h1> <a href="https://www.buymeacoffee.com/openprotocolitp"> <img height="40" alt="Buy me a coffee" src="https://img.buymeacoffee.com/button-api/?text=Buy me a coffee&emoji=&slug=openprotocolitp&button_colour=FFDD00&font_colour=000000&font_family=Cookie&outline_colour=000000&coffee_colour=ffffff" /> </a> <a href="https://opencollective.com/open-protocol-interpreter" alt="Financial Contributors on Open Collective"> <img src="https://opencollective.com/open-protocol-interpreter/all/badge.svg?label=financial+contributors" /> </a> <a href="https://github.com/Rickedb/OpenProtocolInterpreter/"> <img src="https://github.com/rickedb/openprotocolinterpreter/workflows/master/badge.svg" /> </a> <a href="https://raw.githubusercontent.com/Rickedb/OpenProtocolIntepreter/master/LICENSE"> <img src= "https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT"> </a> </h1> > OpenProtocol communication utility > Missing OpenProtocolInterpreter v1.0.0 ? [>It's here!<](https://github.com/Rickedb/OpenProtocolInterpreter/releases/tag/1.0.0) > Missing OpenProtocolInterpreter v2.2.1 ? [>It's here!<](https://github.com/Rickedb/OpenProtocolInterpreter/releases/tag/2.2.1) 1. [What is Open Protocol at all?](#what-is-open-protocol-at-all) 2. [What is OpenProtocolInterpreter?](#what-is-openprotocolinterpreter) 3. [Changelog version 3.0.0](#changelog-for-version-3.0.0) 4. [How does it work?](#how-does-it-work) 5. [Usage examples](#lets-see-some-examples-of-usage) 6. [Available on package managers](#get-it-on-nuget) 7. [Advanced section](#advanced-section) * [How it was built?](#how-it-was-built) * [Customization](#mids-identifying-customization) * [Advanced example](#advanced-example) 8. [Tips](#tips) 9. [Contribute to the project](#contribute-to-the-project) 10. [Still unavailable mids](#list-of-still-unavailable-mids) 11. [Next steps](#next-steps) ## What is Open Protocol at all? Open Protocol, as the name says, it's a protocol to communicate with Atlas Copco Tightening Controllers or whatever that implement that protocol. Most common Tightening Controllers from Atlas Copco company are **PowerFocus4000** and **PowerMacs**. *Although, some other companies adhered to use the same protocol.* ## What is OpenProtocolInterpreter? OpenProtocolInterpreter is a **library that converts the ugly string** that came from Open Protocol packages, which is commonly called **MID**, to an **object**. *"Substringing"* packages is such a boring thing to do, so let OpenProtocolIntepreter do it for you! **[If you're curious, just take a look at their documentation.](https://github.com/Rickedb/OpenProtocolIntepreter/blob/master/docs/OpenProtocol_Specification.pdf)** ## Changelog for version 3.0.0 or greater 1. Reworked on how to instantiate a Mid class when parsing to fix a bug where the parse method updates the same instance instead of creating a new; 2. Pack methods added to MidInterpreter as Pack(Mid mid) and PackBytes(Mid mid); 3. Added extension methods to MidInterpreter to use the desired Mids/Message parsers; 4. Now you can instantiate MidIntepreter telling if you're the Controller or the Integrator; 5. Upgraded it from .net framework 4.5.1 to .net standard 2.0 to include .net core projects; ## How does it work? It's simple, you give us your byte[] or string package and we deliver you an object, simple as that! For example, let's imagine you received the following string package: ``` csharp string package = "00240005001 0018"; ``` It's **MID 5**, so OpenProtocolIntepreter will return a **Mid0005** class for you with all his datafields and the package entire translated to an object. ## Let's see some examples of usage A simple usage: ``` csharp var interpreter = new MidInterpreter(); var midPackage = @"00260004001 001802"; var myMid04 = interpreter.Parse<Mid0004>(midPackage); //MID 0004 is an error mid which contains which MID Failed and its error code //Int value of the Failed Mid int myFailedMid = myMid04.FailedMid; //An enum with Error Code Error errorCode = myMid04.ErrorCode; ``` It can generate an object from a string, but can it make it to the other way?? FOR SURE! ``` csharp var jobUploadRequest = new Mid0032(1, 2); //Job id 1, revision 2 var package = jobUploadRequest.Pack(); //Generated package => 00240032002 0001 ``` ## Get it on [NuGet](https://www.nuget.org/packages/OpenProtocolInterpreter)! ``` Install-Package OpenProtocolInterpreter ``` ## Advanced Section! Now we will get real! Put one thing in mind, in real world we will always need to build something more complex than the dummies examples we give to you. **With this in mind, this section is for you:** #### How it was built? It used to rely on **Chain Of Responsabilities** design pattern, but since we had some problems with instance references, it changed! For now, instead of iterating through all Mids of the same category, it relies on a Dictionary, which every category knows which mid it attends, once it found it creates a new Instance via System.Reflection and parse it. #### MIDs Identifying Customization We have several MIDs inside Open Protocol documentation, but do you really need all of them? The answer is... **NO!** You will probably need only to use a range of MIDs, with this in mind, we did something to make things faster. You can tell us which MIDs we should considerate! > *NOTE: You can register only mids you need to call "Parse" method Here is an example: ``` csharp string package = "00260004001 001802"; var myCustomInterpreter = new MidInterpreter() .UseAllMessages(new Type[] { typeof(Mid0001), typeof(Mid0002), typeof(Mid0003), typeof(Mid0004), typeof(Mid0106) }); //Will work: var myMid04 = myCustomInterpreter.Parse<Mid0004>(package); //Won't work, will throw NotImplementedException: var myMid30 = myCustomInterpreter.Parse<Mid0030>(package); //Won't work, will throw InvalidCastException: var myMid01 = myCustomInterpreter.Parse<Mid0001>(package); ``` When you don't know which package will come, use ``` Parse ``` overload, not ``` Parse<DesiredMid> ```. If you want, take a look at the sample on this repository. > If necessary, there is a new overload where you can define if you're the controller or the integrator, which will automatically handle implemented mids #### MIDs Overriding Maybe you have a totally crazy controller that does not implement the Mid as the documentation says or you might want to inject your own Mid inheriting another Mid, so you can customize it and add more properties to handle some conversions. Anyway, if you need that, it's possible to override! Here is an example: ``` csharp //This will override Mid 81 with my custom Mid var _midInterpreter new MidInterpreter().UseAllMessages() .UseTimeMessages(new Dictionary<int, Type>() { { 81, typeof(OverridedMid0081) } }); public class OverridedMid0081 : Mid0081 { public string FormattedDate { get => Time.ToString("dd/MM/yyyy HH:mm:ss"); set => Time = DateTime.Parse(value); } public OverridedMid0081() { } public override string Pack() { Time = TestCustomMid.Now; return base.Pack(); } } ``` #### Adding MIDs that are not in documentation Maybe your controller is weird and have unknown MID numbers, MIDs that are not in the documentation and you want to inject into MidInterpreter, there is a way: ``` csharp var _midInterpreter new MidInterpreter().UseAllMessages() .UseCustomMessage(new Dictionary<int, Type>() { { 83, typeof(NewMid0083) } }); public class NewMid0083 : Mid { private readonly IValueConverter<DateTime> _dateConverter; private const int LAST_REVISION = 1; public const int MID = 83; public DateTime Time { get => GetField(1, (int)DataFields.TIME).GetValue(_dateConverter.Convert); set => GetField(1, (int)DataFields.TIME).SetValue(_dateConverter.Convert, value); } public string TimeZone { get => GetField(1, (int)DataFields.TIMEZONE).Value; set => GetField(1, (int)DataFields.TIMEZONE).SetValue(value); } public NewMid0083() : base(MID, LAST_REVISION) { _dateConverter = new DateConverter(); } protected override Dictionary<int, List<DataField>> RegisterDatafields() { return new Dictionary<int, List<DataField>>() { { 1, new List<DataField>() { new DataField((int)DataFields.TIME, 20, 19), new DataField((int)DataFields.TIMEZONE, 41, 2) } } }; } public enum DataFields { TIME, TIMEZONE } } ``` > **NOTE:** Custom messages might not perform as fast as other MIDs because they don't have optimizations for finding it #### Advanced Example Declared a delegate: ``` csharp protected delegate void ReceivedCommandActionDelegate(ReceivedMIDEventArgs e); ``` **ReceivedMIDEventArgs class**: ``` csharp public class ReceivedMidEventArgs : EventArgs { public Mid ReceivedMid { get; set; } } ``` Created a method to register all those MID types by delegates: ``` csharp protected Dictionary<Type, ReceivedCommandActionDelegate> RegisterOnAsyncReceivedMids() { var receivedMids = new Dictionary<Type, ReceivedCommandActionDelegate>(); receivedMids.Add(typeof(Mid0005), new ReceivedCommandActionDelegate(OnCommandAcceptedReceived)); receivedMids.Add(typeof(Mid0004), new ReceivedCommandActionDelegate(OnErrorReceived)); receivedMids.Add(typeof(Mid0071), new ReceivedCommandActionDelegate(OnAlarmReceived)); receivedMids.Add(typeof(Mid0061), new ReceivedCommandActionDelegate(OnTighteningReceived)); receivedMids.Add(typeof(Mid0035), new ReceivedCommandActionDelegate(OnJobInfoReceived)); return receivedMids; } ``` What was done is registering in a dictionary the correspondent delegate for a determinated MID, once done that we just need to invoke the delegate everytime you face a desired MID. When a package income: ``` csharp protected void OnPackageReceived(string message) { try { //Parse to mid class var mid = Interpreter.Parse(message); //Get Registered delegate for the MID that was identified var action = OnReceivedMid.FirstOrDefault(x => x.Key == mid.GetType()); if (action.Equals(default(KeyValuePair<Type, ReceivedCommandActionDelegate>))) return; //Stop if there is no delegate registered for the message that arrived action.Value(new ReceivedMidEventArgs() { ReceivedMid = mid }); //Call delegate } catch (Exception ex) { Console.log(ex.Message); } } ``` This would call the registered delegate which you're sure what mid it is. For example when a **MID_0061** (last tightening) pop up, the **onTighteningReceived** delegate will be called: ``` csharp protected void OnTighteningReceived(ReceivedMidEventArgs e) { try { Mid0061 tighteningMid = e.ReceivedMID as Mid0061; //Casting to the right mid //This method just send the ack from tightening mid BuildAndSendAcknowledge(tighteningMid); Console.log("TIGHTENING ARRIVED") } catch (Exception ex) { Console.log(ex.Message); } } protected void BuildAndSendAcknowledge(Mid mid) { TcpClient.GetStream().Write(new Mid0062().Pack()); //Send acknowledge to controller } ``` ### Tips > Instantiate the **MIDIdentifier** class just once and keep working with it! > **Controller Implementation Tip:** Always **TRY** to register used MIDs, not all Tightening Controllers use every available MID. > **Integrator Implementation Tip:** Always **DO** register used MIDs, I'm pretty sure you won't need all of them to your application. ### Contribute to the project Lot's of effort were given to this project and by seen people using it motivated me a lot to improve it more and more. Does it help you a lot? That's awesome and very rewarding! But if you wish, you can support and help to motivate the constant improving of this library by contributing in [OpenCollective](https://opencollective.com/open-protocol-interpreter). ### List of still unavailable Mids - Mid 0009; - Mid 0066; - Mid 0700; - Mid 0702; - Mid 0703; - Mid 0900; - Mid 0901; - Mid 1000; - Mid 1001; - Mid 1601; - Mid 1602; - Mid 1900; - Mid 1901; - Mid 2100; - Mid 2500; - Mid 2501; - Mid 2505; - Mid 2600; - Mid 2601; - Mid 2602; - Mid 2603; - Mid 2604; - Mid 2605; - Mid 2606. Feel free to fork and contribute to add any of those mids. ### Next Steps 1. Add missing mids; 2. Create wiki.
{ "content_hash": "59330f54aa4ca128a2072038f09fcb9e", "timestamp": "", "source": "github", "line_count": 356, "max_line_length": 243, "avg_line_length": 37.01685393258427, "alnum_prop": 0.7010927303080893, "repo_name": "Rickedb/OpenProtocolIntepreter", "id": "c7f544790a7e8036a30f76c12783ae71f1b0f2c7", "size": "13178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "425509" } ], "symlink_target": "" }
const R = require('ramda'); const { authenticate } = require('feathers-authentication').hooks; const { associateCurrentUser } = require('feathers-authentication-hooks'); const hypermedia = require('../hypermedia'); const allowedFields = hook => { hook.params.sequelize = { fields: ['title', 'description', 'plainDescription', 'published', 'tags','traits','measurements'], }; }; const setCurrentUser = associateCurrentUser({ idField: 'id', as: 'user_id', }); const filterProjectWhere = { publicProject: { published: true }, isAuthor: userId => ({ user_id: userId }), hasMembership: userId => ({ '$projectMemberships.user_id$': userId }), }; const filterProjects = hook => { // If it was an internal call then skip this hook if (!hook.params.provider) { return hook; } const sequelize = hook.app.get('sequelizeClient'); hook.params.query = Object.assign({}, hook.params.query, { $or: [ filterProjectWhere.publicProject, filterProjectWhere.isAuthor(hook.params.user.id), filterProjectWhere.hasMembership(hook.params.user.id), ], }); hook.params.sequelize = Object.assign({}, hook.params.sequelize,{ include: [ { duplicating: false, // seems to be the only way to make it work with where clause, join AND limit attributes: [], model: sequelize.models.projectMemberships, as: 'projectMemberships', }, ], }); return hook; }; const isUpdatePossible = hook => { // If it was an internal call then skip this hook if (!hook.params.provider) { return hook; } const userId = hook.params.user.id; const sequelize = hook.app.get('sequelizeClient'); const projectsService = hook.app.service('projects'); return projectsService .get(hook.id, { query: { $or: [ filterProjectWhere.publicProject, filterProjectWhere.isAuthor(userId), filterProjectWhere.hasMembership(userId), ], }, sequelize: { include: [ { duplicating: false, // seems to be the only way to make it work with where clause, join AND limit attributes: [], model: sequelize.models.projectMemberships, as: 'projectMemberships', }, ], }, }) .then(() => { return hook; }); }; const isAuthor = (project, userId) => project.user_id === userId; const allowedActions = hook => { // If it was an internal call then skip this hook if (!hook.params.provider) { return hook; } const userId = hook.params.user.id; hook.result['@actions'] = hypermedia.actions(false, false); if (isAuthor(hook.result, userId)) { hook.result['@actions'] = hypermedia.actions(true, true); } else { const projectMembershipsService = hook.app.service('project-memberships'); return projectMembershipsService .find({ paginate: false, query: { project_id: hook.id, user_id: userId } }) .then(memberships => { const isEditor = memberships.filter(membership => membership.type === 'editor').length > 0; if (isEditor) { hook.result['@actions'] = hypermedia.actions(true, true); } return hook; }); } return hook; }; const allowedActionsOnList = hook => { // If it was an internal call then skip this hook if (!hook.params.provider) { return hook; } const userId = hook.params.user.id; const projectIds = R.pluck('id', hook.result.data); const projectMembershipsService = hook.app.service('project-memberships'); return projectMembershipsService .find({ paginate: false, query: { project_id: { $in: projectIds }, user_id: userId } }) .then(memberships => { const projectsWithActions = hook.result.data.map(project => { const isEditor = memberships.filter(membership => membership.type === 'editor' && membership.project_id === project.id) .length > 0; if (isEditor || isAuthor(project, userId)) { project['@actions'] = hypermedia.actions(true, true); } else { project['@actions'] = hypermedia.actions(false, false); } return project; }); hook.result.data = projectsWithActions; return hook; }); }; const findAllAttributes = hook => { const sequelize = hook.app.get('sequelizeClient'); hook.params.sequelize = Object.assign({}, hook.params.sequelize,{ attributes: [ 'id', 'title', [sequelize.fn('LEFT', sequelize.col('plain_description'),100),'plainDescription'] ] }); }; module.exports = { before: { all: [authenticate('jwt')], find: [findAllAttributes], get: [filterProjects], create: [setCurrentUser], update: [isUpdatePossible, allowedFields], patch: [isUpdatePossible, allowedFields], remove: [isUpdatePossible], }, after: { all: [], find: [allowedActionsOnList], get: [allowedActions], create: [], update: [], patch: [], remove: [], }, error: { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [], }, };
{ "content_hash": "8464aa689edb819dfbd40aeb72d2a72f", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 112, "avg_line_length": 29.245714285714286, "alnum_prop": 0.6178194607268465, "repo_name": "YeFFreY/bernard", "id": "0b8f5eb3a5b79c21045ef9f659d8f8bf2092e18a", "size": "5118", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/src/services/projects/projects.hooks.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "352" }, { "name": "HTML", "bytes": "12510" }, { "name": "JavaScript", "bytes": "98161" } ], "symlink_target": "" }
'use strict'; module.exports = { friendlyName: "REST.api.call", injectableName: "Task.Base.Rest", runJob:"Job.Rest", requiredOptions:["url", "method"], requiredProperties:[], properties:{} };
{ "content_hash": "8cc7050a0055d8802713495c11863eb1", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 38, "avg_line_length": 21.7, "alnum_prop": 0.6267281105990783, "repo_name": "nortonluo/on-tasks", "id": "8b922ac864e400f61e12065d47e80f7b09faacf4", "size": "247", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/task-data/base-tasks/rest.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "2600238" }, { "name": "Shell", "bytes": "2671" } ], "symlink_target": "" }
#include "own_functions.h" // void findMatches(StringSet<String<Dna>> & Reads,StringSet<String<char>> & ReadID,StringSet<String<AminoAcid>> & Proteine, StringSet<String<char>> & ProteinID, int seed,StringSet<String<int>> & Alphabete){ // Schleife fuer jedes Alphabet for(int alp=0;alp<length(Alphabete);++alp){ StringSet<String<int>> trans_reads; // Schleife fuer jedes Read // Uebersetzung for (int read=0;read<length(Reads);++read){ // Schleife fuer jedes moegliche Reading-Frame for(int reading_frame=0;reading_frame<6;++reading_frame){ // Funktion in translate.cpp translate_reads(trans_reads,Reads[read],Alphabete[alp],reading_frame); } } for (int p=0;p<length(trans_reads);p++) cout << trans_reads[p]<<endl; // Schleife fuer jedes Protein // Uebersetzung StringSet<String<int>> trans_databank; String<AminoAcid> x = Proteine[0]; for (int p=0;p<length(x);++p) cout << (int)x[p]<<"\t"; //for (int protein=0;protein<length(Proteine);++protein){ //} } }
{ "content_hash": "3d04aaf9e7f10f439c793a21498921a2", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 121, "avg_line_length": 38.2962962962963, "alnum_prop": 0.6682785299806576, "repo_name": "bkahlert/seqan-research", "id": "84d199570b3bc593eb41459cce88b2dafdcab6a6", "size": "1171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "raw/pmsb13/pmsb13-data-20130530/sources/fjt74l9mlcqisdus/2013-04-21T20-58-04.985+0200/sandbox/my_sandbox/apps/blastX/finder.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "39014" }, { "name": "Awk", "bytes": "44044" }, { "name": "Batchfile", "bytes": "37736" }, { "name": "C", "bytes": "1261223" }, { "name": "C++", "bytes": "277576131" }, { "name": "CMake", "bytes": "5546616" }, { "name": "CSS", "bytes": "271972" }, { "name": "GLSL", "bytes": "2280" }, { "name": "Groff", "bytes": "2694006" }, { "name": "HTML", "bytes": "15207297" }, { "name": "JavaScript", "bytes": "362928" }, { "name": "LSL", "bytes": "22561" }, { "name": "Makefile", "bytes": "6418610" }, { "name": "Objective-C", "bytes": "3730085" }, { "name": "PHP", "bytes": "3302" }, { "name": "Perl", "bytes": "10468" }, { "name": "PostScript", "bytes": "22762" }, { "name": "Python", "bytes": "9267035" }, { "name": "R", "bytes": "230698" }, { "name": "Rebol", "bytes": "283" }, { "name": "Shell", "bytes": "437340" }, { "name": "Tcl", "bytes": "15439" }, { "name": "TeX", "bytes": "738415" }, { "name": "VimL", "bytes": "12685" } ], "symlink_target": "" }
Date: 2018/02/19 Authors: Echo Can Luo Keywords: 3D Avatar Performance, Installation --- --- # Nicely nicely all the time! – Nr. 1 ![](Echo_3.jpg) In Deutschland leben viele Menschen mit unterschiedlicher Herkunft. Die meisten davon haben schon Erfahrungen mit Diskriminierung und Rassismus erlebt. Um in dieses Thema weiter einzusteigen habe ich Interviews mit einigen Betroffenen geführt und eine Reihe von Gesichtern 3D eingescannt um diese als interaktive Avatare dem Publikum zur Verfügung zu stellen. Während die Besucherin oder der Besucher eine der Geschichten aus den Interviews am Mikrofon vorließt, wird das Gesicht durch das eines der animierten Avatare ersetzt. In anderer, virtueller Haut werden Erfahrungen neu erlebt. ![](Echo_2.jpg) ![](Echo_1.jpg)
{ "content_hash": "2932ea260fd9f7c119024d329ffdff4b", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 586, "avg_line_length": 48.25, "alnum_prop": 0.7953367875647669, "repo_name": "voec/website015", "id": "9a2656613c9c871c6f78afb649b90689f9fce84e", "size": "778", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "content/201802-echo-can-luo-nicely-nicely-all-the-time-nr1/echo-can-luo-nicely-nicely-all-the-time-nr1.md", "mode": "33188", "license": "mit", "language": [ { "name": "Hack", "bytes": "10633" }, { "name": "PHP", "bytes": "16272" }, { "name": "Shell", "bytes": "52" } ], "symlink_target": "" }
<?php ///////////////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ // BioDigital Content API OAuth using PHP 5.6 // // Author: BioDigital Inc. // Email: developers@biodigital.com // // This example uses PHP sample code // found here: https://www.oauth.com/oauth2-servers/oauth2-clients/server-side-apps/ // // For more information about the OAuth process for web applications // accessing BioDigital APIs, please visit: // https://developer.biodigital.com // ////////////////////////////////////////////////////////////////////// define('SSLVERIFY', false); // BioDigital OAuth endpoint for requesting an access token define('OAUTH_TOKEN_URL', 'https://apis.biodigital.com/oauth2/v2/token/'); // BioDigital Content API endpoint for collection requests define('CONTENTAPI_COLLECTIONS_URL', 'https://apis.biodigital.com/services/v2/content/collections/'); // Your API / Developer key you received when you registered your // application at https://developer.biodigital.com define('CLIENT_ID', '<DEVELOPER_KEY>'); // Your API / Developer secret you received when you registered your // application at https://developer.biodigital.com define('CLIENT_SECRET', '<DEVELOPER_SECRET>'); // The type of authorization being requested define('GRANT_TYPE', 'client_credentials'); // The service scope in which your authorization will be used define('SCOPE', 'contentapi'); // Start a session so we have a place to store things session_start(); include_once('myview.php'); // Helper functions: These functions let us access query string parameters // and session data easily without checking if keys exist first. function get($key, $default=NULL) { return array_key_exists($key, $_GET) ? $_GET[$key] : $default; } function session($key, $default=NULL) { return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default; } function request_access_token(){ // *********************************************************** // Exchanges basic client credentials for an access token // *********************************************************** // Construct authentication string: // 1. Concatenate the client id, a colon character ":", and the client secret into a single string // 2. URL encode the string from step 1 // 3. Base64 encode the string from step 2 $authstr = '%s:%s'; $authstr = sprintf($authstr, CLIENT_ID, CLIENT_SECRET); $authstr = iconv(mb_detect_encoding($authstr, mb_detect_order(), true), "UTF-8", $authstr); $authstr = base64_encode($authstr); # For Private application authentication, you must specifiy # grant_type=client_credentials and the service scope. For the # Content API, scope=contentapi $post_data = array( 'grant_type' => GRANT_TYPE, 'scope' => SCOPE ); $post_data_string = json_encode($post_data); $ch = curl_init(OAUTH_TOKEN_URL); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, SSLVERIFY); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS,"POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_string); // Construct an Authorization header with the value of 'Basic <base64 encoded auth string>' $headers[] = 'Authorization: Basic ' . $authstr; $headers[] = 'Content-Type: application/json;charset=UTF-8'; $headers[] = 'Accept: application/json'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $response = curl_exec($ch); if(curl_error($ch)) { # Handle unknown error echo '<pre>'; echo '<h3>Unknown Error:</h3>'; echo '<pre>'; echo curl_error($ch); } else { $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $json = json_decode($response); $json_print = json_encode($json, JSON_PRETTY_PRINT); if (in_array($httpcode, array(400,500), true) ){ # Handle known error echo '<pre>'; echo '<h3>Known Error:</h3>'; echo '<pre>'; echo $json_print; } else if ($httpcode == 200) { $results = json_decode($response); $_SESSION['access_token'] = $results->access_token; $_SESSION['token_type'] = $results->token_type; $_SESSION['expires_in'] = $results->expires_in; $_SESSION['timestamp'] = $results->timestamp; $dtime = DateTime::createFromFormat("Y-m-d\TH:i:s", $results->timestamp); $dtime->add(DateInterval::createFromDateString($results->expires_in . ' seconds')); $_SESSION['token_expiry'] = $dtime->format('Y-m-d\TH:i:s'); $t = new MyView(); $t->access_token = $_SESSION['access_token']; $t->token_type = $results->token_type; $t->expires_in = $results->expires_in; $t->timestamp = $results->timestamp; $t->token_expiry = $_SESSION['token_expiry']; $t->render('access-token.phtml'); } } curl_close($ch); } function query_collection_myhuman ($access_token){ // *********************************************************** // Query Content API Collection with access token. // *********************************************************** $url = CONTENTAPI_COLLECTIONS_URL . "myhuman"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); # do not output, but store to variable curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, SSLVERIFY); # Construct an Authorization header with the value of 'Bearer <access token>' $headers[] = 'Authorization: Bearer ' . $access_token; $headers[] = 'Accept: application/json'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); if(curl_error($ch)) { # Handle unknown error echo '<pre>'; echo '<h3>Unknown Error:</h3>'; echo '<pre>'; echo curl_error($ch); } else { $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $json = json_decode($response); $json_print = json_encode($json, JSON_PRETTY_PRINT); $t = new MyView(); if (in_array($httpcode, array(400,500), true)){ $t->reponse_status = "Error!"; } else if ($httpcode == 200) { $t->reponse_status = "Successful!"; } $t->access_token = $_SESSION['access_token']; $t->endpoint_path = 'myhuman/'; $t->myhuman_results = $json_print; $t->render('myhuman.phtml'); } curl_close($ch); } function query_collection_mycollections ($access_token){ // *********************************************************** // Query Content API Collection with access token. // *********************************************************** $url = CONTENTAPI_COLLECTIONS_URL . "mycollections"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); # do not output, but store to variable curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, SSLVERIFY); # Construct an Authorization header with the value of 'Bearer <access token>' $headers[] = 'Authorization: Bearer ' . $access_token; $headers[] = 'Accept: application/json'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); if(curl_error($ch)) { # Handle unknown error echo '<pre>'; echo '<h3>Unknown Error:</h3>'; echo '<pre>'; echo curl_error($ch); } else { $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $json = json_decode($response); $json_print = json_encode($json, JSON_PRETTY_PRINT); $t = new MyView(); if (in_array($httpcode, array(400,500), true)){ $t->reponse_status = "Error!"; } else if ($httpcode == 200) { $t->reponse_status = "Successful!"; } $t->access_token = $_SESSION['access_token']; $t->endpoint_path = 'mycollections/'; $t->mycollections_results = $json_print; $t->mycollections_results_obj = $json; $t->render('mycollections.phtml'); } curl_close($ch); } function query_collection_mycollections_id ($access_token, $collection_id){ // *********************************************************** // Query Content API Collection with access token. // *********************************************************** $url = CONTENTAPI_COLLECTIONS_URL . "mycollections/$collection_id"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); # do not output, but store to variable curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, SSLVERIFY); # Construct an Authorization header with the value of 'Bearer <access token>' $headers[] = 'Authorization: Bearer ' . $access_token; $headers[] = 'Accept: application/json'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); if(curl_error($ch)) { # Handle unknown error echo '<pre>'; echo '<h3>Unknown Error:</h3>'; echo '<pre>'; echo curl_error($ch); } else { $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $json = json_decode($response); $json_print = json_encode($json, JSON_PRETTY_PRINT); $t = new MyView(); if (in_array($httpcode, array(400,500), true)){ $t->reponse_status = "Error!"; } else if ($httpcode == 200) { $t->reponse_status = "Successful!"; } $t->access_token = $_SESSION['access_token']; $t->endpoint_path = "mycollections/$collection_id"; $t->mycollections_id_results = $json_print; $t->mycollections_id_results_obj = $json; $t->render('mycollections-id.phtml'); } curl_close($ch); } function query_collection_mycollections_id_content_list ($access_token, $collection_id){ // *********************************************************** // Query Content API Collection with access token. // *********************************************************** $url = CONTENTAPI_COLLECTIONS_URL . "mycollections/$collection_id/content_list"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); # do not output, but store to variable curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, SSLVERIFY); # Construct an Authorization header with the value of 'Bearer <access token>' $headers[] = 'Authorization: Bearer ' . $access_token; $headers[] = 'Accept: application/json'; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); if(curl_error($ch)) { # Handle unknown error echo '<pre>'; echo '<h3>Unknown Error:</h3>'; echo '<pre>'; echo curl_error($ch); } else { $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); $json = json_decode($response); $json_print = json_encode($json, JSON_PRETTY_PRINT); $t = new MyView(); if (in_array($httpcode, array(400,500), true)){ $t->reponse_status = "Error!"; } else if ($httpcode == 200) { $t->reponse_status = "Successful!"; } $t->access_token = $_SESSION['access_token']; $t->endpoint_path = "mycollections/$collection_id/content_list"; $t->mycollections_id_contentlist_results = $json_print; $t->mycollections_id_contentlist_results_obj = $json; $t->render('mycollections-id-content_list.phtml'); } curl_close($ch); } try { if (get('action') == 'request_access_token'){ request_access_token(); } else if (get('action') == 'query_collection_myhuman'){ query_collection_myhuman(get('access_token')); } else if (get('action') == 'query_collection_mycollections'){ query_collection_mycollections(get('access_token')); } else if (get('action') == 'query_collection_mycollections_id'){ query_collection_mycollections_id(get('access_token'), get('collection_id')); } else if (get('action') == 'query_collection_mycollections_id_content_list'){ query_collection_mycollections_id_content_list(get('access_token'), get('collection_id')); } else { echo '<pre>'; echo '<h3>Private Application Authentication</h3>'; echo '<pre>'; echo '<a href="?action=request_access_token">Request Access Token</a>'; } } catch(OAuthException $e) { echo '<pre>'; print_r($e); } ?>
{ "content_hash": "5dbc20a929858e57431805aba9efc645", "timestamp": "", "source": "github", "line_count": 381, "max_line_length": 103, "avg_line_length": 32.57217847769029, "alnum_prop": 0.577276390008058, "repo_name": "biodigital-inc/bdhuman-contentapi", "id": "6e8d14a3c194aa99fdd2e223088eddede3fd26eb", "size": "12410", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "php/v2.0/client.php", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "14422" }, { "name": "C#", "bytes": "47969" }, { "name": "HTML", "bytes": "27790" }, { "name": "Java", "bytes": "41094" }, { "name": "JavaScript", "bytes": "26633" }, { "name": "PHP", "bytes": "20720" }, { "name": "Python", "bytes": "19450" }, { "name": "Ruby", "bytes": "25326" } ], "symlink_target": "" }
Unobstrusive tooltips jQuery/Zepto plugin. ## Requirements utip has no other requirements than jQuery/Zepto. ## Installation Include utip's CSS and jQuery/Zepto plugin. ```html <script type='text/javascript' src='jquery.utip.js'></script> <link rel="stylesheet" href="utip.css" type="text/css" /> ``` ## Markup Specify a `data-utip` attribute on any DOM element you'd want a tooltip on, set to the tooltip's content, e.g. ```html <a href="#" data-utip="Hello, I'm a utip.">Tooltip</a> ``` You can also specify a `data-utip-gravity` on those elements to set the tooltip's direction, e.g. ```html <a href="#" data-utip="Hello, I'm a righty tooltip." data-utip-gravity="e">Tooltip</a> ``` `data-utip-gravity` can be set to `nw | n | ne | e | se | s | sw | w` If you want to be able to hover on the tooltip, add a `data-utip-hoverable` attribute to the element, e.g. ```html <a href="#" data-utip="Hello, I'm a hoverable utip." data-utip-hoverable>Tooltip</a> ``` ## Usage ```javascript $(function(){ $('a[data-utip]').utip(); }); ``` **Note:** utip binds its event to `$(document)` rather than the elements themselves, making it possible to dynamically add or remove utip'ed elements that match the selector, or in this case, `$('a[data-utip]')`. ## License This software is licensed under the MIT license.
{ "content_hash": "fcdb94e566197370870eca557220c120", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 212, "avg_line_length": 26.48, "alnum_prop": 0.6858006042296072, "repo_name": "symeapp/utip", "id": "884eede07cdb3c711cd3ece1cf671d503a1be9f2", "size": "1332", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6339" }, { "name": "JavaScript", "bytes": "2728" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "b79285a51e2652bc3584b8f62235055d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "ed52fce996b4f48d841b80b6692e27e5c426c984", "size": "173", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Alismatales/Zosteraceae/Zostera/Zostera hornemanni/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
ActiveForm::Element::SelectNumericRange::create :select_month do define_option_flags :use_short_month, :add_month_numbers, :use_month_numbers def to_monthname multiple? ? element_value.map { |i| number_to_label(i) } : number_to_label(element_value) end def export_value exp_value = super if self.type_cast == :string to_monthname else exp_value end end def range (1..12) end def casting_for_string [nil, nil] end def casting_filter(value) value = case value when Date, Time then value.month when Array, Range then value.to_a else value.to_i rescue 0 end super(value) end def number_to_label(month_number) month_names = use_short_month? ? Date::ABBR_MONTHNAMES : Date::MONTHNAMES rescue {} if use_month_numbers? || month_names.empty? month_number.zero_padded(2) elsif add_month_numbers? month_number.zero_padded(2) + ' - ' + month_names[month_number] else month_names[month_number] end end end
{ "content_hash": "edb1fd6844dba76c97bb238ccfdeb011", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 93, "avg_line_length": 22.847826086956523, "alnum_prop": 0.6403425309229306, "repo_name": "davesag/active_form", "id": "6c3af5466af556d0b3bd95c5ba12697eac3dd009", "size": "1051", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "lib/active_form/facets/select_month.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "448676" } ], "symlink_target": "" }
package com.twitter.hbc.example; import com.twitter.hbc.ClientBuilder; import com.twitter.hbc.core.Client; import com.twitter.hbc.core.Constants; import com.twitter.hbc.core.endpoint.RealTimeEnterpriseStreamingEndpoint; import com.twitter.hbc.core.processor.LineStringProcessor; import com.twitter.hbc.httpclient.auth.BasicAuth; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class EnterpriseStreamExample { public static void run(String username, String password, String account, String label, String product) throws InterruptedException { BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10000); BasicAuth auth = new BasicAuth(username, password); RealTimeEnterpriseStreamingEndpoint endpoint = new RealTimeEnterpriseStreamingEndpoint(account, product, label); // Create a new BasicClient. By default gzip is enabled. Client client = new ClientBuilder() .name("PowerTrackClient-01") .hosts(Constants.ENTERPRISE_STREAM_HOST) .endpoint(endpoint) .authentication(auth) .processor(new LineStringProcessor(queue)) .build(); // Establish a connection client.connect(); // Do whatever needs to be done with messages for (int msgRead = 0; msgRead < 1000; msgRead++) { String msg = queue.take(); System.out.println(msg); } client.stop(); } // public static void main(String[] args) { // try { // EnterpriseStreamExample.run(args[0], args[1], args[2], args[3], args[4]); // } catch (InterruptedException e) { // System.out.println(e); // } // } }
{ "content_hash": "979812578c7fa4047be0627b4a2c89d5", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 116, "avg_line_length": 31.607142857142858, "alnum_prop": 0.6649717514124294, "repo_name": "twitter/hbc", "id": "f9c281b74c5c11ee777cfdcb58dce14127c7c5b6", "size": "2355", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "hbc-example/src/main/java/com/twitter/hbc/example/EnterpriseStreamExample.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "287758" } ], "symlink_target": "" }
module Support module Constants def self.included(base) base.extend(ClassMethods) end module ClassMethods def uses_constants(*constants) before { create_constants(*constants) } end end def create_constants(*constants) constants.each { |constant| create_constant(constant) } end def remove_constants(*constants) constants.each { |constant| remove_constant(constant) } end def create_constant(constant) remove_constant(constant) Object.const_set(constant, Model(constant)) end def remove_constant(constant) Object.send(:remove_const, constant) if Object.const_defined?(constant) end def Model(name=nil) Class.new.tap do |model| model.class_eval """ def self.name; '#{name}' end def self.to_s; '#{name}' end """ if name model.send(:include, Ricordami::Model) end end end end
{ "content_hash": "677ce08a01397ea16418946ffbc8c84d", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 77, "avg_line_length": 23.75, "alnum_prop": 0.628421052631579, "repo_name": "mathieul/ricordami", "id": "bee9234f6f007fded413618e7ced0cc799d4822d", "size": "1086", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/support/constants.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "147178" } ], "symlink_target": "" }
module NominetEPP module Domain class Renew < Request def initialize(name, exp_date, period = nil) validate_period(period) @command = EPP::Domain::Renew.new(name, exp_date, period) end end end end
{ "content_hash": "ca4c36be4463608599756f00100f0d4c", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 65, "avg_line_length": 23.7, "alnum_prop": 0.6371308016877637, "repo_name": "m247/nominet-epp", "id": "9a6c8261a477989003d5fd34f30fe31fd981fe71", "size": "237", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/nominet-epp/requests/domain/renew.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "143921" } ], "symlink_target": "" }
namespace app { 'use strict'; /** * * * @export * @interface IRightsService */ export interface IRightsService { /** * * * @param {Club} club * @param {AppUser} user * @returns {angular.IPromise<void>} */ giveRights(club: Club, user: AppUser): angular.IPromise<void>; } /** * * * @class RightsService * @implements {IRightsService} */ class RightsService implements IRightsService { /** * * * @private * @type {*} */ private firebaseRolesRef: any; /** * * * @private * @type {*} */ private firebaseUserRolesRef: any; // @ngInject /** * Creates an instance of RightsService. * * @param {angular.IRootScopeService} $rootScope * @param {angular.IQService} $q * @param {angular.ILogService} $log */ constructor( private $rootScope: angular.IRootScopeService, private $q: angular.IQService, private $log: angular.ILogService ) { let me: RightsService = this; me.firebaseRolesRef = firebase.database().ref('/roles'); me.firebaseUserRolesRef = firebase.database().ref('/userroles'); } /** * * * @param {Club} club * @param {AppUser} user * @returns {angular.IPromise<void>} */ public giveRights(club: Club, user: AppUser): angular.IPromise<void> { let me: RightsService = this; let def: angular.IDeferred<any> = me.$q.defer(); return def.promise; } /** * * * @param {AppUser} user * @param {(Club | Event | Post)} item * @returns {angular.IPromise<boolean>} */ public hasRights(user: AppUser, item: Club | Event | Post): angular.IPromise<boolean> { let me: RightsService = this; let def: angular.IDeferred<boolean> = me.$q.defer(); return def.promise; } } angular.module('app').service('rightsService', RightsService); }
{ "content_hash": "f10de5ff556701ba9108de27229a79f1", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 95, "avg_line_length": 24.294736842105262, "alnum_prop": 0.4865684575389948, "repo_name": "cskiwi/portal-for-fun", "id": "32844307f3e706bad6c18caf253195ea57a51a14", "size": "2308", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Web/app/shared/services/rights.serice.ts", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "243" }, { "name": "CSS", "bytes": "4507" }, { "name": "HTML", "bytes": "12465" }, { "name": "JavaScript", "bytes": "11810" }, { "name": "Shell", "bytes": "76" }, { "name": "TypeScript", "bytes": "57403" } ], "symlink_target": "" }
<html lang="en"> <head> <title>Tree SSA - GNU Compiler Collection (GCC) Internals</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="GNU Compiler Collection (GCC) Internals"> <meta name="generator" content="makeinfo 4.7"> <link title="Top" rel="start" href="index.html#Top"> <link rel="prev" href="Control-Flow.html#Control-Flow" title="Control Flow"> <link rel="next" href="Loop-Analysis-and-Representation.html#Loop-Analysis-and-Representation" title="Loop Analysis and Representation"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- Copyright (C) 1988, 1989, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with the Invariant Sections being ``GNU General Public License'' and ``Funding Free Software'', the Front-Cover texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the section entitled ``GNU Free Documentation License''. (a) The FSF's Front-Cover Text is: A GNU Manual (b) The FSF's Back-Cover Text is: You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development.--> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family: serif; font-weight: normal; } --></style> </head> <body> <div class="node"> <p> <a name="Tree-SSA"></a>Next:&nbsp;<a rel="next" accesskey="n" href="Loop-Analysis-and-Representation.html#Loop-Analysis-and-Representation">Loop Analysis and Representation</a>, Previous:&nbsp;<a rel="previous" accesskey="p" href="Control-Flow.html#Control-Flow">Control Flow</a>, Up:&nbsp;<a rel="up" accesskey="u" href="index.html#Top">Top</a> <hr><br> </div> <h2 class="chapter">10 Analysis and Optimization of GIMPLE Trees</h2> <p><a name="index-Tree-SSA-2066"></a><a name="index-Optimization-infrastructure-for-GIMPLE-2067"></a> GCC uses three main intermediate languages to represent the program during compilation: GENERIC, GIMPLE and RTL. GENERIC is a language-independent representation generated by each front end. It is used to serve as an interface between the parser and optimizer. GENERIC is a common representation that is able to represent programs written in all the languages supported by GCC. <p>GIMPLE and RTL are used to optimize the program. GIMPLE is used for target and language independent optimizations (e.g., inlining, constant propagation, tail call elimination, redundancy elimination, etc). Much like GENERIC, GIMPLE is a language independent, tree based representation. However, it differs from GENERIC in that the GIMPLE grammar is more restrictive: expressions contain no more than 3 operands (except function calls), it has no control flow structures and expressions with side-effects are only allowed on the right hand side of assignments. See the chapter describing GENERIC and GIMPLE for more details. <p>This chapter describes the data structures and functions used in the GIMPLE optimizers (also known as &ldquo;tree optimizers&rdquo; or &ldquo;middle end&rdquo;). In particular, it focuses on all the macros, data structures, functions and programming constructs needed to implement optimization passes for GIMPLE. <ul class="menu"> <li><a accesskey="1" href="GENERIC.html#GENERIC">GENERIC</a>: A high-level language-independent representation. <li><a accesskey="2" href="GIMPLE.html#GIMPLE">GIMPLE</a>: A lower-level factored tree representation. <li><a accesskey="3" href="Annotations.html#Annotations">Annotations</a>: Attributes for statements and variables. <li><a accesskey="4" href="Statement-Operands.html#Statement-Operands">Statement Operands</a>: Variables referenced by GIMPLE statements. <li><a accesskey="5" href="SSA.html#SSA">SSA</a>: Static Single Assignment representation. <li><a accesskey="6" href="Alias-analysis.html#Alias-analysis">Alias analysis</a>: Representing aliased loads and stores. </ul> </body></html>
{ "content_hash": "71844f37422b2a9a104aaa5ec7bc7c46", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 177, "avg_line_length": 52.417582417582416, "alnum_prop": 0.7362683438155136, "repo_name": "UECIDE/UECIDE_data", "id": "036c446556d8dc93b7b1264ef758cd5e63974809", "size": "4770", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "compilers/avr-gcc/windows/avr-gcc/doc/gcc/HTML/gcc-4.3.2/gccint/Tree-SSA.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Arduino", "bytes": "3816646" }, { "name": "Assembly", "bytes": "1421566" }, { "name": "C", "bytes": "546627695" }, { "name": "C++", "bytes": "113272035" }, { "name": "CSS", "bytes": "64919" }, { "name": "Emacs Lisp", "bytes": "237675" }, { "name": "Erlang", "bytes": "5952" }, { "name": "Java", "bytes": "3443" }, { "name": "JavaScript", "bytes": "22190" }, { "name": "Max", "bytes": "312593" }, { "name": "Objective-C", "bytes": "98663423" }, { "name": "Perl", "bytes": "563426" }, { "name": "Processing", "bytes": "1052533" }, { "name": "Pure Data", "bytes": "9910" }, { "name": "Python", "bytes": "383681" }, { "name": "Shell", "bytes": "800332" }, { "name": "Tcl", "bytes": "1379995" }, { "name": "TeX", "bytes": "510" }, { "name": "XC", "bytes": "79648" } ], "symlink_target": "" }
<?php namespace PHPExiftool\Driver\Tag\QuickTime; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class Gamma extends AbstractTag { protected $Id = 'gama'; protected $Name = 'Gamma'; protected $FullName = 'QuickTime::ImageDesc'; protected $GroupName = 'QuickTime'; protected $g0 = 'QuickTime'; protected $g1 = 'QuickTime'; protected $g2 = 'Image'; protected $Type = 'fixed32u'; protected $Writable = false; protected $Description = 'Gamma'; }
{ "content_hash": "1a571cf6b8ce16fb8041fdb25f6c2417", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 49, "avg_line_length": 16.228571428571428, "alnum_prop": 0.6654929577464789, "repo_name": "romainneutron/PHPExiftool", "id": "3a72fc6f5f0a1385a13e1377c659d204e4011f83", "size": "790", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/PHPExiftool/Driver/Tag/QuickTime/Gamma.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "22042446" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.OleDb; using System.Data.SqlClient; using System.Security; using System.Windows; using Brackets2012; using C5; using System.Collections; namespace Brackets2012 { public class Player : IEquatable<Player>, IComparer<Player> { //used for the overridden ToString() method. private const string lastfirst = "lf"; private const string firstlast = "fl"; #region PlayerMembers private String firstName; public String _firstName { get { return firstName; } set { this.firstName = value; } } private String lastName; public String _lastName { get { return lastName; } set { this.lastName = value; } } public String wholeName; private String middleInitial; public String _middleInitial { get { return middleInitial; } set { this.middleInitial = value; } } private String suffix; public String _suffix { get { return suffix; } set { this.suffix = value; } } private String gender; public String _gender { get { return gender; } set { this.gender = value; } } private int BowlerID; public int _BowlerID { get { return BowlerID; } set { this.BowlerID = value; } } private int phoneNumber; public int _PhoneNumber { get { return phoneNumber; } set { this.phoneNumber = value; } } private String emailAddress; public String _emailAddress { get { return emailAddress; } set { this.emailAddress = value; } } public string _dateOfBirth; private String streetAddress; public String _streetAddress { get { return this.streetAddress; } set { this.streetAddress = value; } } private String city; public String _city { get { return this.city; } set { this.city = value; } } private String state; public String _state { get { return this.state; } set { this.state = value; } } private bool isChosen; public bool _isChosen { get { return isChosen; } set { this.isChosen = value; } } private double pinsPerFrameAvg; public double _pinsPerFrameAvg { get { return pinsPerFrameAvg; } set { this.pinsPerFrameAvg = value; } } private int pointsWon; public int _pointsWon { get { return pointsWon; } set { this.pointsWon = value; } } private int totalPointsPossible; public int _totalPointsPossible { get { return totalPointsPossible; } set { this.totalPointsPossible = value; } } private int totalPins; public int _totalPins { get { return totalPins; } set { this.totalPins = value; } } private double bowlerAvg; public double _bowlerAvg { get { return bowlerAvg; } set { this.bowlerAvg = value; } } private int handicap; public int _handicap { get { return handicap; } set { this.handicap = value; } } public String desiredBrackets; //brackets entered in the GUI. public int maxBrackets; public int currentNumOfBrackets; private bool isAllType; //is used to denote when a player opts to be in "ALL" brackets public bool _isAllType { get { return isAllType; } set { this.isAllType = value; } } public int numOfConfirmedBrackets; //how many brackets a player has actually been entered into. public int bracketValue; //the dollar amount a bracket costs. public double refundOwed; public double moneyOwedToHouse; private List<Game> games = new List<Game>(); //default constructor public Player(String first, String last, string desiredBracks) { this._suffix = " "; ; this.BowlerID = this.GetHashCode(); this.firstName = first; this.lastName = last; this.wholeName = firstName + " " + lastName; this.desiredBrackets = desiredBracks; this.numOfConfirmedBrackets = 0; //now parse the string to get number of brackets or ALL brackets type if (this.desiredBrackets.Contains('A') || this.desiredBrackets.Contains('a')) { //set the number of brackets to the maximum integer value (2^32 - 1) this.maxBrackets = Int32.MaxValue; this._isAllType = true; } /////this is the comment else { try { this._isAllType = false; this.maxBrackets = int.Parse(this.desiredBrackets); } catch (Exception e) { MessageBox.Show("Invalid Number of Brackets Entered."); Console.Write(e.StackTrace); } } } #endregion PlayerMembers /// <summary> /// Clear the player's number of brackets /// </summary> public void ClearPlayerBrackets() { numOfConfirmedBrackets = 0; } /// <summary> /// After a game, update the points won by the player. /// </summary> /// <param name="points"></param> public void AddToPointsWon(int points) { if (points < 0) { return; } else { this._pointsWon += points; } } public void AddToTotalPins(int pins) { if (pins == 0 || pins < 0) { return; } else { this.totalPins += pins; } } //override the toString() method to return the player's first and last name separated by a space. public string ToString(string format) { if (format.Equals(lastfirst)) { //return name in the last,first format. return this.lastName + "," + this.firstName; } else if (format.Equals(firstlast)) { //return first_last format of player's name. return this.firstName + " " + this.lastName; } else { //otherwise, just return the last name. return this.lastName; } } public bool Equals(Player other) { if (Object.ReferenceEquals(other, null)) return false; if (Object.ReferenceEquals(this, other)) return true; return (wholeName.Equals(other.wholeName) && this.BowlerID.Equals(other.BowlerID)); } public int Compare(Player x, Player y) { //if this.bowlerID is less than the other's bowlerID, //return -1 if (x._BowlerID < y._BowlerID) { return -1; } //otherwise, return 1 because this ID is greater. else { return 1; } } } }
{ "content_hash": "a9a547f92ceeb7e5a3c0b73b56121e70", "timestamp": "", "source": "github", "line_count": 389, "max_line_length": 105, "avg_line_length": 24.115681233933163, "alnum_prop": 0.4221298369043812, "repo_name": "ercsoftworks/bracket_generator", "id": "adde5ad23744ea21f8960ae3986220620a0f4f3d", "size": "9381", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Player.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "12856" } ], "symlink_target": "" }
package org.sagebionetworks.web.client.widget.entity.tabs; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; public interface FilesTabView extends IsWidget { void setFileTitlebar(Widget w); void setFileTitlebarVisible(boolean visible); void setFolderTitlebar(Widget w); void setFolderTitlebarVisible(boolean visible); void setBreadcrumb(Widget w); void setFileBrowser(Widget w); void setPreview(Widget w); void setProvenance(Widget w); void setMetadata(Widget w); void setFileFolderUIVisible(boolean visible); void setWikiPage(Widget w); void setSynapseAlert(Widget w); void setProvenanceVisible(boolean visible); void setWikiPageWidgetVisible(boolean visible); void setFileBrowserVisible(boolean visible); void setPreviewVisible(boolean visible); void setModifiedCreatedBy(IsWidget modifiedCreatedBy); void setRefreshAlert(Widget w); void clearRefreshAlert(); void setDiscussionThreadListWidget(Widget widget); void setDiscussionThreadListWidgetVisible(Boolean visible); void setDiscussionText(String entityName); void showLoading(boolean value); void setFilesTab(FilesTab presenter); }
{ "content_hash": "9e982f97aa4ede32a42fb1b11c58402d", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 60, "avg_line_length": 21.85185185185185, "alnum_prop": 0.8059322033898305, "repo_name": "jay-hodgson/SynapseWebClient", "id": "8194c515e689f95d8b13f0b3ba1e8bad1782dda7", "size": "1180", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/main/java/org/sagebionetworks/web/client/widget/entity/tabs/FilesTabView.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "392172" }, { "name": "HTML", "bytes": "3785996" }, { "name": "Java", "bytes": "7951622" }, { "name": "JavaScript", "bytes": "8787050" }, { "name": "SCSS", "bytes": "69093" }, { "name": "Shell", "bytes": "1363" } ], "symlink_target": "" }
var $ = require('jquery'); var TABLET_WIDTH = 760; var MOBILE_WIDTH = 480; var utils = {}; utils._isViewport = function (vp) { return $(window).width() < vp; }; utils.isMobileViewport = function () { return this._isViewport(MOBILE_WIDTH); }; utils.isTabletViewport = function () { return this._isViewport(TABLET_WIDTH); }; module.exports = utils;
{ "content_hash": "d149595d66eb0340f44b643a5bb6de7d", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 40, "avg_line_length": 17.95, "alnum_prop": 0.6685236768802229, "repo_name": "CartoDB/cartodb", "id": "cfb1e3ec753dcabbe7eedcc225c0a9fc18fc884a", "size": "359", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/assets/javascripts/deep-insights/viewport-utils.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7083" }, { "name": "EJS", "bytes": "311401" }, { "name": "HTML", "bytes": "6933668" }, { "name": "JavaScript", "bytes": "9784580" }, { "name": "Jupyter Notebook", "bytes": "47684" }, { "name": "Makefile", "bytes": "14050" }, { "name": "Mustache", "bytes": "30410" }, { "name": "PLpgSQL", "bytes": "1233" }, { "name": "Procfile", "bytes": "189" }, { "name": "Python", "bytes": "10350" }, { "name": "Ruby", "bytes": "6995180" }, { "name": "SCSS", "bytes": "1454540" }, { "name": "Shell", "bytes": "14538" }, { "name": "Smarty", "bytes": "654458" }, { "name": "Vue", "bytes": "755091" } ], "symlink_target": "" }
<html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>PICO-8 Cartridge</title> <meta name="description" content=""> <STYLE TYPE="text/css"> <!-- canvas#canvas { width: 512px; height: 512px; } .pico8_el { float:left; width:92px; display:inline-block; margin: 1px; padding: 4px; text-align: center; color:#fff; background-color:#777; font-family : verdana; font-size: 9pt; cursor: pointer; cursor: hand; } .pico8_el a{ text-decoration: none; color:#fff; } .pico8_el:hover{ background-color:#aaa; } .pico8_el:link{ background-color:#aaa; } canvas{ image-rendering: optimizeSpeed; image-rendering: -moz-crisp-edges; image-rendering: -webkit-optimize-contrast; image-rendering: optimize-contrast; image-rendering: pixelated; -ms-interpolation-mode: nearest-neighbor; border: 0px } --> </STYLE> </head> <body bgcolor=#303030> <br><br><br> <center><div style="width:512px;"> <canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()"></canvas> <script type="text/javascript"> var canvas = document.getElementById("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; // show Emscripten environment where the canvas is // arguments are passed to PICO-8 var Module = {}; Module.canvas = canvas; /* // When pico8_buttons is defined, PICO-8 takes each int to be a live bitfield // representing the state of each player's buttons var pico8_buttons = [0, 0, 0, 0, 0, 0, 0, 0]; // max 8 players pico8_buttons[0] = 2 | 16; // example: player 0, RIGHT and Z held down // when pico8_gpio is defined, reading and writing to gpio pins will // read and write to these values var pico8_gpio = new Array(128); */ </script> <script async type="text/javascript" src="octo.js"></script> <script> // key blocker. prevent cursor keys from scrolling page while playing cart. function onKeyDown_blocker(event) { event = event || window.event; var o = document.activeElement; if (!o || o == document.body || o.tagName == "canvas") { if ([32, 37, 38, 39, 40].indexOf(event.keyCode) > -1) { if (event.preventDefault) event.preventDefault(); } } } document.addEventListener('keydown', onKeyDown_blocker, false); </script> <br> <div class=pico8_el onclick="Module.pico8Reset();"> <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAaklEQVR4Ae2dOwoAMQhE15A+rfc/3bZ7AlMnQfywCkKsfcgMM9ZP+QHtIn0vLeBAFduiFdQ/0DmvtR5LXJ6CPSXe2ZXcFNlTxFbemKrbZPs35XogeS9xeQr+anT6LzoOwEDwZJ7jwhXUnwkTTiDQ2Ja34AAAABB0RVh0TG9kZVBORwAyMDExMDIyMeNZtsEAAAAASUVORK5CYII=" alt="Reset" width=12 height= 12/> Reset</div> <div class=pico8_el onclick="Module.pico8TogglePaused();"> <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAPUlEQVR4Ae3doQ0AIAxEUWABLPtPh2WCq26DwFSU/JPNT166QSu/Hg86W9dwLte+diP7AwAAAAAAgD+A+jM2ZAgo84I0PgAAABB0RVh0TG9kZVBORwAyMDExMDIyMeNZtsEAAAAASUVORK5CYII=" alt="Pause" width=12 height=12/> Pause</div> <div class=pico8_el onclick="Module.requestFullScreen(true, false);"> <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAaklEQVR4Ae2dsQ1AIQhExfze1v2ns3UCrfgFhmgUUAoGgHscp21wX9BqaZoDojbB96OkDJKNcTN2BHTyYNYmoT2BlPL7BKgcPfHjAVXKKadkHOn9K1r16N0czN6a95N8mnA7Aq2fTZ3Af3UKmCSMazL8HwAAABB0RVh0TG9kZVBORwAyMDExMDIyMeNZtsEAAAAASUVORK5CYII=" alt="Fullscreen" width=12 height=12/> Fullscreen</div> <div class=pico8_el onclick="Module.pico8ToggleSound();"> <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAXklEQVR4Ae2doQ4AIQxD4YLH8v9fh+ULhjpxxSwLg2uyapr1JRu1iV5Z+1BGl4+xNpX38SYo2uRvYiT5LwEmt+ocgXVLrhPEgBiw8Q5w7/kueSkK+D2tJO4E/I3GrwkqQCBabEj/4QAAABB0RVh0TG9kZVBORwAyMDExMDIyMeNZtsEAAAAASUVORK5CYII=" alt="Toggle Sound" width=12 height=12/> Sound</div> <div class=pico8_el ><a target="_new" href="http://www.lexaloffle.com/bbs/?cat=7&sub=2"> <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAAlElEQVR4Ae2dMQ5FQBCGh6jcwAkkateg3DiAa+iQUGqVKi95FQfAJRQOoHeBUf8JyQqKjZ1uMzuz2e/LTE3KhyF7kSlgLOykas23f6D+A9Yp84aAOYU15pcJnfji0Il2ID8HzC4y38ZrnfIBGxeRoR3c3EWrACdsV5BOsx7OSRnrOXh4F5HzA6bevwUn8wlz7eCDsQM99B3ks0s/4QAAABB0RVh0TG9kZVBORwAyMDExMDIyMeNZtsEAAAAASUVORK5CYII=" alt="More Carts" width=12 height=12/> Carts</a></div> <br> </div></center> <br><br> </body></html>
{ "content_hash": "036885e1326cba03d33bcce190a952c0", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 384, "avg_line_length": 31.886524822695037, "alnum_prop": 0.7473309608540926, "repo_name": "jcupitt/pico8", "id": "89cbd6e637f952ff3e27412d0e1574ed127accca", "size": "4498", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "octo/octo.html", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "102943" } ], "symlink_target": "" }
package org.gwtproject.dom.builder.shared; /** HTML-based implementation of {@link LIBuilder}. */ public class HtmlLIBuilder extends HtmlElementBuilderBase<LIBuilder> implements LIBuilder { HtmlLIBuilder(HtmlBuilderImpl delegate) { super(delegate); } }
{ "content_hash": "39db911037041b042a375905602b1eaf", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 91, "avg_line_length": 26.4, "alnum_prop": 0.7727272727272727, "repo_name": "gwtproject/gwt-dom", "id": "55d41ce0fb6936ded896540cdc50f13ddffa493f", "size": "873", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gwt-dom/src/main/java/org/gwtproject/dom/builder/shared/HtmlLIBuilder.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1309271" }, { "name": "JavaScript", "bytes": "2163" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" href="http://www.petercorke.com/RVC/common/toolboxhelp.css"> <title>M-File Help: zcross</title> </head> <body> <table border="0" cellspacing="0" width="100%"> <tr class="subheader"> <td class="headertitle">M-File Help: zcross</td> <td class="subheader-left"><a href="matlab:open zcross">View code for zcross</a></td> </tr> </table> <h1>zcross</h1><p><span class="helptopic">Zero-crossing detector</span></p><p> <strong>iz</strong> = <span style="color:red">zcross</span>(<strong>im</strong>) is a binary image with pixels set where the corresponding pixels in the signed image <strong>im</strong> have a zero crossing, a positive pixel adjacent to a negative pixel. </p> <h2>Notes</h2> <ul> <li>Can be used in association with a Lapalacian of Gaussian image to determine edges.</li> </ul> <h2>See also</h2> <p> <a href="ilog.html">ilog</a></p> <hr> <table border="0" width="100%" cellpadding="0" cellspacing="0"> <tr class="subheader" valign="top"><td>&nbsp;</td></tr></table> <p class="copy">&copy; 1990-2014 Peter Corke.</p> </body></html>
{ "content_hash": "8819e2ae08ab83f2ceea928b2952611a", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 138, "avg_line_length": 36.18181818181818, "alnum_prop": 0.669179229480737, "repo_name": "sgabello1/calibration", "id": "6f778d054c3b4e1c509a97c718bfec643fcbb4c6", "size": "1194", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vision/info/html/zcross.html", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "144077" }, { "name": "HTML", "bytes": "1502260" }, { "name": "M", "bytes": "129" }, { "name": "Makefile", "bytes": "1997" }, { "name": "Matlab", "bytes": "1501081" }, { "name": "Objective-C", "bytes": "545" }, { "name": "Objective-C++", "bytes": "18721" } ], "symlink_target": "" }
const t = require('@babel/types') const { IDENTIFIER_STYLE, INTERNAL_GET_STYLE, VIRTUAL_HOST_STYLE } = require('../../../constants') const { getCode, hyphenate, isRootElement } = require('../../../util') const getMemberExpr = require('../member-expr') const REGEX_PX = /(:|\s|\(|\/)[+-]?\d+(\.\d+)?u?px/g const REGEX_UPX = /(:|\s|\(|\/)[+-]?\d+(\.\d+)?upx/g function processStaticStyleUnit (styleStr, state) { if (typeof styleStr === 'string') { let matches = styleStr.match(REGEX_UPX) if (matches && matches.length) { matches.forEach(function (match) { styleStr = styleStr.replace(match, match.substr(0, match.length - 3) + 'rpx') }) } // TODO 不应该再支持 px 转 rpx if (state.options.transformPx) { // 需要转换 px matches = styleStr.match(REGEX_PX) if (matches && matches.length) { matches.forEach(function (match) { styleStr = styleStr.replace(match, match.substr(0, match.length - 2) + 'rpx') }) } } } return styleStr } function getStaticStyleStringLiteral (staticStylePath, state) { const staticStyle = staticStylePath.node.value.properties .map(property => { return `${property.key.value}:${property.value.value}` }) .join(';') const staticStyleStr = processStaticStyleUnit(staticStyle, state).trim() return t.stringLiteral(staticStyleStr + (!staticStyleStr.endsWith(';') ? ';' : '')) } function processStaticStyle (binaryExpressions, staticStylePath, state) { let binaryExpression binaryExpressions.forEach(binaryExpr => { if (!binaryExpression) { if (staticStylePath) { binaryExpression = t.binaryExpression( '+', getStaticStyleStringLiteral(staticStylePath, state), binaryExpr ) staticStylePath.remove() } else { binaryExpression = binaryExpr } } else { binaryExpression = t.binaryExpression( '+', binaryExpression, binaryExpr ) } }) return binaryExpression } function processStyleObjectExpression (styleValuePath) { const binaryExpressions = [] const propertyPaths = styleValuePath.get('properties') propertyPaths.forEach(propertyPath => { const key = propertyPath.node.key binaryExpressions.push( t.binaryExpression( '+', t.binaryExpression( '+', t.stringLiteral(hyphenate(key.name || key.value) + ':'), t.parenthesizedExpression(propertyPath.node.value) ), t.stringLiteral(';') ) ) }) return binaryExpressions } function processStyleArrayExpression (elementPaths) { let binaryExpressions = [] elementPaths.forEach(elementPath => { binaryExpressions = binaryExpressions.concat(processStyleObjectExpression(elementPath)) }) return binaryExpressions } function generateGetStyle (stylePath, styleValuePath, staticStylePath, state) { const args = [stylePath.node.value] if (staticStylePath) { args.push(staticStylePath.node.value) staticStylePath.remove() } styleValuePath.replaceWith( getMemberExpr( stylePath, IDENTIFIER_STYLE, t.callExpression(t.identifier(INTERNAL_GET_STYLE), args), state ) ) } module.exports = function processStyle (paths, path, state) { const stylePath = paths.style const staticStylePath = paths.staticStyle const mergeVirtualHostAttributes = state.options.mergeVirtualHostAttributes if (stylePath) { const styleValuePath = stylePath.get('value') if (styleValuePath.isObjectExpression()) { styleValuePath.replaceWith( processStaticStyle( processStyleObjectExpression(styleValuePath), staticStylePath, state ) ) } else if (styleValuePath.isArrayExpression()) { // array const elementPaths = styleValuePath.get('elements') const dynamicStyle = elementPaths.find(elementPath => !elementPath.isObjectExpression()) if (dynamicStyle) { generateGetStyle(stylePath, styleValuePath, staticStylePath, state) } else { styleValuePath.replaceWith( processStaticStyle( processStyleArrayExpression(elementPaths), staticStylePath, state ) ) } } else if ( styleValuePath.isStringLiteral() || // :style="'background:red'" styleValuePath.isIdentifier() || // TODO 需要优化到下一个条件,:style="styleObject" styleValuePath.isMemberExpression() || // TODO 需要优化到下一个条件,:style="item.styleObject" styleValuePath.isConditionalExpression() || styleValuePath.isLogicalExpression() || styleValuePath.isBinaryExpression() ) { // 理论上 ConditionalExpression,LogicalExpression 可能存在 styleObject,应该__get_style,还是先不考虑这种情况吧 // ConditionalExpression :style="index === currentIndex ? activeStyle : itemStyle" // BinaryExpression :style="'m-content-head-'+message.user" styleValuePath.replaceWith( processStaticStyle( [t.parenthesizedExpression(styleValuePath.node)], staticStylePath, state ) ) } else if ( styleValuePath.isIdentifier() || styleValuePath.isMemberExpression() ) { // TODO 目前先不考虑 classObject,styleObject // generateGetStyle(stylePath, styleValuePath, staticStylePath, state) } else { state.errors.add(`:style 不支持 ${getCode(styleValuePath.node)} 语法`) } if (mergeVirtualHostAttributes && isRootElement(path.parentPath)) { styleValuePath.replaceWith(t.binaryExpression('+', styleValuePath.node, t.identifier(VIRTUAL_HOST_STYLE))) } } else if (staticStylePath) { if (mergeVirtualHostAttributes && isRootElement(path.parentPath)) { const styleNode = processStaticStyle([t.identifier(VIRTUAL_HOST_STYLE)], staticStylePath, state) const property = t.objectProperty(t.identifier('style'), styleNode) path.node.properties.push(property) return [] } staticStylePath.get('value').replaceWith(getStaticStyleStringLiteral(staticStylePath, state)) } else { if (mergeVirtualHostAttributes && isRootElement(path.parentPath)) { const property = t.objectProperty(t.identifier('style'), t.identifier(VIRTUAL_HOST_STYLE)) path.node.properties.push(property) } } return [] }
{ "content_hash": "8509371d679316911846919906b20bac", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 112, "avg_line_length": 33.48969072164948, "alnum_prop": 0.6446052024011082, "repo_name": "dcloudio/uni-app", "id": "657e8795343ca87638cbad3ad58495e2dbecdd65", "size": "6629", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "packages/uni-template-compiler/lib/script/traverse/data/style.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "53384" }, { "name": "HTML", "bytes": "375160" }, { "name": "JavaScript", "bytes": "3523088" }, { "name": "TypeScript", "bytes": "41997" }, { "name": "Vue", "bytes": "493381" } ], "symlink_target": "" }
#include "config.h" #include "debug.h" #include "dict.h" #include "hash.h" #include <sys/types.h> #include <assert.h> #include <stdint.h> #include <stdlib.h> #include <string.h> struct _p11_dict { p11_dict_hasher hash_func; p11_dict_equals equal_func; p11_destroyer key_destroy_func; p11_destroyer value_destroy_func; struct _p11_dictbucket **buckets; unsigned int num_items; unsigned int num_buckets; }; typedef struct _p11_dictbucket { void *key; unsigned int hashed; void *value; struct _p11_dictbucket *next; } dictbucket; static dictbucket * next_entry (p11_dictiter *iter) { dictbucket *bucket = iter->next; while (!bucket) { if (iter->index >= iter->dict->num_buckets) return NULL; bucket = iter->dict->buckets[iter->index++]; } iter->next = bucket->next; return bucket; } bool p11_dict_next (p11_dictiter *iter, void **key, void **value) { dictbucket *bucket = next_entry (iter); if (bucket == NULL) return false; if (key) *key = bucket->key; if (value) *value = bucket->value; return true; } void p11_dict_iterate (p11_dict *dict, p11_dictiter *iter) { iter->dict = dict; iter->index = 0; iter->next = NULL; } static dictbucket ** lookup_or_create_bucket (p11_dict *dict, const void *key, bool create) { dictbucket **bucketp; unsigned int hash; /* Perform the hashing */ hash = dict->hash_func (key); /* scan linked list */ for (bucketp = &dict->buckets[hash % dict->num_buckets]; *bucketp != NULL; bucketp = &(*bucketp)->next) { if((*bucketp)->hashed == hash && dict->equal_func ((*bucketp)->key, key)) break; } if ((*bucketp) != NULL || !create) return bucketp; /* add a new entry for non-NULL val */ (*bucketp) = calloc (sizeof (dictbucket), 1); if (*bucketp != NULL) { (*bucketp)->key = (void*)key; (*bucketp)->hashed = hash; dict->num_items++; } return bucketp; } void * p11_dict_get (p11_dict *dict, const void *key) { dictbucket **bucketp; bucketp = lookup_or_create_bucket (dict, key, false); if (bucketp && *bucketp) return (void*)((*bucketp)->value); else return NULL; } bool p11_dict_set (p11_dict *dict, void *key, void *val) { dictbucket **bucketp; p11_dictiter iter; dictbucket *bucket; dictbucket **new_buckets; unsigned int num_buckets; bucketp = lookup_or_create_bucket (dict, key, true); if(bucketp && *bucketp) { /* Destroy the previous key */ if ((*bucketp)->key && (*bucketp)->key != key && dict->key_destroy_func) dict->key_destroy_func ((*bucketp)->key); /* Destroy the previous value */ if ((*bucketp)->value && (*bucketp)->value != val && dict->value_destroy_func) dict->value_destroy_func ((*bucketp)->value); /* replace entry */ (*bucketp)->key = key; (*bucketp)->value = val; /* check that the collision rate isn't too high */ if (dict->num_items > dict->num_buckets) { num_buckets = dict->num_buckets * 2 + 1; new_buckets = (dictbucket **)calloc (sizeof (dictbucket *), num_buckets); /* Ignore failures, maybe we can expand later */ if(new_buckets) { p11_dict_iterate (dict, &iter); while ((bucket = next_entry (&iter)) != NULL) { unsigned int i = bucket->hashed % num_buckets; bucket->next = new_buckets[i]; new_buckets[i] = bucket; } free (dict->buckets); dict->buckets = new_buckets; dict->num_buckets = num_buckets; } } return true; } return_val_if_reached (false); } bool p11_dict_steal (p11_dict *dict, const void *key, void **stolen_key, void **stolen_value) { dictbucket **bucketp; bucketp = lookup_or_create_bucket (dict, key, false); if (bucketp && *bucketp) { dictbucket *old = *bucketp; *bucketp = (*bucketp)->next; --dict->num_items; if (stolen_key) *stolen_key = old->key; if (stolen_value) *stolen_value = old->value; free (old); return true; } return false; } bool p11_dict_remove (p11_dict *dict, const void *key) { void *old_key; void *old_value; if (!p11_dict_steal (dict, key, &old_key, &old_value)) return false; if (dict->key_destroy_func) dict->key_destroy_func (old_key); if (dict->value_destroy_func) dict->value_destroy_func (old_value); return true; } void p11_dict_clear (p11_dict *dict) { dictbucket *bucket, *next; int i; /* Free all entries in the array */ for (i = 0; i < dict->num_buckets; ++i) { bucket = dict->buckets[i]; while (bucket != NULL) { next = bucket->next; if (dict->key_destroy_func) dict->key_destroy_func (bucket->key); if (dict->value_destroy_func) dict->value_destroy_func (bucket->value); free (bucket); bucket = next; } } memset (dict->buckets, 0, dict->num_buckets * sizeof (dictbucket *)); dict->num_items = 0; } p11_dict * p11_dict_new (p11_dict_hasher hash_func, p11_dict_equals equal_func, p11_destroyer key_destroy_func, p11_destroyer value_destroy_func) { p11_dict *dict; assert (hash_func); assert (equal_func); dict = malloc (sizeof (p11_dict)); if (dict) { dict->hash_func = hash_func; dict->equal_func = equal_func; dict->key_destroy_func = key_destroy_func; dict->value_destroy_func = value_destroy_func; dict->num_buckets = 9; dict->buckets = (dictbucket **)calloc (sizeof (dictbucket *), dict->num_buckets); if (!dict->buckets) { free (dict); return NULL; } dict->num_items = 0; } return dict; } void p11_dict_free (p11_dict *dict) { dictbucket *bucket; p11_dictiter iter; if (!dict) return; p11_dict_iterate (dict, &iter); while ((bucket = next_entry (&iter)) != NULL) { if (dict->key_destroy_func) dict->key_destroy_func (bucket->key); if (dict->value_destroy_func) dict->value_destroy_func (bucket->value); free (bucket); } if (dict->buckets) free (dict->buckets); free (dict); } unsigned int p11_dict_size (p11_dict *dict) { return dict->num_items; } unsigned int p11_dict_str_hash (const void *string) { uint32_t hash; p11_hash_murmur3 (&hash, string, strlen (string), NULL); return hash; } bool p11_dict_str_equal (const void *string_one, const void *string_two) { assert (string_one); assert (string_two); return strcmp (string_one, string_two) == 0; } unsigned int p11_dict_ulongptr_hash (const void *to_ulong) { assert (to_ulong); return (unsigned int)*((unsigned long*)to_ulong); } bool p11_dict_ulongptr_equal (const void *ulong_one, const void *ulong_two) { assert (ulong_one); assert (ulong_two); return *((unsigned long*)ulong_one) == *((unsigned long*)ulong_two); } unsigned int p11_dict_intptr_hash (const void *to_int) { assert (to_int); return (unsigned int)*((int*)to_int); } bool p11_dict_intptr_equal (const void *int_one, const void *int_two) { assert (int_one); assert (int_two); return *((int*)int_one) == *((int*)int_two); } unsigned int p11_dict_direct_hash (const void *ptr) { return (unsigned int)(size_t)ptr; } bool p11_dict_direct_equal (const void *ptr_one, const void *ptr_two) { return ptr_one == ptr_two; }
{ "content_hash": "c5f4fe261c222719c5026ce043a6f582", "timestamp": "", "source": "github", "line_count": 358, "max_line_length": 83, "avg_line_length": 20.28491620111732, "alnum_prop": 0.618149270173506, "repo_name": "freedesktop-unofficial-mirror/p11-glue__p11-kit", "id": "db7b575fe13fc8acde2d84673bc031e7484034f5", "size": "8871", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "common/dict.c", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "2078006" }, { "name": "C++", "bytes": "35144" }, { "name": "Makefile", "bytes": "10769" }, { "name": "Objective-C", "bytes": "115573" }, { "name": "Shell", "bytes": "7820" } ], "symlink_target": "" }
package org.cloudfoundry.client.v3.serviceofferings; import com.fasterxml.jackson.annotation.JsonProperty; import org.cloudfoundry.Nullable; import org.cloudfoundry.client.v3.Metadata; import org.cloudfoundry.client.v3.Resource; import java.util.List; /** * Base class for responses that are service offerings */ public abstract class ServiceOffering extends Resource { /** * Whether the service offering is available */ @JsonProperty("available") public abstract Boolean getAvailable(); /** * The broker catalog */ @JsonProperty("broker_catalog") public abstract BrokerCatalog getBrokerCatalog(); /** * The description */ @JsonProperty("description") public abstract String getDescription(); /** * The documentation url */ @JsonProperty("documentation_url") public abstract String getDocumentationUrl(); /** * The metadata */ @JsonProperty("metadata") @Nullable public abstract Metadata getMetadata(); /** * The name */ @JsonProperty("name") public abstract String getName(); /** * The relationships */ @JsonProperty("relationships") @Nullable public abstract ServiceOfferingRelationships getRelationships(); /** * A list of permissions that the user would have to give the service */ @JsonProperty("requires") @Nullable public abstract List<String> getRequires(); /** * Whether or not service instances of this service offering can be shared across organizations and spaces */ @JsonProperty("shareable") public abstract Boolean getShareable(); /** * A list of tags for the service offering */ @JsonProperty("tags") @Nullable public abstract List<String> getTags(); }
{ "content_hash": "38d30ae8e82dc13d3ee78aad81873c8a", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 110, "avg_line_length": 22.506172839506174, "alnum_prop": 0.6653867251782776, "repo_name": "cloudfoundry/cf-java-client", "id": "73667f6fceb701cd683ce97aca1f21e0fe1a5569", "size": "2443", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "cloudfoundry-client/src/main/java/org/cloudfoundry/client/v3/serviceofferings/ServiceOffering.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "460" }, { "name": "HTML", "bytes": "818" }, { "name": "Java", "bytes": "7530131" }, { "name": "Shell", "bytes": "6507" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.14"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>CryptoAuthLib: Data Fields</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(initResizable); /* @license-end */</script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">CryptoAuthLib </div> <div id="projectbrief">Microchip CryptoAuthentication Library</div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.14 --> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ var searchBox = new SearchBox("searchBox", "search",false,'Search'); /* @license-end */ </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); /* @license-end */</script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ $(document).ready(function(){initNavTree('functions.html','');}); /* @license-end */ </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all struct and union fields with links to the structures/unions they belong to:</div> <h3><a id="index__"></a>- _ -</h3><ul> <li>_reserved : <a class="el" href="a00853.html#ad64c25d49d8bac111d62c92a0e552289">ATCAPacket</a> </li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.14 </li> </ul> </div> </body> </html>
{ "content_hash": "fc7ae71a61e19162facbca326307328c", "timestamp": "", "source": "github", "line_count": 107, "max_line_length": 126, "avg_line_length": 38.52336448598131, "alnum_prop": 0.6836487142163998, "repo_name": "PhillyNJ/SAMD21", "id": "75c9193850d695597751f8ca5a44b53fe680f46b", "size": "4122", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cryptoauthlib/docs/html/functions.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "5279135" }, { "name": "C++", "bytes": "115549" }, { "name": "CMake", "bytes": "2949" }, { "name": "CSS", "bytes": "34508" }, { "name": "HTML", "bytes": "7331097" }, { "name": "JavaScript", "bytes": "638479" }, { "name": "Objective-C", "bytes": "3349" }, { "name": "Python", "bytes": "192213" } ], "symlink_target": "" }
'use babel'; import Angular2ComponentGenerator from '../lib/angular2-component-generator'; // Use the command `window:run-package-specs` (cmd-alt-ctrl-p) to run specs. // // To run a specific `it` or `describe` block add an `f` to the front (e.g. `fit` // or `fdescribe`). Remove the `f` to unfocus the block. describe('Angular2ComponentGenerator', () => { let workspaceElement, activationPromise; beforeEach(() => { workspaceElement = atom.views.getView(atom.workspace); activationPromise = atom.packages.activatePackage('angular2-component-generator'); }); describe('when the angular2-component-generator:toggle event is triggered', () => { it('hides and shows the modal panel', () => { // Before the activation event the view is not on the DOM, and no panel // has been created expect(workspaceElement.querySelector('.angular2-component-generator')).not.toExist(); // This is an activation event, triggering it will cause the package to be // activated. atom.commands.dispatch(workspaceElement, 'angular2-component-generator:toggle'); waitsForPromise(() => { return activationPromise; }); runs(() => { expect(workspaceElement.querySelector('.angular2-component-generator')).toExist(); let angular2ComponentGeneratorElement = workspaceElement.querySelector('.angular2-component-generator'); expect(angular2ComponentGeneratorElement).toExist(); let angular2ComponentGeneratorPanel = atom.workspace.panelForItem(angular2ComponentGeneratorElement); expect(angular2ComponentGeneratorPanel.isVisible()).toBe(true); atom.commands.dispatch(workspaceElement, 'angular2-component-generator:toggle'); expect(angular2ComponentGeneratorPanel.isVisible()).toBe(false); }); }); it('hides and shows the view', () => { // This test shows you an integration test testing at the view level. // Attaching the workspaceElement to the DOM is required to allow the // `toBeVisible()` matchers to work. Anything testing visibility or focus // requires that the workspaceElement is on the DOM. Tests that attach the // workspaceElement to the DOM are generally slower than those off DOM. jasmine.attachToDOM(workspaceElement); expect(workspaceElement.querySelector('.angular2-component-generator')).not.toExist(); // This is an activation event, triggering it causes the package to be // activated. atom.commands.dispatch(workspaceElement, 'angular2-component-generator:toggle'); waitsForPromise(() => { return activationPromise; }); runs(() => { // Now we can test for view visibility let angular2ComponentGeneratorElement = workspaceElement.querySelector('.angular2-component-generator'); expect(angular2ComponentGeneratorElement).toBeVisible(); atom.commands.dispatch(workspaceElement, 'angular2-component-generator:toggle'); expect(angular2ComponentGeneratorElement).not.toBeVisible(); }); }); }); });
{ "content_hash": "a4bc944718e27adc4bce4d1a7753e620", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 112, "avg_line_length": 42.32876712328767, "alnum_prop": 0.7019417475728156, "repo_name": "dbaikov/atom-angular2-component-generator", "id": "b7cb7bf69e5ddc8b33d51eeded3c7a3e6b1cdeb3", "size": "3090", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/angular2-component-generator-spec.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "311" }, { "name": "JavaScript", "bytes": "4593" }, { "name": "TypeScript", "bytes": "4583" } ], "symlink_target": "" }
define([ 'dojo/_base/declare', "dojo/_base/lang", 'dojo/on', 'dojo/_base/html', 'dijit/_WidgetBase', 'dijit/_TemplatedMixin', 'dijit/_WidgetsInTemplateMixin', 'dojo/text!./AlignSelector.html', "dijit/form/NumberSpinner", 'jimu/dijit/CheckBox' ], function(declare, lang, on, html, _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, template) { return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], { templateString: template, nls: null, // _size: null, // _isCustom: false, postCreate: function() { this.inherited(arguments); this._initAlign(); }, startup: function() { this.inherited(arguments); }, _initAlign: function() { this.own(on(this.top, 'click', lang.hitch(this, function() { this._cleanSelected(); html.addClass(this.top, "selected"); }))); this.own(on(this.middle, 'click', lang.hitch(this, function() { this._cleanSelected(); html.addClass(this.middle, "selected"); }))); }, _cleanSelected: function() { html.removeClass(this.top, 'selected'); html.removeClass(this.middle, 'selected'); }, getValue: function() { var val; if (html.hasClass(this.top, 'selected')) { val = "top"; } else if (html.hasClass(this.middle, 'selected')) { val = "middle"; } return val; }, setValue: function(align) { this._cleanSelected(); if (typeof align === "string") { if (align === "top") { html.addClass(this.top, "selected"); } else if (align === "middle") { html.addClass(this.middle, "selected"); } } } }); });
{ "content_hash": "b6b3da04c0f78e2c76f11bcebcacc988", "timestamp": "", "source": "github", "line_count": 64, "max_line_length": 77, "avg_line_length": 28.78125, "alnum_prop": 0.5347448425624322, "repo_name": "cmndrbensisko/LocalLayer", "id": "02ee965214b9428287d6e3216409b991474396ed", "size": "2606", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "samples/wazeViewer/widgets/Splash/setting/AlignSelector.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "28288" }, { "name": "HTML", "bytes": "170060" }, { "name": "JavaScript", "bytes": "478816" } ], "symlink_target": "" }
package br.edu.senac.kkcommerce.service; import br.edu.senac.kkcommerce.dao.MarcaDao; import br.edu.senac.kkcommerce.model.Marca; import java.util.List; /** * * @author while true */ public class MarcaService extends ServiceBase { public MarcaService() { super(new MarcaDao()); } public List<Marca> listar() throws Exception { return dao.listar(); } public Marca buscar(int id) throws Exception { return (Marca) dao.getById(id); } }
{ "content_hash": "6e8360bbecaf8221161670bc29463d85", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 50, "avg_line_length": 19.76, "alnum_prop": 0.659919028340081, "repo_name": "Maltasga/pi4-while-true", "id": "8efd95a97bf6a22cbcbd46df22680d550e300ffb", "size": "494", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kkcommerce/src/main/java/br/edu/senac/kkcommerce/service/MarcaService.java", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "9988" }, { "name": "CSS", "bytes": "12174" }, { "name": "HTML", "bytes": "170204" }, { "name": "Java", "bytes": "203501" }, { "name": "JavaScript", "bytes": "6611" }, { "name": "Shell", "bytes": "12936" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "5accac0495f1dfb0fd4694bcf3617c0c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "a452cd25ed9575452a51422b93dcd54d9d440ddc", "size": "185", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Chlorophyta/Bryopsidophyceae/Bryopsidales/Codiaceae/Codium/Codium cranwelliae/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
.. [COMMENT] This file is a placeholder and will be replaced Index ======
{ "content_hash": "e06b0c42f7af02f8fad9cc0dfbb5f63f", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 60, "avg_line_length": 15.4, "alnum_prop": 0.6623376623376623, "repo_name": "openfheorg/openfhe-development", "id": "57e08876ebb1d65687e4b4e4dca0f492cf80ce5f", "size": "77", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "docs/genindex.rst", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "74777" }, { "name": "C++", "bytes": "5404712" }, { "name": "CMake", "bytes": "47675" }, { "name": "Dockerfile", "bytes": "1338" }, { "name": "Makefile", "bytes": "177" }, { "name": "Shell", "bytes": "6324" } ], "symlink_target": "" }
this['@dna/playerInfo'] = function() { return new $.sys.Frame({ name: 'playerInfo', evo: function(scene, dt) { }, txt: function(ctx, text1, text2){ ctx.font = '32px kenney, impact, sans-serif'; ctx.fillStyle="#202020"; ctx.fillText(text1, 12, 37); ctx.fillStyle="#E08040"; ctx.fillText(text1, 10, 35); ctx.fillStyle="#202020"; ctx.fillText(text2, 12, 72); ctx.fillStyle="#6080D0"; ctx.fillText(text2, 10, 70); }, addVar: function(opts){ let v = opts.value === undefined ? this._.selectOne(opts.path): opts.value; if (opts.number) { v = v || 0; } return opts.caption + v + " "; }, draw: function(ctx) { let spawned = this._.selectOneNumber(constants.path.DUDES_SPAWNED_COUNT); let dead = this._.selectOneNumber(constants.path.DUDES_DEAD); let goal = this._.selectOneNumber(constants.path.GOAL) let escaped = this._.selectOneNumber(constants.path.DUDES_ESCAPED) let level = this._.selectOne(constants.path.PLAYER_LEVEL) let levelName = this._.selectOne(constants.path.LEVEL_NAME) let txt1 = "Level " + level + ": " + levelName let txt2 = "" //txt += this.addVar({caption: "Alive:", value: (spawned - dead) + "/" + spawned}); txt2 += this.addVar({caption: "Goal: ", value: escaped + "/" + goal }); txt2 += this.addVar({caption: " Walking: ", value: spawned - escaped - dead }); this.txt(ctx, txt1, txt2); } }) }
{ "content_hash": "6d61984617fe46ee937c61a116f0aae4", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 95, "avg_line_length": 34.04255319148936, "alnum_prop": 0.554375, "repo_name": "invider/mark-to-escape", "id": "d06ce5a0fbd48d4220ca153a31155923982a418d", "size": "1600", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/playerInfo.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1417" }, { "name": "JavaScript", "bytes": "83188" }, { "name": "OCaml", "bytes": "165" }, { "name": "Shell", "bytes": "216" } ], "symlink_target": "" }
/* /ns/b-include-import.css */
{ "content_hash": "133810080084fd0c0ea080803a99d096", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 30, "avg_line_length": 30, "alnum_prop": 0.6333333333333333, "repo_name": "fateevv/basisjs-tools-build", "id": "eb6f2ba0491eef3952fcc8810d598b84ca3a0ed7", "size": "30", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "test/extract/env/basis1.5/app/ns/b-include-import.css", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "263" }, { "name": "HTML", "bytes": "183" }, { "name": "JavaScript", "bytes": "616021" } ], "symlink_target": "" }
// // NSURLDemoViewController.m // JKCategories (https://github.com/shaojiankui/JKCategories) // // Created by Jakey on 15/3/29. // Copyright (c) 2015年 www.skyfox.org. All rights reserved. // #import "NSURLDemoViewController.h" @interface NSURLDemoViewController () @end @implementation NSURLDemoViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end
{ "content_hash": "f937fef3b18dd962f91fe7087ae6b950", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 102, "avg_line_length": 24.81081081081081, "alnum_prop": 0.7363834422657952, "repo_name": "devtofu/iOS-Categories", "id": "f2924d087232a84cc01afefdfc5f4418782d1e9a", "size": "920", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "JKCategories-Demo/Demos/Foundation/NSURL/NSURLDemoViewController.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1613030" }, { "name": "Ruby", "bytes": "1117" } ], "symlink_target": "" }
namespace content { class WebUI; } // namespace content namespace ash { class AccessibilityFeatures; class ScanningAppDelegate; // The WebUI for chrome://scanning. class ScanningUI : public ui::MojoWebUIController { public: using BindScanServiceCallback = base::RepeatingCallback<void( mojo::PendingReceiver<scanning::mojom::ScanService>)>; // |callback| should bind the pending receiver to an implementation of // ash::scanning::mojom::ScanService. ScanningUI(content::WebUI* web_ui, BindScanServiceCallback callback, std::unique_ptr<ScanningAppDelegate> scanning_app_delegate); ~ScanningUI() override; ScanningUI(const ScanningUI&) = delete; ScanningUI& operator=(const ScanningUI&) = delete; // Instantiates the implementor of the ash::scanning::mojom::ScanService // Mojo interface by passing the pending receiver that will be internally // bound. void BindInterface( mojo::PendingReceiver<scanning::mojom::ScanService> pending_receiver); // Instantiates the implementor of the // ash::common::mojom::AccessibilityFeatures Mojo interface by passing the // pending receiver that will be internally bound. void BindInterface(mojo::PendingReceiver<common::mojom::AccessibilityFeatures> pending_receiver); private: const BindScanServiceCallback bind_pending_receiver_callback_; std::unique_ptr<AccessibilityFeatures> accessibility_features_; WEB_UI_CONTROLLER_TYPE_DECL(); }; } // namespace ash #endif // ASH_WEBUI_SCANNING_SCANNING_UI_H_
{ "content_hash": "f885accc90f3da71a0413fde666e8023", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 80, "avg_line_length": 31.755102040816325, "alnum_prop": 0.737146529562982, "repo_name": "nwjs/chromium.src", "id": "bbd2d21eace81a4457bc7d44d61a559ffe840a60", "size": "2107", "binary": false, "copies": "6", "ref": "refs/heads/nw70", "path": "ash/webui/scanning/scanning_ui.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
import dependency_manager import logging import mock import subprocess import unittest from battor import battor_error from battor import battor_wrapper from devil.utils import battor_device_mapping from devil.utils import find_usb_devices import serial from serial.tools import list_ports class DependencyManagerMock(object): def __init__(self, _): self._fetch_return = 'path' self._version_return = 'cbaa843' def FetchPath(self, _, *unused): del unused return self._fetch_return def FetchPathWithVersion(self, _, *unused): del unused return self._fetch_return, self._version_return class PopenMock(object): def __init__(self, *unused): pass def poll(self): pass def kill(self): pass class IsBattOrConnectedTest(unittest.TestCase): def setUp(self): # Windows monkey patches. self._serial_tools_return = [] self._comports = serial.tools.list_ports.comports serial.tools.list_ports.comports = lambda: self._serial_tools_return # Linux/Android monkey patches. self._generate_serial_map_return = {} self._generate_serial_map = battor_device_mapping.GenerateSerialMap battor_device_mapping.GenerateSerialMap = ( lambda: self._generate_serial_map_return) self._read_serial_map_file_return = {} self._read_serial_map_file = battor_device_mapping.ReadSerialMapFile battor_device_mapping.ReadSerialMapFile = ( lambda f: self._read_serial_map_file_return) self._get_bus_number_to_device_tree_map = ( find_usb_devices.GetBusNumberToDeviceTreeMap) find_usb_devices.GetBusNumberToDeviceTreeMap = lambda fast=None: {} self._get_battor_list_return = [] self._get_battor_list = battor_device_mapping.GetBattOrList battor_device_mapping.GetBattOrList = lambda x: self._get_battor_list_return def tearDown(self): serial.tools.list_ports.comports = self._comports battor_device_mapping.GenerateSerialMap = self._generate_serial_map battor_device_mapping.ReadSerialMapFile = self._read_serial_map_file find_usb_devices.GetBusNumberToDeviceTreeMap = ( self._get_bus_number_to_device_tree_map) battor_device_mapping.GetBattOrList = self._get_battor_list def forceException(self): raise NotImplementedError def testAndroidWithBattOr(self): self._generate_serial_map_return = {'abc': '123'} self.assertTrue(battor_wrapper.IsBattOrConnected('android', 'abc')) def testAndroidWithoutMatchingBattOr(self): self._generate_serial_map_return = {'notabc': 'not123'} self.assertFalse(battor_wrapper.IsBattOrConnected('android', 'abc')) def testAndroidNoDevicePassed(self): with self.assertRaises(ValueError): battor_wrapper.IsBattOrConnected('android') def testAndroidWithMapAndFile(self): device_map = {'abc': '123'} battor_device_mapping.ReadSerialMapFile = self.forceException self.assertTrue( battor_wrapper.IsBattOrConnected('android', android_device='abc', android_device_map=device_map, android_device_file='file')) def testAndroidWithMap(self): self.assertTrue( battor_wrapper.IsBattOrConnected('android', android_device='abc', android_device_map={'abc', '123'})) def testAndroidWithFile(self): self._read_serial_map_file_return = {'abc': '123'} self.assertTrue( battor_wrapper.IsBattOrConnected('android', android_device='abc', android_device_file='file')) def testLinuxWithBattOr(self): self._get_battor_list_return = ['battor'] self.assertTrue(battor_wrapper.IsBattOrConnected('linux')) def testLinuxWithoutBattOr(self): self._get_battor_list_return = [] self.assertFalse(battor_wrapper.IsBattOrConnected('linux')) def testMacWithBattOr(self): self._serial_tools_return = [('/dev/tty.usbserial-MAA', 'BattOr v3.3', '')] self.assertTrue(battor_wrapper.IsBattOrConnected('mac')) def testMacWithoutBattOr(self): self._serial_tools_return = [('/dev/tty.usbserial-MAA', 'not_one', '')] self.assertFalse(battor_wrapper.IsBattOrConnected('mac')) def testWinWithBattOr(self): self._serial_tools_return = [('COM4', 'USB Serial Port', '')] self.assertTrue(battor_wrapper.IsBattOrConnected('win')) def testWinWithoutBattOr(self): self._get_battor_list_return = [] self.assertFalse(battor_wrapper.IsBattOrConnected('win')) class BattOrWrapperTest(unittest.TestCase): def setUp(self): self._battor = None self._is_battor = True self._battor_list = ['battor1'] self._should_pass = True self._fake_map = {'battor1': 'device1'} self._fake_return_code = None self._fake_battor_return = 'Done.\n' self._get_battor_path_from_phone_serial = ( battor_device_mapping.GetBattOrPathFromPhoneSerial) self._get_bus_number_to_device_tree_map = ( find_usb_devices.GetBusNumberToDeviceTreeMap) self._dependency_manager = dependency_manager.DependencyManager self._get_battor_list = battor_device_mapping.GetBattOrList self._is_battor = battor_device_mapping.IsBattOr self._generate_serial_map = battor_device_mapping.GenerateSerialMap self._serial_tools = serial.tools.list_ports.comports battor_device_mapping.GetBattOrPathFromPhoneSerial = ( lambda x, serial_map_file=None, serial_map=None: x + '_battor') find_usb_devices.GetBusNumberToDeviceTreeMap = lambda fast=False: True dependency_manager.DependencyManager = DependencyManagerMock battor_device_mapping.GetBattOrList = lambda x: self._battor_list battor_device_mapping.IsBattOr = lambda x, y: self._is_battor battor_device_mapping.GenerateSerialMap = lambda: self._fake_map serial.tools.list_ports.comports = lambda: [('COM4', 'USB Serial Port', '')] self._subprocess_check_output_code = 0 def subprocess_check_output_mock(*unused): if self._subprocess_check_output_code != 0: raise subprocess.CalledProcessError(None, None) return 0 self._subprocess_check_output = subprocess.check_output subprocess.check_output = subprocess_check_output_mock def tearDown(self): battor_device_mapping.GetBattOrPathFromPhoneSerial = ( self._get_battor_path_from_phone_serial) find_usb_devices.GetBusNumberToDeviceTreeMap = ( self._get_bus_number_to_device_tree_map) dependency_manager.DependencyManager = self._dependency_manager battor_device_mapping.GetBattOrList = self._get_battor_list battor_device_mapping.IsBattOr = self._is_battor battor_device_mapping.GenerateSerialMap = self._generate_serial_map serial.tools.list_ports.comports = self._serial_tools subprocess.check_output = self._subprocess_check_output def _DefaultBattOrReplacements(self): battor_wrapper.DEFAULT_SHELL_CLOSE_TIMEOUT_S = .1 self._battor._StartShellImpl = lambda *unused: PopenMock() self._battor.GetShellReturnCode = lambda *unused: self._fake_return_code self._battor._SendBattOrCommandImpl = lambda x: self._fake_battor_return self._battor._StopTracingImpl = lambda *unused: (self._fake_battor_return, None) def testBadPlatform(self): with self.assertRaises(battor_error.BattOrError): self._battor = battor_wrapper.BattOrWrapper('unknown') def testInitAndroidWithBattOr(self): self._battor = battor_wrapper.BattOrWrapper('android', android_device='abc') self.assertEquals(self._battor._battor_path, 'abc_battor') def testInitAndroidWithoutBattOr(self): self._battor_list = [] self._fake_map = {} battor_device_mapping.GetBattOrPathFromPhoneSerial = ( self._get_battor_path_from_phone_serial) with self.assertRaises(battor_error.BattOrError): self._battor = battor_wrapper.BattOrWrapper('android', android_device='abc') def testInitBattOrPathIsBattOr(self): battor_path = 'battor/path/here' self._battor = battor_wrapper.BattOrWrapper( 'android', android_device='abc', battor_path=battor_path) self.assertEquals(self._battor._battor_path, battor_path) def testInitNonAndroidWithBattOr(self): self._battor = battor_wrapper.BattOrWrapper('win') self.assertEquals(self._battor._battor_path, 'COM4') def testInitNonAndroidWithMultipleBattOr(self): self._battor_list.append('battor2') with self.assertRaises(battor_error.BattOrError): self._battor = battor_wrapper.BattOrWrapper('linux') def testInitNonAndroidWithoutBattOr(self): self._battor_list = [] serial.tools.list_ports.comports = lambda: [('COM4', 'None', '')] with self.assertRaises(battor_error.BattOrError): self._battor = battor_wrapper.BattOrWrapper('win') def testStartShellPass(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() self._battor.StartShell() self.assertIsNotNone(self._battor._battor_shell) def testStartShellDoubleStart(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() self._battor.StartShell() with self.assertRaises(AssertionError): self._battor.StartShell() def testStartShellFail(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() self._battor.GetShellReturnCode = lambda *unused: 1 with self.assertRaises(AssertionError): self._battor.StartShell() def testStartTracingPass(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() self._battor.StartShell() self._battor.StartTracing() self.assertTrue(self._battor._tracing) def testStartTracingDoubleStart(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() self._battor.StartShell() self._battor.StartTracing() with self.assertRaises(AssertionError): self._battor.StartTracing() def testStartTracingCommandFails(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() self._battor._SendBattOrCommandImpl = lambda *unused: 'Fail.\n' self._battor.StartShell() with self.assertRaises(battor_error.BattOrError): self._battor.StartTracing() def testStopTracingPass(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() self._battor.StartShell() self._battor.StartTracing() self._battor.GetShellReturnCode = lambda *unused: 0 self._battor.StopTracing() self.assertFalse(self._battor._tracing) def testStopTracingNotRunning(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() with self.assertRaises(AssertionError): self._battor.StopTracing() def testFlashFirmwarePass(self): self._battor = battor_wrapper.BattOrWrapper('linux') self._DefaultBattOrReplacements() self.assertTrue(self._battor.FlashFirmware('hex_path', 'config_path')) def testFlashFirmwareFail(self): self._battor = battor_wrapper.BattOrWrapper('linux') self._DefaultBattOrReplacements() self._subprocess_check_output_code = 1 with self.assertRaises(battor_wrapper.BattOrFlashError): self._battor.FlashFirmware('hex_path', 'config_path') def testFlashFirmwareShellRunning(self): self._battor = battor_wrapper.BattOrWrapper('linux') self._DefaultBattOrReplacements() self._battor.StartShell() with self.assertRaises(AssertionError): self._battor.FlashFirmware('hex_path', 'config_path') def testGetFirmwareGitHashNotRunning(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() with self.assertRaises(AssertionError): self._battor.GetFirmwareGitHash() def testGetFirmwareGitHashPass(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() self._battor.StartShell() self._battor.GetFirmwareGitHash = lambda: 'cbaa843' self.assertTrue(isinstance(self._battor.GetFirmwareGitHash(), basestring)) def testStopShellPass(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() self._battor.StartShell() self._fake_return_code = 0 self._battor.StopShell() self.assertIsNone(self._battor._battor_shell) @mock.patch('time.sleep', mock.Mock) def testStopShellTimeOutAndKill(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() self._battor.StartShell() self._battor.StopShell() self.assertIsNone(self._battor._battor_shell) def testStopShellNotStarted(self): self._battor = battor_wrapper.BattOrWrapper('win') self._DefaultBattOrReplacements() with self.assertRaises(AssertionError): self._battor.StopShell() @mock.patch('time.sleep', mock.Mock) def testFlashBattOrSameGitHash(self): self._battor = battor_wrapper.BattOrWrapper('linux') self._DefaultBattOrReplacements() self._battor.StartShell() self._battor.GetFirmwareGitHash = lambda: 'cbaa843' dependency_manager.DependencyManager._version_return = 'cbaa843' self.assertFalse(self._battor._FlashBattOr()) @mock.patch('time.sleep', mock.Mock) def testFlashBattOrDifferentGitHash(self): self._battor = battor_wrapper.BattOrWrapper('linux') self._DefaultBattOrReplacements() self._battor.StartShell() self._battor.GetFirmwareGitHash = lambda: 'bazz732' dependency_manager.DependencyManager._version_return = 'cbaa843' self.assertTrue(self._battor._FlashBattOr()) if __name__ == '__main__': logging.getLogger().setLevel(logging.DEBUG) unittest.main(verbosity=2)
{ "content_hash": "e41fab7141cd0516d3a20b342bd83957", "timestamp": "", "source": "github", "line_count": 361, "max_line_length": 80, "avg_line_length": 38.337950138504155, "alnum_prop": 0.7119219653179191, "repo_name": "benschmaus/catapult", "id": "3e48a3362dc90775d2ad07b03770f325c351f918", "size": "14003", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "common/battor/battor/battor_wrapper_unittest.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "4902" }, { "name": "C++", "bytes": "43486" }, { "name": "CSS", "bytes": "24873" }, { "name": "Go", "bytes": "58279" }, { "name": "HTML", "bytes": "11801772" }, { "name": "JavaScript", "bytes": "518002" }, { "name": "Makefile", "bytes": "1588" }, { "name": "Python", "bytes": "6141932" }, { "name": "Shell", "bytes": "2288" } ], "symlink_target": "" }
#ifndef __itkStandardDeviationPerComponentSampleFilter_h #define __itkStandardDeviationPerComponentSampleFilter_h #include "itkProcessObject.h" #include "itkVariableSizeMatrix.h" #include "itkSimpleDataObjectDecorator.h" #include "itkNumericTraitsFixedArrayPixel.h" namespace itk { namespace Statistics { /** \class StandardDeviationPerComponentSampleFilter * \brief Calculates the covariance matrix of the target sample data. * * The filter calculates first the sample mean and use it in the covariance * calculation. The covariance is computed as follows * Let \f$\Sigma\f$ denotes covariance matrix for the sample, then: * When \f$x_{i}\f$ is \f$i\f$th component of a measurement vector * \f$\vec x\f$, \f$\mu_{i}\f$ is the \f$i\f$th componet of the \f$\vec\mu\f$, * and the \f$\sigma_{ij}\f$ is the \f$ij\f$th componet \f$\Sigma\f$, * \f$\sigma_{ij} = (x_{i} - \mu_{i})(x_{j} - \mu_{j})\f$ * * Without the plugged in mean vector, this calculator will perform * the single pass mean and covariance calculation algorithm. * * \ingroup ITK-Statistics */ template< class TSample > class ITK_EXPORT StandardDeviationPerComponentSampleFilter: public ProcessObject { public: /** Standard class typedefs. */ typedef StandardDeviationPerComponentSampleFilter Self; typedef ProcessObject Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; typedef TSample SampleType; /** Standard Macros */ itkTypeMacro(StandardDeviationPerComponentSampleFilter, ProcessObject); itkNewMacro(Self); /** Length of a measurement vector */ typedef typename TSample::MeasurementVectorSizeType MeasurementVectorSizeType; /** Measurement vector type */ typedef typename TSample::MeasurementVectorType MeasurementVectorType; typedef typename NumericTraits< MeasurementVectorType >::RealType MeasurementVectorRealType; /** Method to set/get the sample */ void SetInput(const SampleType *sample); const SampleType * GetInput() const; /** MeasurementVector is not a DataObject, we need to decorate it to push it down * a ProcessObject's pipeline */ typedef SimpleDataObjectDecorator< MeasurementVectorRealType > MeasurementVectorRealDecoratedType; typedef MeasurementVectorRealDecoratedType OutputType; /** Return the standard deviation vector */ const MeasurementVectorRealType GetStandardDeviationPerComponent() const; const MeasurementVectorRealDecoratedType * GetStandardDeviationPerComponentOutput() const; /** Return the mean vector */ const MeasurementVectorRealType GetMeanPerComponent() const; const MeasurementVectorRealDecoratedType * GetMeanPerComponentOutput() const; protected: StandardDeviationPerComponentSampleFilter(const Self &); //purposely not // implemented void operator=(const Self &); //purposely not // implemented StandardDeviationPerComponentSampleFilter(); virtual ~StandardDeviationPerComponentSampleFilter(); void PrintSelf(std::ostream & os, Indent indent) const; /** DataObject pointer */ typedef DataObject::Pointer DataObjectPointer; virtual DataObjectPointer MakeOutput(unsigned int idx); void GenerateData(); MeasurementVectorSizeType GetMeasurementVectorSize() const; private: }; // end of class } // end of namespace Statistics } // end of namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkStandardDeviationPerComponentSampleFilter.txx" #endif #endif
{ "content_hash": "2975a0cddff7ca8541167f9ceb017cf1", "timestamp": "", "source": "github", "line_count": 104, "max_line_length": 101, "avg_line_length": 35.52884615384615, "alnum_prop": 0.7193504736129905, "repo_name": "cpatrick/ITK-RemoteIO", "id": "e3288d153d070304d32b2ac234f0c348904e875e", "size": "4470", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Modules/Numerics/Statistics/include/itkStandardDeviationPerComponentSampleFilter.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "26042085" }, { "name": "C#", "bytes": "1714" }, { "name": "C++", "bytes": "29021501" }, { "name": "FORTRAN", "bytes": "2241251" }, { "name": "Java", "bytes": "60339" }, { "name": "Objective-C", "bytes": "6591" }, { "name": "Perl", "bytes": "17899" }, { "name": "Python", "bytes": "896705" }, { "name": "Ruby", "bytes": "296" }, { "name": "Shell", "bytes": "208330" }, { "name": "Tcl", "bytes": "133660" } ], "symlink_target": "" }
dofile 'interpreters/luabase.lua' return MakeLuaInterpreter()
{ "content_hash": "63197a9a854cb56df0163abb451269e6", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 33, "avg_line_length": 31, "alnum_prop": 0.8387096774193549, "repo_name": "LuaExtend/LuaExtend", "id": "49af2790fd452bcdd3380d379b0d476da60615d0", "size": "62", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tools/ZeroBraneStudio/interpreters/luadeb.lua", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1417" }, { "name": "C", "bytes": "2010156" }, { "name": "C++", "bytes": "411067" }, { "name": "CMake", "bytes": "31973" }, { "name": "CSS", "bytes": "2454" }, { "name": "HTML", "bytes": "412730" }, { "name": "Java", "bytes": "177782" }, { "name": "Lua", "bytes": "4733282" }, { "name": "Makefile", "bytes": "59247" }, { "name": "Objective-C", "bytes": "40148" }, { "name": "Objective-C++", "bytes": "25822" }, { "name": "Perl", "bytes": "1689" }, { "name": "Roff", "bytes": "34641" }, { "name": "Shell", "bytes": "9749" }, { "name": "XSLT", "bytes": "12288" } ], "symlink_target": "" }
#ifndef TREE_MUDFLAP_H #define TREE_MUDFLAP_H /* Instrumentation. */ extern void mudflap_init (void); extern void mudflap_enqueue_decl (tree); extern void mudflap_enqueue_constant (tree); extern void mudflap_finish_file (void); /* Tree node marking. */ extern int mf_marked_p (tree); extern tree mf_mark (tree); #endif /* TREE_MUDFLAP_H */
{ "content_hash": "e3ec682d6aed08778baff5f999e2b22a", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 44, "avg_line_length": 21.6875, "alnum_prop": 0.7175792507204611, "repo_name": "the-linix-project/linix-kernel-source", "id": "b8779fe073b1b9ba44b22a7e7b2cab144980633c", "size": "1162", "binary": false, "copies": "53", "ref": "refs/heads/master", "path": "gccsrc/gcc-4.7.2/gcc/tree-mudflap.h", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Ada", "bytes": "38139979" }, { "name": "Assembly", "bytes": "3723477" }, { "name": "Awk", "bytes": "83739" }, { "name": "C", "bytes": "103607293" }, { "name": "C#", "bytes": "55726" }, { "name": "C++", "bytes": "38577421" }, { "name": "CLIPS", "bytes": "6933" }, { "name": "CSS", "bytes": "32588" }, { "name": "Emacs Lisp", "bytes": "13451" }, { "name": "FORTRAN", "bytes": "4294984" }, { "name": "GAP", "bytes": "13089" }, { "name": "Go", "bytes": "11277335" }, { "name": "Haskell", "bytes": "2415" }, { "name": "Java", "bytes": "45298678" }, { "name": "JavaScript", "bytes": "6265" }, { "name": "Matlab", "bytes": "56" }, { "name": "OCaml", "bytes": "148372" }, { "name": "Objective-C", "bytes": "995127" }, { "name": "Objective-C++", "bytes": "436045" }, { "name": "PHP", "bytes": "12361" }, { "name": "Pascal", "bytes": "40318" }, { "name": "Perl", "bytes": "358808" }, { "name": "Python", "bytes": "60178" }, { "name": "SAS", "bytes": "1711" }, { "name": "Scilab", "bytes": "258457" }, { "name": "Shell", "bytes": "2610907" }, { "name": "Tcl", "bytes": "17983" }, { "name": "TeX", "bytes": "1455571" }, { "name": "XSLT", "bytes": "156419" } ], "symlink_target": "" }
#ifndef BaseButtonInputType_h #define BaseButtonInputType_h #include "core/html/forms/BaseClickableWithKeyInputType.h" namespace blink { // Base of button, file, image, reset, and submit types. class BaseButtonInputType : public BaseClickableWithKeyInputType { protected: BaseButtonInputType(HTMLInputElement& element) : BaseClickableWithKeyInputType(element) { } void valueAttributeChanged() override; void createShadowSubtree() override; private: bool shouldSaveAndRestoreFormControlState() const override; bool appendFormData(FormDataList&, bool) const override; LayoutObject* createLayoutObject(const ComputedStyle&) const override; bool storesValueSeparateFromAttribute() override; void setValue(const String&, bool, TextFieldEventBehavior) override; }; } // namespace blink #endif // BaseButtonInputType_h
{ "content_hash": "b5efa91eea32862c7dabeaebb4751fa0", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 95, "avg_line_length": 31.555555555555557, "alnum_prop": 0.7910798122065728, "repo_name": "Bysmyyr/blink-crosswalk", "id": "e0dc1459386c66ac298f17454e80909e76daa8fc", "size": "2414", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "Source/core/html/forms/BaseButtonInputType.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "1835" }, { "name": "Assembly", "bytes": "14768" }, { "name": "Batchfile", "bytes": "35" }, { "name": "C", "bytes": "129060" }, { "name": "C++", "bytes": "44967078" }, { "name": "CSS", "bytes": "570685" }, { "name": "CoffeeScript", "bytes": "163" }, { "name": "GLSL", "bytes": "11578" }, { "name": "Groff", "bytes": "28067" }, { "name": "HTML", "bytes": "58737983" }, { "name": "Java", "bytes": "109391" }, { "name": "JavaScript", "bytes": "24397188" }, { "name": "Objective-C", "bytes": "48694" }, { "name": "Objective-C++", "bytes": "293932" }, { "name": "PHP", "bytes": "194683" }, { "name": "Perl", "bytes": "585390" }, { "name": "Python", "bytes": "3817839" }, { "name": "Ruby", "bytes": "141818" }, { "name": "Shell", "bytes": "10037" }, { "name": "XSLT", "bytes": "50203" }, { "name": "Yacc", "bytes": "61184" } ], "symlink_target": "" }
An event store on top of RethinkDB. ## Installation **Important:** Please not that this is alpha software and currently a _work in progress_. API may change in the next releases. Nevertheless, I encourage you to give it a test drive and provide feedback how you like it :) ```sh npm i --save eventastic ``` or if you are using `yarn`: ```sh yarn add eventastic ``` ## Usage ```typescript import createEventStore, { createEvent } from "eventastic"; const app = async () => { const es = await createEventStore({ host: 'localhost', port: 32793 }); const user: IUser = { username: "akoenig", firstname: "André", lastname: "König", email: "andre.koenig@posteo.de", password: "e3b0c4....", salt: "852b85...." }; const UserRegisteredEvent = createEvent<IUser>('UserRegisteredEvent'); await es.commit(UserRegisteredEvent(user)); }; ``` ### Changefeed `eventastic` comes with a changefeed implementation which allows further processing of the event after it has been persisted (e. g. publish to message broker, etc.). ```typescript import createEventStore, { createEvent } from "eventastic"; const app = async() => { const es = await createEventStore({ host: 'localhost', port: 32793 }); await es.changes((err: Error, event: IEvent<any>) => { if (err) { // Handle error ... } console.log(`A new event has been persisted: ${JSON.stringify(event)}.`); // Publish to message broker etc. ... }); }; ``` ### Projections ```typescript import createEventStore from "eventastic"; import createProjection, { when } from "eventastic/projection"; const app = async() => { const es = await createEventStore({ host: 'localhost', port: 32793 }); const UserCount = createProjection( when('UserRegisteredEvent', (count: number, event: IEvent<IUser>) => count++), when('UserUnregisteredEvent', (count: number, event: IEvent<IUser>) => count--) ); const registeredUserCount = await es.project(UserCount); console.log(`We have ${registeredUserCount} user(s). Yay!`); }; ``` ### Replay all events ```typescript import createEventStore from "eventastic"; const app = async() => { const es = await createEventStore({ host: 'localhost', port: 32793 }); await es.replay(event => { // Do something with the event }); console.log(`We have ${registeredUserCount} user(s). Yay!`); }; ``` # License MIT © [André König](http://andrekoenig.de)
{ "content_hash": "7e4cd917381faa9bd990923e97cc0a75", "timestamp": "", "source": "github", "line_count": 112, "max_line_length": 220, "avg_line_length": 23.205357142857142, "alnum_prop": 0.6275490573297422, "repo_name": "akoenig/eventastic", "id": "13ad62a83da3bccaa42d8319d823d5811cda5c6e", "size": "2738", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "readme.md", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "330" }, { "name": "TypeScript", "bytes": "10209" } ], "symlink_target": "" }
/** * @author Richard Searle */ package cognitiveentity.xml.sax.interop import scala.xml._ import org.xml.sax.ext.LexicalHandler import org.xml.sax._ import org.xml.sax.helpers._ import scala.xml.Utility._ class XMLDumper(target:ContentHandler){ val lexical:Option[LexicalHandler] = if(target.isInstanceOf[LexicalHandler]) Some(target.asInstanceOf[LexicalHandler]) else None def toXML(x: Node){ target.startDocument toXML(x,TopScope) target.endDocument } private def toXML(x: Node, pscope: NamespaceBinding) { x match { case c: Comment => lexical.map(_.comment(c.commentText.toCharArray,0,c.commentText.length)) case a: PCData => lexical.map {lex=> lex.startCDATA; characters(a); lex.endCDATA} case a: Atom[_] => characters(a) case e: EntityRef => characters(e) case p: ProcInstr => target.processingInstruction(p.target,p.proctext) case g: Group => g.nodes foreach {toXML(_, x.scope)} case _ => element(x,x.scope,pscope ) } } private def characters(n:Node){ val s = n text; target.characters(s.toCharArray,0,s.length) } private def element(x:Node,ns:NamespaceBinding,stop:NamespaceBinding){ if(ns eq stop) { val uri = x.namespace val localName = x.label val qName = if(x.prefix == null) localName else x.prefix + ":" + localName target.startElement(uri,localName,qName,toAttributes(x) ) x.child foreach {toXML(_, x.scope)} target.endElement(uri,localName,qName) } else { val p = if(ns.prefix==null) "" else ns.prefix target.startPrefixMapping(p,ns.uri) element(x,ns.parent, stop) target.endPrefixMapping(p) } } private def toAttributes(node:Node) = { val atts = new AttributesImpl() var natt = node.attributes while(natt != null){ natt match { case pa:PrefixedAttribute => atts.addAttribute(null,pa.key,pa.pre+":"+pa.key,"CDATA",toString(pa.value)) case ua:UnprefixedAttribute => atts.addAttribute(null,ua.key,ua.key,"CDATA",toString(ua.value)) case Null => //ignored } natt = natt.next } atts } private def toString(ns:Seq[Node]) = { val sb = new StringBuilder ns foreach {_ match { case a: Atom[_] => sb.append(a.text) case e:EntityRef => sb.append(e.text) } } sb.toString } }
{ "content_hash": "d28ab687626673871bda53ad91b05965", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 132, "avg_line_length": 28.49411764705882, "alnum_prop": 0.6354252683732452, "repo_name": "searler/ScalaXML", "id": "404e42c7fff65683e13e3d5a9ca387ed15ca3da4", "size": "3020", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/cognitiveentity/xml/sax/interop/XMLDumper.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "775" }, { "name": "Scala", "bytes": "147029" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Hello Electron React!</title> <link rel="stylesheet" href="../node_modules/font-awesome/css/font-awesome.min.css" /> <script> if (!process.env.HOT) { const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = '../dist/style.css'; document.write(link.outerHTML); } </script> </head> <body> <div id="root"></div> <script> { const script = document.createElement('script'); const port = process.env.PORT || 3000; script.src = (process.env.HOT) ? `http://localhost:${port}/dist/bundle.js` : '../dist/bundle.js'; document.write(script.outerHTML); } </script> </body> </html>
{ "content_hash": "3e277caee0cd6f1810eaad743e4a4c9a", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 105, "avg_line_length": 28.925925925925927, "alnum_prop": 0.5697823303457106, "repo_name": "htanjo/server-app", "id": "da882db669d2cb67762f9722fea92197985a54ac", "size": "781", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "app/app.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4780" }, { "name": "HTML", "bytes": "781" }, { "name": "JavaScript", "bytes": "44883" } ], "symlink_target": "" }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.spi.statistics; import com.facebook.presto.spi.ColumnHandle; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static java.lang.String.format; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; public final class TableStatistics { private static final TableStatistics EMPTY = TableStatistics.builder().build(); private final Estimate rowCount; private final Map<ColumnHandle, ColumnStatistics> columnStatistics; public static TableStatistics empty() { return EMPTY; } public TableStatistics(Estimate rowCount, Map<ColumnHandle, ColumnStatistics> columnStatistics) { this.rowCount = requireNonNull(rowCount, "rowCount can not be null"); if (!rowCount.isUnknown() && rowCount.getValue() < 0) { throw new IllegalArgumentException(format("rowCount must be greater than or equal to 0: %s", rowCount.getValue())); } this.columnStatistics = unmodifiableMap(requireNonNull(columnStatistics, "columnStatistics can not be null")); } public Estimate getRowCount() { return rowCount; } public Map<ColumnHandle, ColumnStatistics> getColumnStatistics() { return columnStatistics; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TableStatistics that = (TableStatistics) o; return Objects.equals(rowCount, that.rowCount) && Objects.equals(columnStatistics, that.columnStatistics); } @Override public int hashCode() { return Objects.hash(rowCount, columnStatistics); } @Override public String toString() { return "TableStatistics{" + "rowCount=" + rowCount + ", columnStatistics=" + columnStatistics + '}'; } public static Builder builder() { return new Builder(); } public static final class Builder { private Estimate rowCount = Estimate.unknown(); private Map<ColumnHandle, ColumnStatistics> columnStatisticsMap = new HashMap<>(); public Builder setRowCount(Estimate rowCount) { this.rowCount = requireNonNull(rowCount, "rowCount can not be null"); return this; } public Builder setColumnStatistics(ColumnHandle columnHandle, ColumnStatistics columnStatistics) { requireNonNull(columnHandle, "columnHandle can not be null"); requireNonNull(columnStatistics, "columnStatistics can not be null"); this.columnStatisticsMap.put(columnHandle, columnStatistics); return this; } public TableStatistics build() { return new TableStatistics(rowCount, columnStatisticsMap); } } }
{ "content_hash": "88300f906964a43cc24434cdd7159f17", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 127, "avg_line_length": 30.775862068965516, "alnum_prop": 0.6605042016806723, "repo_name": "raghavsethi/presto", "id": "af75c0fd463118e409944733dbc174559d482f37", "size": "3570", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "presto-spi/src/main/java/com/facebook/presto/spi/statistics/TableStatistics.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "26997" }, { "name": "CSS", "bytes": "13018" }, { "name": "HTML", "bytes": "28633" }, { "name": "Java", "bytes": "31909074" }, { "name": "JavaScript", "bytes": "214692" }, { "name": "Makefile", "bytes": "6830" }, { "name": "PLSQL", "bytes": "2797" }, { "name": "PLpgSQL", "bytes": "11504" }, { "name": "Python", "bytes": "7664" }, { "name": "SQLPL", "bytes": "926" }, { "name": "Shell", "bytes": "29871" }, { "name": "Thrift", "bytes": "12631" } ], "symlink_target": "" }
#ifndef __AMEBAD_REBOOT_REASON_H__ #define __AMEBAD_REBOOT_REASON_H__ #include <tinyara/reboot_reason.h> enum { REBOOT_SYSTEM_DSLP_RESET = REBOOT_BOARD_SPECIFIC1, /* System wake up from deep sleep */ REBOOT_SYSTEM_SYS_RESET_CORE = REBOOT_BOARD_SPECIFIC2, /* System reset by Core */ REBOOT_SYSTEM_BOD_RESET = REBOOT_BOARD_SPECIFIC3, /* Brownout reset */ REBOOT_SYSTEM_TZWD_RESET = REBOOT_BOARD_SPECIFIC4, /* TrustZone Watch dog */ }; #endif /* __AMEBAD_REBOOT_REASON_H__ */
{ "content_hash": "f716afd08408b0aee8dbfd3fecaa1ec0", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 92, "avg_line_length": 33, "alnum_prop": 0.692929292929293, "repo_name": "junmin-kim/TizenRT", "id": "35dc09192ac795050f1908c0c68816cdc5d5fd5e", "size": "1270", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "os/arch/arm/src/amebad/amebad_reboot_reason.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "2045766" }, { "name": "Batchfile", "bytes": "42646" }, { "name": "C", "bytes": "75257607" }, { "name": "C++", "bytes": "813875" }, { "name": "HTML", "bytes": "2990" }, { "name": "Java", "bytes": "63595" }, { "name": "Makefile", "bytes": "825075" }, { "name": "Perl", "bytes": "4361" }, { "name": "PowerShell", "bytes": "8511" }, { "name": "Python", "bytes": "267794" }, { "name": "Roff", "bytes": "4401" }, { "name": "Shell", "bytes": "236136" }, { "name": "Tcl", "bytes": "163693" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>Deferred-notify</title> <style> #notifier{ width:500px;height:500px; margin: 0 auto; /*background: #2365cc;*/ } </style> </head> <body> <div id="main"> <div id="notifier" ></div> </div> <script type="text/javascript" src="js/jquery-1.7.1.js"></script> <script type="text/javascript"> ;(function($){ var longRunning = function(){ return $.Deferred(function(dfd){ dfd.notify("operation started"); console.log(dfd.state); var callback = function(){ dfd.notify("operation finished"); dfd.resolve(); }; setTimeout(callback,5000); }).promise(); }; longRunning().progress(function(notification){ console.log(this.state); $("#notifier") .text(notification) .fadeIn(5000); }).done(function(){ console.log(this.state); $("#notifier").css({ "color":"green", "font-weight":"bold" }); }); })(jQuery); </script> </body> </html>
{ "content_hash": "8bd5cbc83ab040953e28153521115a7c", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 69, "avg_line_length": 28.306122448979593, "alnum_prop": 0.4297043979812545, "repo_name": "kongwen/zhubao1", "id": "bc18a8d6822e03901bd21eb9021b247a763694ef", "size": "1387", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "project/web/assets/Jquery/deferred-notify.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "39014" }, { "name": "CSS", "bytes": "272873" }, { "name": "CoffeeScript", "bytes": "2795" }, { "name": "HTML", "bytes": "256286" }, { "name": "JavaScript", "bytes": "1467439" } ], "symlink_target": "" }
#include "sdk_common.h" #if NRF_MODULE_ENABLED(PEER_MANAGER) #include "security_dispatcher.h" #include <string.h> #include "ble.h" #include "ble_gap.h" #include "ble_conn_state.h" #include "peer_manager_types.h" #include "peer_database.h" #include "id_manager.h" // The number of registered event handlers. #define SMD_EVENT_HANDLERS_CNT (sizeof(m_evt_handlers) / sizeof(m_evt_handlers[0])) // Security Dispacher event handlers in Security Manager and GATT Cache Manager. extern void sm_smd_evt_handler(smd_evt_t const * p_event); extern void gcm_smd_evt_handler(smd_evt_t const * p_event); // Security Dispatcher events' handlers. // The number of elements in this array is SMD_EVENT_HANDLERS_CNT. static smd_evt_handler_t const m_evt_handlers[] = { sm_smd_evt_handler, gcm_smd_evt_handler }; static bool m_module_initialized; static ble_conn_state_user_flag_id_t m_flag_sec_proc = BLE_CONN_STATE_USER_FLAG_INVALID; static ble_conn_state_user_flag_id_t m_flag_sec_proc_pairing = BLE_CONN_STATE_USER_FLAG_INVALID; static ble_conn_state_user_flag_id_t m_flag_sec_proc_new_peer = BLE_CONN_STATE_USER_FLAG_INVALID; static ble_gap_lesc_p256_pk_t m_peer_pk; static void evt_send(smd_evt_t * p_event) { for (uint32_t i = 0; i < SMD_EVENT_HANDLERS_CNT; i++) { m_evt_handlers[i](p_event); } } static void sec_start_send(uint16_t conn_handle, pm_conn_sec_procedure_t procedure) { smd_evt_t evt = { .evt_id = SMD_EVT_SEC_PROCEDURE_START, .conn_handle = conn_handle, .params = {.sec_procedure_start = {.procedure = procedure}} }; evt_send(&evt); } /**@brief Event handler for events from the Peer Database module. * This handler is extern in Peer Database. * * @param[in] p_event The event that has happened. */ void smd_pdb_evt_handler(pdb_evt_t const * p_event) { if ((p_event->evt_id == PDB_EVT_WRITE_BUF_STORED) && (p_event->data_id == PM_PEER_DATA_ID_BONDING)) { smd_evt_t evt = { .evt_id = SMD_EVT_BONDING_INFO_STORED, .conn_handle = im_conn_handle_get(p_event->peer_id), .params = {.bonding_info_stored = {.peer_id = p_event->peer_id}} }; evt_send(&evt); } } /**@brief Function for processing the @ref BLE_GAP_EVT_SEC_PARAMS_REQUEST event from the SoftDevice. * * @param[in] p_gap_evt The event from the SoftDevice. */ static void sec_params_request_process(ble_gap_evt_t * p_gap_evt) { smd_evt_t evt = { .evt_id = SMD_EVT_PARAMS_REQ, .conn_handle = p_gap_evt->conn_handle }; evt_send(&evt); return; } /**@brief Function for administrative actions to be taken when a security process has been attempted. * * @param[in] conn_handle The connection the security process was attempted on. * @param[in] peer_id The peer ID given to the connected peer. * @param[in] success Whether the process was started successfully. * @param[in] pairing Whether the process was a pairing process. * @param[in] new_peer_created Whether a new peer was created during the process attempt. */ static void sec_proc_start(uint16_t conn_handle, pm_peer_id_t peer_id, bool success, bool pairing, bool new_peer_created) { ble_conn_state_user_flag_set(conn_handle, m_flag_sec_proc, success); if (success) { ble_conn_state_user_flag_set(conn_handle, m_flag_sec_proc_pairing, pairing); ble_conn_state_user_flag_set(conn_handle, m_flag_sec_proc_new_peer, new_peer_created); if (new_peer_created) { im_new_peer_id(conn_handle, peer_id); } } else { if (new_peer_created) { ret_code_t err_code = im_peer_free(peer_id); // Attempt to free allocated peer. UNUSED_VARIABLE(err_code); } } } /**@brief Function for processing the @ref BLE_GAP_EVT_SEC_INFO_REQUEST event from the SoftDevice. * * @param[in] p_gap_evt The event from the SoftDevice. */ static void sec_info_request_process(ble_gap_evt_t * p_gap_evt) { ret_code_t err_code; ble_gap_enc_info_t const * p_enc_info = NULL; pm_peer_data_flash_t peer_data; pm_peer_id_t peer_id = im_peer_id_get_by_master_id(&p_gap_evt->params.sec_info_request.master_id); smd_evt_t evt; evt.conn_handle = p_gap_evt->conn_handle; if (peer_id == PM_PEER_ID_INVALID) { peer_id = im_peer_id_get_by_conn_handle(p_gap_evt->conn_handle); } if (peer_id != PM_PEER_ID_INVALID) { err_code = pdb_peer_data_ptr_get(peer_id, PM_PEER_DATA_ID_BONDING, &peer_data); if (err_code == NRF_SUCCESS) { // There is stored bonding data for this peer. ble_gap_enc_key_t const * p_existing_key = &peer_data.p_bonding_data->own_ltk; if ( p_existing_key->enc_info.lesc || (im_master_ids_compare(&p_existing_key->master_id, &p_gap_evt->params.sec_info_request.master_id))) { p_enc_info = &p_existing_key->enc_info; } } } // All return values from the following can be safely ignored. err_code = sd_ble_gap_sec_info_reply(p_gap_evt->conn_handle, p_enc_info, NULL, NULL); if (err_code != NRF_SUCCESS) { evt.evt_id = SMD_EVT_ERROR_UNEXPECTED; evt.params.error_unexpected.error = err_code; evt_send(&evt); } else if (p_enc_info == NULL) { evt.evt_id = SMD_EVT_LINK_ENCRYPTION_FAILED; evt.params.link_encryption_failed.error = PM_CONN_SEC_ERROR_PIN_OR_KEY_MISSING; evt.params.link_encryption_failed.error_src = BLE_GAP_SEC_STATUS_SOURCE_LOCAL; evt_send(&evt); sec_proc_start(p_gap_evt->conn_handle, peer_id, false, false, false); } else { sec_start_send(p_gap_evt->conn_handle, PM_LINK_SECURED_PROCEDURE_ENCRYPTION); sec_proc_start(p_gap_evt->conn_handle, peer_id, err_code == NRF_SUCCESS, false, false); } return; } /**@brief Function for processing the @ref BLE_GAP_EVT_SEC_REQUEST event from the SoftDevice. * * @param[in] p_gap_evt The event from the SoftDevice. */ static void sec_request_process(ble_gap_evt_t * p_gap_evt) { smd_evt_t evt = { .evt_id = SMD_EVT_SLAVE_SECURITY_REQ, .conn_handle = p_gap_evt->conn_handle, .params = { .slave_security_req = { .bond = p_gap_evt->params.sec_request.bond, .mitm = p_gap_evt->params.sec_request.mitm, } } }; evt_send(&evt); return; } /**@brief Function for processing the @ref BLE_GAP_EVT_AUTH_STATUS event from the SoftDevice, when * the auth_status is success. * * @param[in] p_gap_evt The event from the SoftDevice. */ static void auth_status_success_process(ble_gap_evt_t * p_gap_evt) { ret_code_t err_code = NRF_SUCCESS; uint8_t role = ble_conn_state_role(p_gap_evt->conn_handle); pm_peer_id_t peer_id = im_peer_id_get_by_conn_handle(p_gap_evt->conn_handle); ble_gap_sec_kdist_t kdist_own = p_gap_evt->params.auth_status.kdist_own; ble_gap_sec_kdist_t kdist_peer = p_gap_evt->params.auth_status.kdist_peer; ble_conn_state_user_flag_set(p_gap_evt->conn_handle, m_flag_sec_proc, false); if (role == BLE_GAP_ROLE_INVALID) { /* Unlikely, but maybe possible? */ return; } if (p_gap_evt->params.auth_status.bonded) { err_code = pdb_write_buf_store(peer_id, PM_PEER_DATA_ID_BONDING); if (err_code != NRF_SUCCESS) { /* Unexpected */ smd_evt_t error_evt; error_evt.evt_id = SMD_EVT_ERROR_BONDING_INFO; error_evt.conn_handle = p_gap_evt->conn_handle; error_evt.params.error_bonding_info.peer_id = peer_id; error_evt.params.error_bonding_info.error = err_code; evt_send(&error_evt); } } else if (ble_conn_state_user_flag_get(p_gap_evt->conn_handle, m_flag_sec_proc_new_peer)) { ret_code_t err_code_free = im_peer_free(peer_id); UNUSED_VARIABLE(err_code_free); // Errors can be safely ignored. } smd_evt_t pairing_success_evt; pairing_success_evt.evt_id = SMD_EVT_PAIRING_SUCCESS; pairing_success_evt.conn_handle = p_gap_evt->conn_handle; pairing_success_evt.params.pairing_success.bonded = p_gap_evt->params.auth_status.bonded; pairing_success_evt.params.pairing_success.mitm = p_gap_evt->params.auth_status.sm1_levels.lv3; pairing_success_evt.params.pairing_success.kdist_own = kdist_own; pairing_success_evt.params.pairing_success.kdist_peer = kdist_peer; evt_send(&pairing_success_evt); return; } /**@brief Function for cleaning up after a failed pairing procedure. * * @param[in] conn_handle The handle of the connection the pairing procedure happens on. * @param[in] peer_id The peer id used in the pairing procedure. * @param[in] error The error the procedure failed with. * @param[in] error_src The party that raised the error. See @ref BLE_GAP_SEC_STATUS_SOURCES. */ static void pairing_failure(uint16_t conn_handle, pm_peer_id_t peer_id, pm_sec_error_code_t error, uint8_t error_src) { ret_code_t err_code = NRF_SUCCESS; smd_evt_t evt = { .evt_id = SMD_EVT_PAIRING_FAIL, .conn_handle = conn_handle, .params = { .pairing_failed = { .error = error, .error_src = error_src, } } }; if (ble_conn_state_user_flag_get(conn_handle, m_flag_sec_proc_new_peer)) { // The peer_id was created during the procedure, and should be freed, because no data is // stored under it. err_code = im_peer_free(peer_id); // Attempt to free allocated peer. UNUSED_VARIABLE(err_code); } else { err_code = pdb_write_buf_release(peer_id, PM_PEER_DATA_ID_BONDING); if ((err_code != NRF_SUCCESS) && (err_code == NRF_ERROR_NOT_FOUND /* No buffer was allocated */)) { smd_evt_t error_evt; error_evt.evt_id = SMD_EVT_ERROR_UNEXPECTED; error_evt.conn_handle = conn_handle; error_evt.params.error_unexpected.error = err_code; evt_send(&error_evt); } } ble_conn_state_user_flag_set(conn_handle, m_flag_sec_proc, false); evt_send(&evt); return; } /**@brief Function for cleaning up after a failed encryption procedure. * * @param[in] conn_handle The handle of the connection the encryption procedure happens on. * @param[in] error The error the procedure failed with. * @param[in] error_src The party that raised the error. See @ref BLE_GAP_SEC_STATUS_SOURCES. */ static void encryption_failure(uint16_t conn_handle, pm_sec_error_code_t error, uint8_t error_src) { smd_evt_t evt = { .evt_id = SMD_EVT_LINK_ENCRYPTION_FAILED, .conn_handle = conn_handle, .params = { .link_encryption_failed = { .error = error, .error_src = error_src, } } }; ble_conn_state_user_flag_set(conn_handle, m_flag_sec_proc, false); evt_send(&evt); return; } /**@brief Function for possibly cleaning up after a failed pairing or encryption procedure. * * @param[in] conn_handle The handle of the connection the pairing procedure happens on. * @param[in] peer_id The peer id used in the pairing procedure. * @param[in] error The error the procedure failed with. * @param[in] error_src The party that raised the error. See @ref BLE_GAP_SEC_STATUS_SOURCES. */ static void link_secure_failure(uint16_t conn_handle, pm_sec_error_code_t error, uint8_t error_src) { if (ble_conn_state_user_flag_get(conn_handle, m_flag_sec_proc)) { pm_peer_id_t peer_id = im_peer_id_get_by_conn_handle(conn_handle); if (peer_id != PM_PEER_ID_INVALID) { if (ble_conn_state_user_flag_get(conn_handle, m_flag_sec_proc_pairing)) { pairing_failure(conn_handle, peer_id, error, error_src); } else { encryption_failure(conn_handle, error, error_src); } } } } /**@brief Function for processing the @ref BLE_GAP_EVT_DISCONNECT event from the SoftDevice. * * @param[in] p_gap_evt The event from the SoftDevice. */ static void disconnect_process(ble_gap_evt_t * p_gap_evt) { pm_sec_error_code_t error = (p_gap_evt->params.disconnected.reason == BLE_HCI_CONN_TERMINATED_DUE_TO_MIC_FAILURE) ? PM_CONN_SEC_ERROR_MIC_FAILURE : PM_CONN_SEC_ERROR_DISCONNECT; link_secure_failure(p_gap_evt->conn_handle, error, BLE_GAP_SEC_STATUS_SOURCE_LOCAL); } /**@brief Function for processing the @ref BLE_GAP_EVT_AUTH_STATUS event from the SoftDevice, when * the auth_status is failure. * * @param[in] p_gap_evt The event from the SoftDevice. */ static void auth_status_failure_process(ble_gap_evt_t * p_gap_evt) { link_secure_failure(p_gap_evt->conn_handle, p_gap_evt->params.auth_status.auth_status, p_gap_evt->params.auth_status.error_src); } /**@brief Function for processing the @ref BLE_GAP_EVT_AUTH_STATUS event from the SoftDevice. * * @param[in] p_gap_evt The event from the SoftDevice. */ static void auth_status_process(ble_gap_evt_t * p_gap_evt) { switch (p_gap_evt->params.auth_status.auth_status) { case BLE_GAP_SEC_STATUS_SUCCESS: auth_status_success_process(p_gap_evt); break; default: auth_status_failure_process(p_gap_evt); break; } } /**@brief Function for processing the @ref BLE_GAP_EVT_CONN_SEC_UPDATE event from the SoftDevice. * * @param[in] p_gap_evt The event from the SoftDevice. */ static void conn_sec_update_process(ble_gap_evt_t * p_gap_evt) { if (ble_conn_state_encrypted(p_gap_evt->conn_handle)) { if (!ble_conn_state_user_flag_get(p_gap_evt->conn_handle, m_flag_sec_proc_pairing)) { ble_conn_state_user_flag_set(p_gap_evt->conn_handle, m_flag_sec_proc, false); } smd_evt_t evt; evt.conn_handle = p_gap_evt->conn_handle; evt.evt_id = SMD_EVT_LINK_ENCRYPTION_UPDATE; evt.params.link_encryption_update.mitm_protected = ble_conn_state_mitm_protected(p_gap_evt->conn_handle); evt_send(&evt); } else { encryption_failure(p_gap_evt->conn_handle, PM_CONN_SEC_ERROR_PIN_OR_KEY_MISSING, BLE_GAP_SEC_STATUS_SOURCE_REMOTE); } } /**@brief Funtion for initializing a BLE Connection State user flag. * * @param[out] flag_id The flag to initialize. */ static void flag_id_init(ble_conn_state_user_flag_id_t * p_flag_id) { if (*p_flag_id == BLE_CONN_STATE_USER_FLAG_INVALID) { *p_flag_id = ble_conn_state_user_flag_acquire(); } } ret_code_t smd_init(void) { NRF_PM_DEBUG_CHECK(!m_module_initialized); flag_id_init(&m_flag_sec_proc); flag_id_init(&m_flag_sec_proc_pairing); flag_id_init(&m_flag_sec_proc_new_peer); if ((m_flag_sec_proc == BLE_CONN_STATE_USER_FLAG_INVALID) || (m_flag_sec_proc_pairing == BLE_CONN_STATE_USER_FLAG_INVALID) || (m_flag_sec_proc_new_peer == BLE_CONN_STATE_USER_FLAG_INVALID)) { return NRF_ERROR_INTERNAL; } m_module_initialized = true; return NRF_SUCCESS; } ret_code_t smd_params_reply(uint16_t conn_handle, ble_gap_sec_params_t * p_sec_params, ble_gap_lesc_p256_pk_t * p_public_key) { NRF_PM_DEBUG_CHECK(m_module_initialized); uint8_t role = ble_conn_state_role(conn_handle); pm_peer_id_t peer_id = PM_PEER_ID_INVALID; ret_code_t err_code = NRF_SUCCESS; uint8_t sec_status = BLE_GAP_SEC_STATUS_SUCCESS; ble_gap_sec_keyset_t sec_keyset; bool new_peer_created = false; memset(&sec_keyset, 0, sizeof(ble_gap_sec_keyset_t)); if (role == BLE_GAP_ROLE_INVALID) { return BLE_ERROR_INVALID_CONN_HANDLE; } if (p_sec_params == NULL) { // NULL params means reject pairing. sec_status = BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP; } else if (p_sec_params->bond) { // Bonding is to be performed, prepare to receive bonding data. pm_peer_data_t peer_data; peer_id = im_peer_id_get_by_conn_handle(conn_handle); if (peer_id == PM_PEER_ID_INVALID) { // Peer is unknown to us, allocate a new peer ID for it. peer_id = pdb_peer_allocate(); if (peer_id != PM_PEER_ID_INVALID) { new_peer_created = true; } else { err_code = NRF_ERROR_INTERNAL; } } if (err_code == NRF_SUCCESS) { // Peer ID is ready, acquire a memory buffer to receive bonding data into. err_code = pdb_write_buf_get(peer_id, PM_PEER_DATA_ID_BONDING, 1, &peer_data); if (err_code == NRF_SUCCESS) { memset(peer_data.p_bonding_data, 0, sizeof(pm_peer_data_bonding_t)); peer_data.p_bonding_data->own_role = role; sec_keyset.keys_own.p_enc_key = &peer_data.p_bonding_data->own_ltk; sec_keyset.keys_own.p_pk = p_public_key; sec_keyset.keys_peer.p_enc_key = &peer_data.p_bonding_data->peer_ltk; sec_keyset.keys_peer.p_id_key = &peer_data.p_bonding_data->peer_ble_id; sec_keyset.keys_peer.p_pk = &m_peer_pk; // Retrieve the address the peer used during connection establishment. // This address will be overwritten if ID is shared. Should not fail. ret_code_t err_code_addr = im_ble_addr_get(conn_handle, &peer_data.p_bonding_data->peer_ble_id.id_addr_info); UNUSED_VARIABLE(err_code_addr); // Buffer is OK, reserve room in flash for the data. err_code = pdb_write_buf_store_prepare(peer_id, PM_PEER_DATA_ID_BONDING); } } } else { // Pairing only, no action needed. } if (err_code == NRF_SUCCESS) { // Everything OK, reply to SoftDevice. If an error happened, the user is given an // opportunity to change the parameters and retry the call. if (role == BLE_GAP_ROLE_CENTRAL) { err_code = sd_ble_gap_sec_params_reply(conn_handle, sec_status, NULL, &sec_keyset); } else { err_code = sd_ble_gap_sec_params_reply(conn_handle, sec_status, p_sec_params, &sec_keyset); if ((p_sec_params != NULL) && (err_code == NRF_SUCCESS)) { pm_conn_sec_procedure_t procedure = p_sec_params->bond ? PM_LINK_SECURED_PROCEDURE_BONDING : PM_LINK_SECURED_PROCEDURE_PAIRING; sec_start_send(conn_handle, procedure); } } } sec_proc_start(conn_handle, peer_id, (err_code == NRF_SUCCESS) && (sec_status != BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP), true, new_peer_created); return err_code; } static ret_code_t link_secure_central_existing_peer(uint16_t conn_handle, ble_gap_sec_params_t * p_sec_params, bool force_repairing, pm_peer_id_t peer_id, pm_conn_sec_procedure_t * procedure) { pm_peer_data_flash_t peer_data; pm_peer_data_t dummy_peer_data; ret_code_t err_code; ble_gap_enc_key_t const * p_existing_key = NULL; bool lesc = false; err_code = pdb_peer_data_ptr_get(peer_id, PM_PEER_DATA_ID_BONDING, &peer_data); if (err_code == NRF_SUCCESS) { // Use peer's key since they are peripheral. p_existing_key = &(peer_data.p_bonding_data->peer_ltk); lesc = peer_data.p_bonding_data->own_ltk.enc_info.lesc; if (lesc) // LESC was used during bonding. { // For LESC, always use own key. p_existing_key = &(peer_data.p_bonding_data->own_ltk); } } if (!force_repairing && (err_code == NRF_SUCCESS) && (p_existing_key != NULL) && (lesc || im_master_id_is_valid(&(p_existing_key->master_id)))) /* There is a valid LTK stored. */ //&& (p_existing_key->enc_info.auth >= p_sec_params->mitm) /* The requested MITM security is at or below the existing level. */ //&& (!p_sec_params->mitm || (lesc >= p_sec_params->lesc))) /* The requested LESC security is at or below the existing level. We only care about LESC if MITM is required. */ { err_code = sd_ble_gap_encrypt(conn_handle, &(p_existing_key->master_id), &(p_existing_key->enc_info)); *procedure = PM_LINK_SECURED_PROCEDURE_ENCRYPTION; } else if ((err_code == NRF_SUCCESS) || (err_code == NRF_ERROR_NOT_FOUND)) { /* Re-pairing is needed, because there is no LTK available or the existing key is not secure enough */ err_code = NRF_SUCCESS; if (p_sec_params->bond) { err_code = pdb_write_buf_get(peer_id, PM_PEER_DATA_ID_BONDING, 1, &dummy_peer_data); if (err_code == NRF_SUCCESS) { err_code = pdb_write_buf_store_prepare(peer_id, PM_PEER_DATA_ID_BONDING); } } if (err_code == NRF_SUCCESS) { err_code = sd_ble_gap_authenticate(conn_handle, p_sec_params); } if (err_code != NRF_SUCCESS) { ret_code_t err_code_release = pdb_write_buf_release(peer_id, PM_PEER_DATA_ID_BONDING); if ((err_code_release != NRF_SUCCESS) && (err_code_release != NRF_ERROR_NOT_FOUND)) { err_code = NRF_ERROR_INTERNAL; } } } sec_proc_start(conn_handle, peer_id, err_code == NRF_SUCCESS, *procedure != PM_LINK_SECURED_PROCEDURE_ENCRYPTION, false); return err_code; } static ret_code_t link_secure_central_new_peer(uint16_t conn_handle, ble_gap_sec_params_t * p_sec_params) { pm_peer_id_t peer_id = pdb_peer_allocate(); pm_peer_data_t dummy_peer_data; ret_code_t err_code; if (peer_id != PM_PEER_ID_INVALID) { err_code = pdb_write_buf_get(peer_id, PM_PEER_DATA_ID_BONDING, 1, &dummy_peer_data); if (err_code == NRF_SUCCESS) { err_code = pdb_write_buf_store_prepare(peer_id, PM_PEER_DATA_ID_BONDING); } if (err_code == NRF_SUCCESS) { err_code = sd_ble_gap_authenticate(conn_handle, p_sec_params); } if (err_code != NRF_SUCCESS) { ret_code_t err_code_free = pdb_write_buf_release(peer_id, PM_PEER_DATA_ID_BONDING); if ((err_code_free != NRF_SUCCESS) && (err_code_free != NRF_ERROR_NOT_FOUND)) { err_code = NRF_ERROR_INTERNAL; } } } else { err_code = NRF_ERROR_INTERNAL; } sec_proc_start(conn_handle, peer_id, err_code == NRF_SUCCESS, true, peer_id != PM_PEER_ID_INVALID); return err_code; } static ret_code_t link_secure_central(uint16_t conn_handle, ble_gap_sec_params_t * p_sec_params, bool force_repairing) { ret_code_t err_code; pm_peer_id_t peer_id; if (p_sec_params == NULL) { return sd_ble_gap_authenticate(conn_handle, NULL); } pm_conn_sec_procedure_t procedure = p_sec_params->bond ? PM_LINK_SECURED_PROCEDURE_BONDING : PM_LINK_SECURED_PROCEDURE_PAIRING; peer_id = im_peer_id_get_by_conn_handle(conn_handle); if (peer_id != PM_PEER_ID_INVALID) { // There is already data in flash for this peer. err_code = link_secure_central_existing_peer(conn_handle, p_sec_params, force_repairing, peer_id, &procedure); } else if (p_sec_params->bond) { // New peer is required. err_code = link_secure_central_new_peer(conn_handle, p_sec_params); } else { // No bonding, only pairing. err_code = sd_ble_gap_authenticate(conn_handle, p_sec_params); sec_proc_start(conn_handle, peer_id, err_code == NRF_SUCCESS, true, false); } if (err_code == NRF_SUCCESS) { sec_start_send(conn_handle, procedure); } return err_code; } static ret_code_t link_secure_peripheral(uint16_t conn_handle, ble_gap_sec_params_t * p_sec_params) { // This should never happen for a peripheral. NRF_PM_DEBUG_CHECK(p_sec_params != NULL); // VERIFY_PARAM_NOT_NULL(p_sec_params); ret_code_t err_code = sd_ble_gap_authenticate(conn_handle, p_sec_params); return err_code; } ret_code_t smd_link_secure(uint16_t conn_handle, ble_gap_sec_params_t * p_sec_params, bool force_repairing) { NRF_PM_DEBUG_CHECK(m_module_initialized); uint8_t role = ble_conn_state_role(conn_handle); switch (role) { case BLE_GAP_ROLE_CENTRAL: return link_secure_central(conn_handle, p_sec_params, force_repairing); case BLE_GAP_ROLE_PERIPH: return link_secure_peripheral(conn_handle, p_sec_params); default: return BLE_ERROR_INVALID_CONN_HANDLE; } } void smd_ble_evt_handler(ble_evt_t * p_ble_evt) { switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_DISCONNECTED: disconnect_process(&(p_ble_evt->evt.gap_evt)); break; case BLE_GAP_EVT_SEC_PARAMS_REQUEST: sec_params_request_process(&(p_ble_evt->evt.gap_evt)); break; case BLE_GAP_EVT_SEC_INFO_REQUEST: sec_info_request_process(&(p_ble_evt->evt.gap_evt)); break; case BLE_GAP_EVT_SEC_REQUEST: sec_request_process(&(p_ble_evt->evt.gap_evt)); break; case BLE_GAP_EVT_AUTH_STATUS: auth_status_process(&(p_ble_evt->evt.gap_evt)); break; case BLE_GAP_EVT_CONN_SEC_UPDATE: conn_sec_update_process(&(p_ble_evt->evt.gap_evt)); break; }; } #endif //NRF_MODULE_ENABLED(PEER_MANAGER)
{ "content_hash": "a05796a330efd9de7b4e8ffbd4a342de", "timestamp": "", "source": "github", "line_count": 858, "max_line_length": 190, "avg_line_length": 34.18065268065268, "alnum_prop": 0.5391959627646878, "repo_name": "Tech4Race/nrf5x-base", "id": "6ed56086a79d285acaa6147de19d9e33155e7fce", "size": "29775", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sdk/nrf5_sdk_12.2.0/components/ble/peer_manager/security_dispatcher.c", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "356869" }, { "name": "C", "bytes": "43986144" }, { "name": "C++", "bytes": "891552" }, { "name": "Makefile", "bytes": "71157" }, { "name": "Objective-C", "bytes": "31666" }, { "name": "Python", "bytes": "1120" }, { "name": "Shell", "bytes": "113" } ], "symlink_target": "" }