code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct template as_one</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../../accumulators/reference.html#header.boost.accumulators.numeric.functional_hpp" title="Header &lt;boost/accumulators/numeric/functional.hpp&gt;"> <link rel="prev" href="as_zero.html" title="Struct template as_zero"> <link rel="next" href="../op/plus.html" title="Struct plus"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="as_zero.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.numeric.functional_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../op/plus.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.numeric.functional.as_one"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct template as_one</span></h2> <p>boost::numeric::functional::as_one</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../../accumulators/reference.html#header.boost.accumulators.numeric.functional_hpp" title="Header &lt;boost/accumulators/numeric/functional.hpp&gt;">boost/accumulators/numeric/functional.hpp</a>&gt; </span><span class="keyword">template</span><span class="special">&lt;</span><span class="keyword">typename</span> Arg<span class="special">,</span> <span class="keyword">typename</span> Tag<span class="special">&gt;</span> <span class="keyword">struct</span> <a class="link" href="as_one.html" title="Struct template as_one">as_one</a> <span class="special">:</span> <span class="keyword">public</span> <span class="identifier">boost</span><span class="special">::</span><span class="identifier">numeric</span><span class="special">::</span><span class="identifier">functional</span><span class="special">::</span><span class="identifier">as_one_base</span><span class="special">&lt;</span> <span class="identifier">Arg</span><span class="special">,</span> <span class="keyword">void</span> <span class="special">&gt;</span> <span class="special">{</span> <span class="special">}</span><span class="special">;</span></pre></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2005, 2006 Eric Niebler<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="as_zero.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../../accumulators/reference.html#header.boost.accumulators.numeric.functional_hpp"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="../op/plus.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
yinchunlong/abelkhan-1
ext/c++/thirdpart/c++/boost/doc/html/boost/numeric/functional/as_one.html
HTML
mit
4,642
TextPack ======== TextPack is a utility for preparing font and string data for Chip8 programs. Font data is read in as a vertical strip of 8xN characters. A simple compression algorithm overlaps characters in the font data where possible, and then strings are encoded as a sequence of byte offsets from the beginning of the font data. Compiling: javac TextPack.java java TextPack usage: textpack [--toimage] [--strip] <font> <alphabet> <text> The `font` argument should be an 8xN vertical strip of characters stored as an image file. The `alphabet` defines the sequence of characters as they appear in the font. Character heights are inferred from the size of the font file and the length of the alphabet. The `text` argument is the string you wish to encode. java TextPack font4x5.png 'ABCDEFGHIJKLMNOPQRSTUVWXYZ!` ' 'SOME TEXT' : font4x5 # (112 bytes) 0xF0 0x40 0x40 0x40 0x40 0x90 0x90 0x70 0x10 0xE0 0x20 0x20 0x20 0x00 0x20 0x40 0x00 0x00 0x00 0x00 0x00 0xE0 0x90 0xE0 0x90 0x90 0x90 0xE0 0x90 0xE0 0x90 0xE0 0x80 0x80 0xD0 0xB0 0xB0 0x90 0x90 0x90 0x90 0x60 0x60 0x90 0x90 0x90 0x60 0x90 0xF0 0x90 0x90 0xF0 0x90 0x90 0xD0 0xB0 0x90 0x90 0x90 0x50 0x20 0xF0 0x80 0xE0 0x80 0x80 0x80 0x80 0xF0 0x80 0xE0 0x80 0xF0 0x40 0x40 0x40 0xF0 0x60 0x90 0x80 0x90 0x60 0x90 0x90 0xB0 0x70 0x80 0xB0 0x90 0x70 0x80 0x60 0x10 0xE0 0x90 0xA0 0xC0 0xA0 0x90 0x90 0xB0 0xB0 0xD0 0xF0 0x20 0x40 0x80 0xF0 0x20 0x20 0x20 0xC0 : text # (9 bytes) 0x59 0x2A 0x22 0x44 0x10 0x00 0x44 0x28 0x00 The `--toimage` option writes compressed font data to a PNG for convenient visual inspection. The `--strip` option removes characters from the font before compression if they are not used in the `text` string. Here is an Octo program which can display text in the format TextPack produces: : main va := 2 # cursor x vb := 1 # cursor y vc := 0 # character index loop i := text i += vc load v0 i := font4x5 i += v0 sprite va vb 5 va += 5 # assume lores screen bounds if va == 62 then vb += 6 if va == 62 then va := 2 vc += 1 # string length check if vc != 22 then again loop again : font4x5 # (50 bytes) 0x70 0x80 0x60 0x10 0xE0 0x90 0xE0 0x80 0x80 0xE0 0x90 0xE0 0x90 0x90 0x00 0x00 0x00 0x00 0x00 0x90 0x60 0x60 0x90 0x90 0x90 0x60 0x90 0xF0 0x90 0x90 0xF0 0x90 0x90 0xD0 0xB0 0xB0 0x90 0x90 0xB0 0xB0 0xD0 0xF0 0x80 0xE0 0x80 0xF0 0x40 0x40 0x40 0x40 : text # (22 bytes) 0x00 0x15 0x21 0x29 0x0E 0x2D 0x29 0x13 0x2D 0x0E 0x0E 0x0E 0x2D 0x1C 0x19 0x2D 0x0E 0x24 0x09 0x19 0x04 0x00 Note that for SuperChip high resolution mode the screen boundaries would need to be adjusted, and for a general-purpose string drawing routine it would be necessary to store the string length in a register and provide indirect access to the string data either with a lookup table or using self-modifying code and `:unpack`.
whoozle/Octo
tools/TextPack/Readme.md
Markdown
mit
2,914
using System; using VkNet.Enums.Filters; using VkNet.Utils; namespace VkNet.Model.RequestParams { /// <summary> /// Список параметров запроса newsfeed.get /// </summary> public struct NewsFeedGetRecommendedParams { /// <summary> /// Время в формате unixtime, начиная с которого следует получить новости для текущего пользователя. /// </summary> public DateTime? StartTime { get; set; } /// <summary> /// Время в формате unixtime, до которого следует получить новости для текущего пользователя. Если параметр не задан, то он считается равным текущему времени. /// </summary> public DateTime? EndTime { get; set; } /// <summary> /// Максимальное количество фотографий, информацию о которых необходимо вернуть. По умолчанию 5. /// </summary> public uint? MaxPhotos { get; set; } /// <summary> /// Идентификатор, необходимый для получения следующей страницы результатов. Значение, необходимое для передачи в этом параметре, возвращается в поле ответа next_from. /// </summary> public long? StartFrom { get; set; } /// <summary> /// Указывает, какое максимальное число новостей следует возвращать, но не более 100. По умолчанию 50. /// </summary> public long? Count { get; set; } /// <summary> /// Список дополнительных полей профилей, которые необходимо вернуть. /// </summary> public UsersFields Fields { get; set; } /// <summary> /// Привести к типу VkParameters. /// </summary> /// <param name="p">Параметры.</param> /// <returns></returns> internal static VkParameters ToVkParameters(NewsFeedGetRecommendedParams p) { var parameters = new VkParameters { { "start_time", p.StartTime }, { "end_time", p.EndTime }, { "max_photos", p.MaxPhotos }, { "start_from", p.StartFrom }, { "count", p.Count }, { "fields", p.Fields } }; return parameters; } } }
kkohno/vk
VkNet/Model/RequestParams/NewsFeed/NewsFeedGetRecommendedParams.cs
C#
mit
2,458
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System; using System.Diagnostics; using System.Runtime; using System.Runtime.InteropServices; using System.Threading; namespace Internal.Runtime.Augments { public sealed partial class RuntimeThread { // Event signaling that the thread has stopped private ManualResetEvent _stopped; private readonly WaitSubsystem.ThreadWaitInfo _waitInfo; internal WaitSubsystem.ThreadWaitInfo WaitInfo => _waitInfo; private void PlatformSpecificInitialize() { RuntimeImports.RhSetThreadExitCallback(AddrofIntrinsics.AddrOf<Action>(OnThreadExit)); } // Platform-specific initialization of foreign threads, i.e. threads not created by Thread.Start private void PlatformSpecificInitializeExistingThread() { _stopped = new ManualResetEvent(false); } /// <summary> /// Callers must ensure to clear and return the array after use /// </summary> internal SafeWaitHandle[] RentWaitedSafeWaitHandleArray(int requiredCapacity) { Debug.Assert(this == CurrentThread); Debug.Assert(!ReentrantWaitsEnabled); // due to this, no need to actually rent and return the array _waitedSafeWaitHandles.VerifyElementsAreDefault(); _waitedSafeWaitHandles.EnsureCapacity(requiredCapacity); return _waitedSafeWaitHandles.Items; } internal void ReturnWaitedSafeWaitHandleArray(SafeWaitHandle[] waitedSafeWaitHandles) { Debug.Assert(this == CurrentThread); Debug.Assert(!ReentrantWaitsEnabled); // due to this, no need to actually rent and return the array Debug.Assert(waitedSafeWaitHandles == _waitedSafeWaitHandles.Items); } private ThreadPriority GetPriorityLive() { return ThreadPriority.Normal; } private bool SetPriorityLive(ThreadPriority priority) { return true; } [NativeCallable] private static void OnThreadExit() { RuntimeThread currentThread = t_currentThread; if (currentThread != null) { // Inform the wait subsystem that the thread is exiting. For instance, this would abandon any mutexes locked by // the thread. WaitSubsystem.OnThreadExiting(currentThread); // Set the Stopped bit and signal the current thread as stopped int state = currentThread._threadState; if ((state & (int)(ThreadState.Stopped | ThreadState.Aborted)) == 0) { currentThread.SetThreadStateBit(ThreadState.Stopped); } currentThread._stopped.Set(); } } private ThreadState GetThreadState() => (ThreadState)_threadState; private bool JoinInternal(int millisecondsTimeout) { // This method assumes the thread has been started Debug.Assert(!GetThreadStateBit(ThreadState.Unstarted) || (millisecondsTimeout == 0)); SafeWaitHandle waitHandle = _stopped.SafeWaitHandle; // If an OS thread is terminated and its Thread object is resurrected, waitHandle may be finalized and closed if (waitHandle.IsClosed) { return true; } // Prevent race condition with the finalizer try { waitHandle.DangerousAddRef(); } catch (ObjectDisposedException) { return true; } try { return _stopped.WaitOne(millisecondsTimeout); } finally { waitHandle.DangerousRelease(); } } private bool CreateThread(GCHandle thisThreadHandle) { // Create the Stop event before starting the thread to make sure // it is ready to be signaled at thread shutdown time. // This also avoids OOM after creating the thread. _stopped = new ManualResetEvent(false); if (!Interop.Sys.RuntimeThread_CreateThread((IntPtr)_maxStackSize, AddrofIntrinsics.AddrOf<Interop.Sys.ThreadProc>(ThreadEntryPoint), (IntPtr)thisThreadHandle)) { return false; } // CoreCLR ignores OS errors while setting the priority, so do we SetPriorityLive(_priority); return true; } /// <summary> /// This is an entry point for managed threads created by application /// </summary> [NativeCallable] private static IntPtr ThreadEntryPoint(IntPtr parameter) { StartThread(parameter); return IntPtr.Zero; } public void Interrupt() => WaitSubsystem.Interrupt(this); internal static void UninterruptibleSleep0() => WaitSubsystem.UninterruptibleSleep0(); private static void SleepInternal(int millisecondsTimeout) => WaitSubsystem.Sleep(millisecondsTimeout); internal const bool ReentrantWaitsEnabled = false; internal static void SuppressReentrantWaits() { throw new PlatformNotSupportedException(); } internal static void RestoreReentrantWaits() { throw new PlatformNotSupportedException(); } } }
shrah/corert
src/System.Private.CoreLib/src/Internal/Runtime/Augments/RuntimeThread.Unix.cs
C#
mit
5,746
@charset "UTF-8"; .ui-widget { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Segoe UI Symbol"; font-size: 1em; } .ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Segoe UI Symbol"; font-size: 1em; } .ui-widget :active { outline: none; } .ui-widget-content { border: 1px solid #d4d4d4; background: #fafafa; color: #081c22; } .ui-widget-content a { color: #081c22; } .ui-widget-header { border: 1px solid #2790b0; background: #2790b0; color: #ffffff; font-weight: 500; } .ui-widget-header a { color: #ffffff; } .ui-widget-overlay { background: #666666; opacity: .50; filter: Alpha(Opacity=50); } .ui-widget-header .ui-state-default, .ui-widget-content .ui-state-default, .ui-state-default { border: 1px solid #d4d4d4; background: #fafafa; color: #081c22; } .ui-widget-header .ui-state-default a, .ui-widget-content .ui-state-default a, .ui-state-default a { color: #081c22; } .ui-widget-header .ui-state-active, .ui-widget-content .ui-state-active, .ui-state-active { border-color: #b8ccd2; background: #cad7dc; color: #081c22; } .ui-widget-header .ui-state-active a, .ui-widget-content .ui-state-active a, .ui-state-active a { color: #081c22; } .ui-widget-header .ui-state-highlight, .ui-widget-content .ui-state-highlight, .ui-state-highlight { border-color: #eecc00; background: #eecc00; color: #081c22; } .ui-widget-header .ui-state-highlight a, .ui-widget-content .ui-state-highlight a, .ui-state-highlight a { color: #081c22; } .ui-widget-header .ui-state-focus, .ui-widget-content .ui-state-focus, .ui-state-focus { border-color: #eecc00; background: #eecc00; color: #081c22; } .ui-widget-header .ui-state-focus a, .ui-widget-content .ui-state-focus a, .ui-state-focus a { color: #081c22; } .ui-widget-header .ui-state-error, .ui-widget-content .ui-state-error, .ui-state-error { border-color: #ec4e4e; background: #ec4e4e; color: #ffffff; } .ui-widget-header .ui-state-error a, .ui-widget-content .ui-state-error a, .ui-state-error a { color: #ffffff; } .ui-state-disabled, .ui-widget:disabled { opacity: 0.35; filter: Alpha(Opacity=35); background-image: none; cursor: default !important; } .ui-state-disabled *, .ui-widget:disabled * { cursor: default !important; } /* Forms */ .ui-inputtext { background: #ffffff; color: #333333; } .ui-inputtext:enabled:hover { border-color: #d4d4d4; } .ui-inputtext.ui-state-focus, .ui-inputtext:focus { outline: 0 none; border-color: #eecc00; -moz-box-shadow: 0px 0px 5px #eecc00; -webkit-box-shadow: 0px 0px 5px #eecc00; box-shadow: 0px 0px 5px #eecc00; } .ui-autocomplete .ui-autocomplete-multiple-container:not(.ui-state-disabled):hover { border-color: #d4d4d4; } .ui-autocomplete .ui-autocomplete-multiple-container:not(.ui-state-disabled).ui-state-focus { border-color: #eecc00; } .ui-chips > ul:not(.ui-state-disabled):hover { border-color: #d4d4d4; } .ui-chips > ul:not(.ui-state-disabled).ui-state-focus { border-color: #eecc00; } .ui-button:focus, .ui-button:enabled:hover { outline: 0 none; border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-button:focus a, .ui-button:enabled:hover a { color: #081c22; } .ui-button:enabled:active { border-color: #b8ccd2; background: #cad7dc; color: #081c22; } .ui-chkbox-box:not(.ui-state-disabled):not(.ui-state-active):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-chkbox-box:not(.ui-state-disabled):not(.ui-state-active):hover a { color: #081c22; } .ui-radiobutton-box:not(.ui-state-disabled):not(.ui-state-active):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-radiobutton-box:not(.ui-state-disabled):not(.ui-state-active):hover a { color: #081c22; } .ui-dropdown:not(.ui-state-disabled):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-dropdown:not(.ui-state-disabled):hover a { color: #081c22; } .ui-dropdown-panel .ui-dropdown-item:not(.ui-state-highlight):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-dropdown-panel .ui-dropdown-item:not(.ui-state-highlight):hover a { color: #081c22; } .ui-listbox .ui-listbox-header .ui-listbox-filter-container .fa { color: #333333; } .ui-listbox .ui-listbox-item:not(.ui-state-highlight):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-listbox .ui-listbox-item:not(.ui-state-highlight):hover a { color: #081c22; } .ui-multiselect:not(.ui-state-disabled):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-multiselect:not(.ui-state-disabled):hover a { color: #081c22; } .ui-multiselect-panel .ui-multiselect-item:not(.ui-state-highlight):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-multiselect-panel .ui-multiselect-item:not(.ui-state-highlight):hover a { color: #081c22; } .ui-multiselect-panel .ui-multiselect-close { color: #ffffff; } .ui-multiselect-panel .ui-multiselect-filter-container .fa { color: #333333; } .ui-spinner:not(.ui-state-disabled) .ui-spinner-button:enabled:hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-spinner:not(.ui-state-disabled) .ui-spinner-button:enabled:hover a { color: #081c22; } .ui-spinner:not(.ui-state-disabled) .ui-spinner-button:enabled:active { border-color: #b8ccd2; background: #cad7dc; color: #081c22; } .ui-selectbutton .ui-button:not(.ui-state-disabled):not(.ui-state-active):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-selectbutton .ui-button:not(.ui-state-disabled):not(.ui-state-active):hover a { color: #081c22; } .ui-togglebutton:not(.ui-state-disabled):not(.ui-state-active):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-togglebutton:not(.ui-state-disabled):not(.ui-state-active):hover a { color: #081c22; } .ui-paginator a:not(.ui-state-disabled):not(.ui-state-active):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-paginator a:not(.ui-state-disabled):not(.ui-state-active):hover a { color: #081c22; } .ui-datatable .ui-rowgroup-header a { color: #ffffff; } .ui-datatable .ui-sortable-column:not(.ui-state-active):hover { background: #eaeaea; color: #081c22; } .ui-datatable .ui-row-toggler { color: #081c22; } .ui-datatable tbody.ui-datatable-hoverable-rows > tr.ui-widget-content:not(.ui-state-highlight):hover { cursor: pointer; background: #eaeaea; color: #081c22; } .ui-orderlist .ui-orderlist-item:not(.ui-state-highlight):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-orderlist .ui-orderlist-item:not(.ui-state-highlight):hover a { color: #081c22; } .ui-picklist .ui-picklist-item:not(.ui-state-highlight):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-picklist .ui-picklist-item:not(.ui-state-highlight):hover a { color: #081c22; } .ui-tree .ui-treenode-content.ui-treenode-selectable .ui-treenode-label:not(.ui-state-highlight):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-tree .ui-treenode-content.ui-treenode-selectable .ui-treenode-label:not(.ui-state-highlight):hover a { color: #081c22; } .ui-tree.ui-tree-horizontal .ui-treenode-content.ui-treenode-selectable .ui-treenode-label:not(.ui-state-highlight):hover { background-color: inherit; color: inherit; } .ui-tree.ui-tree-horizontal .ui-treenode-content.ui-treenode-selectable:not(.ui-state-highlight):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-tree.ui-tree-horizontal .ui-treenode-content.ui-treenode-selectable:not(.ui-state-highlight):hover a { color: #081c22; } .ui-treetable .ui-treetable-row.ui-treetable-row-selectable:not(.ui-state-highlight):hover { background: #eaeaea; color: #081c22; } .ui-accordion .ui-accordion-header:not(.ui-state-active):not(.ui-state-disabled):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-accordion .ui-accordion-header:not(.ui-state-active):not(.ui-state-disabled):hover a { color: #081c22; } .ui-fieldset.ui-fieldset-toggleable .ui-fieldset-legend:hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-fieldset.ui-fieldset-toggleable .ui-fieldset-legend:hover a { color: #081c22; } .ui-panel .ui-panel-titlebar .ui-panel-titlebar-icon:hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-panel .ui-panel-titlebar .ui-panel-titlebar-icon:hover a { color: #081c22; } .ui-tabview .ui-tabview-nav li:not(.ui-state-active):not(.ui-state-disabled):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-tabview .ui-tabview-nav li:not(.ui-state-active):not(.ui-state-disabled):hover a { color: #081c22; } .ui-dialog .ui-dialog-titlebar-icon { color: #ffffff; } .ui-dialog .ui-dialog-titlebar-icon:hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-dialog .ui-dialog-titlebar-icon:hover a { color: #081c22; } .ui-overlaypanel .ui-overlaypanel-close:hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-overlaypanel .ui-overlaypanel-close:hover a { color: #081c22; } .ui-inplace .ui-inplace-display:hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-inplace .ui-inplace-display:hover a { color: #081c22; } .ui-breadcrumb a { color: #ffffff; } .ui-menu .ui-menuitem .ui-menuitem-link { color: #081c22; } .ui-menu .ui-menuitem .ui-menuitem-link:hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; border-color: transparent; } .ui-menu .ui-menuitem .ui-menuitem-link:hover a { color: #081c22; } .ui-menu .ui-menuitem.ui-menuitem-active > .ui-menuitem-link { border-color: #d4d4d4; background: #eaeaea; color: #081c22; border-color: transparent; } .ui-menu .ui-menuitem.ui-menuitem-active > .ui-menuitem-link a { color: #081c22; } .ui-tabmenu .ui-tabmenu-nav li:not(.ui-state-active):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-tabmenu .ui-tabmenu-nav li:not(.ui-state-active):hover a { color: #081c22; } .ui-steps .ui-steps-item:not(.ui-state-highlight):not(.ui-state-disabled):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-steps .ui-steps-item:not(.ui-state-highlight):not(.ui-state-disabled):hover a { color: #081c22; } .ui-panelmenu .ui-panelmenu-header:not(.ui-state-active):hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-panelmenu .ui-panelmenu-header:not(.ui-state-active):hover a { color: #081c22; } .ui-panelmenu .ui-panelmenu-header:not(.ui-state-active):hover a { color: #081c22; } .ui-panelmenu .ui-panelmenu-header.ui-state-active a { color: #081c22; } .ui-panelmenu .ui-panelmenu-content .ui-menuitem-link { color: #081c22; } .ui-panelmenu .ui-panelmenu-content .ui-menuitem-link:hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; border-color: transparent; } .ui-panelmenu .ui-panelmenu-content .ui-menuitem-link:hover a { color: #081c22; } .ui-datepicker .ui-datepicker-header a { color: #ffffff; } .ui-datepicker .ui-datepicker-header a:hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-datepicker .ui-datepicker-header a:hover a { color: #081c22; } .ui-datepicker .ui-datepicker-calendar td:not(.ui-state-disabled) a:hover { border-color: #d4d4d4; background: #eaeaea; color: #081c22; } .ui-datepicker .ui-datepicker-calendar td:not(.ui-state-disabled) a:hover a { color: #081c22; } .fc .fc-toolbar .fc-prev-button .ui-icon-circle-triangle-w { margin-top: .3em; background: none !important; display: inline-block; font: normal normal normal 14px/1 FontAwesome; font-size: inherit; text-rendering: auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-indent: 0px !important; text-align: center; } .fc .fc-toolbar .fc-prev-button .ui-icon-circle-triangle-w:before { content: ""; } .fc .fc-toolbar .fc-next-button .ui-icon-circle-triangle-e { margin-top: .3em; background: none !important; display: inline-block; font: normal normal normal 14px/1 FontAwesome; font-size: inherit; text-rendering: auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-indent: 0px !important; text-align: center; } .fc .fc-toolbar .fc-next-button .ui-icon-circle-triangle-e:before { content: ""; } .ui-rating a { color: #333333; } /* Validation */ .ui-inputtext.ng-dirty.ng-invalid, p-dropdown.ng-dirty.ng-invalid > .ui-dropdown, p-autocomplete.ng-dirty.ng-invalid > .ui-autocomplete > .ui-inputtext, p-calendar.ng-dirty.ng-invalid > .ui-inputtext, p-chips.ng-dirty.ng-invalid > .ui-inputtext, p-inputmask.ng-dirty.ng-invalid > .ui-inputtext, p-checkbox.ng-dirty.ng-invalid .ui-chkbox-box, p-radiobutton.ng-dirty.ng-invalid .ui-radiobutton-box, p-inputswitch.ng-dirty.ng-invalid .ui-inputswitch, p-listbox.ng-dirty.ng-invalid .ui-inputtext, p-multiselect.ng-dirty.ng-invalid > .ui-multiselect, p-spinner.ng-dirty.ng-invalid > .ui-inputtext, p-selectbutton.ng-dirty.ng-invalid .ui-button, p-togglebutton.ng-dirty.ng-invalid .ui-button { border-bottom-color: #ec4e4e; } /* Cornering */ .ui-corner-tl { -moz-border-radius-topleft: 2px; -webkit-border-top-left-radius: 2px; border-top-left-radius: 2px; } .ui-corner-tr { -moz-border-radius-topright: 2px; -webkit-border-top-right-radius: 2px; border-top-right-radius: 2px; } .ui-corner-bl { -moz-border-radius-bottomleft: 2px; -webkit-border-bottom-left-radius: 2px; border-bottom-left-radius: 2px; } .ui-corner-br { -moz-border-radius-bottomright: 2px; -webkit-border-bottom-right-radius: 2px; border-bottom-right-radius: 2px; } .ui-corner-top { -moz-border-radius-topleft: 2px; -webkit-border-top-left-radius: 2px; border-top-left-radius: 2px; -moz-border-radius-topright: 2px; -webkit-border-top-right-radius: 2px; border-top-right-radius: 2px; } .ui-corner-bottom { -moz-border-radius-bottomleft: 2px; -webkit-border-bottom-left-radius: 2px; border-bottom-left-radius: 2px; -moz-border-radius-bottomright: 2px; -webkit-border-bottom-right-radius: 2px; border-bottom-right-radius: 2px; } .ui-corner-right { -moz-border-radius-topright: 2px; -webkit-border-top-right-radius: 2px; border-top-right-radius: 2px; -moz-border-radius-bottomright: 2px; -webkit-border-bottom-right-radius: 2px; border-bottom-right-radius: 2px; } .ui-corner-left { -moz-border-radius-topleft: 2px; -webkit-border-top-left-radius: 2px; border-top-left-radius: 2px; -moz-border-radius-bottomleft: 2px; -webkit-border-bottom-left-radius: 2px; border-bottom-left-radius: 2px; } .ui-corner-all { -moz-border-radius: 2px; -webkit-border-radius: 2px; border-radius: 2px; }
fusion-ffn/primeng
resources/themes/ludvig/theme.css
CSS
mit
15,381
<?php defined('BX_DOL') or die('hack attempt'); /** * Copyright (c) UNA, Inc - https://una.io * MIT License - https://opensource.org/licenses/MIT * * @defgroup UnaCore UNA Core * @{ */ bx_import('BxDolAcl'); define('BX_DOL_VOTE_TYPE_STARS', 'stars'); define('BX_DOL_VOTE_TYPE_LIKES', 'likes'); define('BX_DOL_VOTE_USAGE_BLOCK', 'block'); define('BX_DOL_VOTE_USAGE_INLINE', 'inline'); define('BX_DOL_VOTE_USAGE_DEFAULT', BX_DOL_VOTE_USAGE_BLOCK); /** * Vote for any content * * Related classes: * - BxDolVoteQuery - vote database queries * - BxBaseVote - vote base representation * - BxTemplVote - custom template representation * * AJAX vote for any content. Stars and Plus based representations are supported. * * To add vote section to your feature you need to add a record to 'sys_objects_vote' table: * * - ID - autoincremented id for internal usage * - Name - your unique module name, with vendor prefix, lowercase and spaces are underscored * - TableMain - table name where summary votigs are stored * - TableTrack - table name where each vote is stored * - PostTimeout - number of seconds to not allow duplicate vote * - MinValue - min vote value, 1 by default * - MaxValue - max vote value, 5 by default * - IsUndo - is Undo enabled for Plus based votes * - IsOn - is this vote object enabled * - TriggerTable - table to be updated upon each vote * - TriggerFieldId - TriggerTable table field with unique record id, primary key * - TriggerFieldRate - TriggerTable table field with average rate * - TriggerFieldRateCount - TriggerTable table field with votes count * - ClassName - your custom class name, if you overrride default class * - ClassFile - your custom class path * * You can refer to BoonEx modules for sample record in this table. * * * * @section example Example of usage: * To get Star based vote you need to have different values for MinValue and MaxValue (for example 1 and 5) * and IsUndo should be equal to 0. To get Plus(Like) based vote you need to have equal values * for MinValue and MaxValue (for example 1) and IsUndo should be equal to 1. After filling the other * paramenters in the table you can show vote in any place, using the following code: * @code * $o = BxDolVote::getObjectInstance('system object name', $iYourEntryId); * if (!$o->isEnabled()) return ''; * echo $o->getElementBlock(); * @endcode * * * @section acl Memberships/ACL: * - vote * * * * @section alerts Alerts: * Alerts type/unit - every module has own type/unit, it equals to ObjectName. * The following alerts are rised: * * - rate - comment was posted * - $iObjectId - entry id * - $iSenderId - rater user id * - $aExtra['rate'] - rate * */ class BxDolVote extends BxDolObject { protected $_bLike = true; protected $_sType = BX_DOL_VOTE_TYPE_LIKES; protected function __construct($sSystem, $iId, $iInit = true, $oTemplate = false) { parent::__construct($sSystem, $iId, $iInit, $oTemplate); if(empty($this->_sSystem)) return; $this->_oQuery = new BxDolVoteQuery($this); $this->_bLike = $this->isLikeMode(); $this->_sType = $this->_bLike ? BX_DOL_VOTE_TYPE_LIKES : BX_DOL_VOTE_TYPE_STARS; } /** * get votes object instanse * @param $sSys vote object name * @param $iId associated content id, where vote is available * @param $iInit perform initialization * @return null on error, or ready to use class instance */ public static function getObjectInstance($sSys, $iId, $iInit = true, $oTemplate = false) { if(isset($GLOBALS['bxDolClasses']['BxDolVote!' . $sSys . $iId])) return $GLOBALS['bxDolClasses']['BxDolVote!' . $sSys . $iId]; $aSystems = self::getSystems(); if(!isset($aSystems[$sSys])) return null; $sClassName = 'BxTemplVote'; if(!empty($aSystems[$sSys]['class_name'])) { $sClassName = $aSystems[$sSys]['class_name']; if(!empty($aSystems[$sSys]['class_file'])) require_once(BX_DIRECTORY_PATH_ROOT . $aSystems[$sSys]['class_file']); } $o = new $sClassName($sSys, $iId, $iInit, $oTemplate); return ($GLOBALS['bxDolClasses']['BxDolVote!' . $sSys . $iId] = $o); } public static function &getSystems() { if(!isset($GLOBALS['bx_dol_vote_systems'])) $GLOBALS['bx_dol_vote_systems'] = BxDolDb::getInstance()->fromCache('sys_objects_vote', 'getAllWithKey', ' SELECT `ID` as `id`, `Name` AS `name`, `TableMain` AS `table_main`, `TableTrack` AS `table_track`, `PostTimeout` AS `post_timeout`, `MinValue` AS `min_value`, `MaxValue` AS `max_value`, `IsUndo` AS `is_undo`, `IsOn` AS `is_on`, `TriggerTable` AS `trigger_table`, `TriggerFieldId` AS `trigger_field_id`, `TriggerFieldAuthor` AS `trigger_field_author`, `TriggerFieldRate` AS `trigger_field_rate`, `TriggerFieldRateCount` AS `trigger_field_count`, `ClassName` AS `class_name`, `ClassFile` AS `class_file` FROM `sys_objects_vote`', 'name'); return $GLOBALS['bx_dol_vote_systems']; } public function isUndo() { return (int)$this->_aSystem['is_undo'] == 1; } public function isLikeMode() { $iMinValue = $this->getMinValue(); $iMaxValue = $this->getMaxValue(); return $iMinValue == $iMaxValue; } public function getMinValue() { return (int)$this->_aSystem['min_value']; } public function getMaxValue() { return (int)$this->_aSystem['max_value']; } public function getObjectAuthorId($iObjectId = 0) { if(empty($this->_aSystem['trigger_field_author'])) return 0; return $this->_oQuery->getObjectAuthorId($iObjectId ? $iObjectId : $this->getId()); } /** * Interface functions for outer usage */ public function getStatCounter() { $aVote = $this->_oQuery->getVote($this->getId()); return $aVote['count']; } public function getStatRate() { $aVote = $this->_oQuery->getVote($this->getId()); return $aVote['rate']; } /** * Actions functions */ public function actionVote() { if(!$this->isEnabled()) { echoJson(array('code' => 1)); return; } $iObjectId = $this->getId(); $iObjectAuthorId = $this->getObjectAuthorId($iObjectId); $iAuthorId = $this->_getAuthorId(); $iAuthorIp = $this->_getAuthorIp(); $bUndo = $this->isUndo(); $bLikeMode = $this->isLikeMode(); $bVoted = $this->isPerformed($iObjectId, $iAuthorId); $bPerformUndo = $bVoted && $bUndo ? true : false; if(!$bPerformUndo && !$this->isAllowedVote(true)) { echoJson(array('code' => 2, 'msg' => $this->msgErrAllowedVote())); return; } if((!$bLikeMode && !$this->_oQuery->isPostTimeoutEnded($iObjectId, $iAuthorIp)) || ($bLikeMode && $bVoted && !$bUndo)) { echoJson(array('code' => 3, 'msg' => _t('_vote_err_duplicate_vote'))); return; } $iValue = bx_get('value'); if($iValue === false) { echoJson(array('code' => 4)); return; } $iValue = bx_process_input($iValue, BX_DATA_INT); $iMinValue = $this->getMinValue(); if($iValue < $iMinValue) $iValue = $iMinValue; $iMaxValue = $this->getMaxValue(); if($iValue > $iMaxValue) $iValue = $iMaxValue; $iId = $this->_oQuery->putVote($iObjectId, $iAuthorId, $iAuthorIp, $iValue, $bPerformUndo); if($iId === false) { echoJson(array('code' => 5)); return; } $this->_trigger(); $oZ = new BxDolAlerts($this->_sSystem, ($bPerformUndo ? 'un' : '') . 'doVote', $iObjectId, $iAuthorId, array('vote_id' => $iId, 'vote_author_id' => $iAuthorId, 'object_author_id' => $iObjectAuthorId, 'value' => $iValue)); $oZ->alert(); $oZ = new BxDolAlerts('vote', ($bPerformUndo ? 'un' : '') . 'do', $iId, $iAuthorId, array('object_system' => $this->_sSystem, 'object_id' => $iObjectId, 'object_author_id' => $iObjectAuthorId, 'value' => $iValue)); $oZ->alert(); $aVote = $this->_oQuery->getVote($iObjectId); echoJson(array( 'code' => 0, 'rate' => $aVote['rate'], 'count' => $aVote['count'], 'countf' => (int)$aVote['count'] > 0 ? $this->_getLabelCounter($aVote['count']) : '', 'label_icon' => $bLikeMode ? $this->_getIconDoLike(!$bVoted) : '', 'label_title' => $bLikeMode ? _t($this->_getTitleDoLike(!$bVoted)) : '', 'disabled' => !$bVoted && !$bUndo, )); } public function actionGetVotedBy() { if (!$this->isEnabled()) return ''; return $this->_getVotedBy(); } /** * Permissions functions */ public function isAllowedVote($isPerformAction = false) { if(isAdmin()) return true; return $this->checkAction('vote', $isPerformAction); } public function msgErrAllowedVote() { return $this->checkActionErrorMsg('vote'); } /** * Internal functions */ protected function _getIconDoLike($bVoted) { return $bVoted && $this->isUndo() ? 'thumbs-down' : 'thumbs-up'; } protected function _getTitleDoLike($bVoted) { return $bVoted && $this->isUndo() ? '_vote_do_unlike' : '_vote_do_like'; } protected function _getTitleDoBy() { return '_vote_do_by'; } } /** @} */
camperjz/trident
upgrade/files/9.0.0.B5-9.0.0.RC1/files/inc/classes/BxDolVote.php
PHP
mit
10,009
/* Copyright (c) 2007-2013 Dovecot authors, see the included COPYING file */ #include "test-lib.h" #include "primes.h" void test_primes(void) { unsigned int i, j, num; bool success; success = primes_closest(0) > 0; for (num = 1; num < 1024; num++) { if (primes_closest(num) < num) success = FALSE; } for (i = 10; i < 32; i++) { num = (1U << i) - 100; for (j = 0; j < 200; j++, num++) { if (primes_closest(num) < num) success = FALSE; } } test_out("primes_closest()", success); }
damoxc/dovecot
src/lib/test-primes.c
C
mit
508
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>WDECAccountInfo Class Reference</title> <link rel="stylesheet" href="../css/style.css"> <link rel="stylesheet" href="../css/prism.css"> <script src="../js/jquery.min.js"></script> <script src="../js/format.js"></script> <script src="../js/prism.js" data-manual></script> <script> jQuery.noConflict(); jQuery( document ).ready(function( $ ) { $("pre code").each(function(i, block) { $(this).addClass("language-objectivec") $(this).formatObjectiveC(); }); Prism.highlightAll() }); </script> <meta name="viewport" content="initial-scale=1, maximum-scale=1.4"> <meta name="generator" content="appledoc 2.2.1 (build 1333)"> </head> <body class="appledoc"> <header> <div class="container" class="hide-in-xcode"> <h1 id="library-title"> <a href="../index.html">WDeCom </a> </h1> <p id="developer-home"> <a href="../index.html">Wirecard AG</a> </p> </div> </header> <aside> <div class="container"> <nav> <ul id="header-buttons" role="toolbar"> <li><a href="../index.html">Index</a></li> <li><a href="../hierarchy.html">Hierarchy</a></li> <li id="on-this-page" role="navigation"> <label> On This Page <div class="chevron"> <div class="chevy chevron-left"></div> <div class="chevy chevron-right"></div> </div> <select id="jump-to"> <option value="top">Jump To&#133;</option> <option value="overview">Overview</option> <option value="tasks">Tasks</option> <optgroup label="Properties"> <option value="//api/name/authenticationMethod">authenticationMethod</option> <option value="//api/name/authenticationTimestamp">authenticationTimestamp</option> <option value="//api/name/cardCreationDate">cardCreationDate</option> <option value="//api/name/cardTransactionsLastDay">cardTransactionsLastDay</option> <option value="//api/name/challengeIndicator">challengeIndicator</option> <option value="//api/name/creationDate">creationDate</option> <option value="//api/name/passwordChangeDate">passwordChangeDate</option> <option value="//api/name/purchasesLastSixMonths">purchasesLastSixMonths</option> <option value="//api/name/shippingAddressFirstUse">shippingAddressFirstUse</option> <option value="//api/name/suspiciousActivity">suspiciousActivity</option> <option value="//api/name/transactionsLastDay">transactionsLastDay</option> <option value="//api/name/transactionsLastYear">transactionsLastYear</option> <option value="//api/name/updateDate">updateDate</option> </optgroup> </select> </label> </li> </ul> </nav> </div> </aside> <article> <div id="overview_contents" class="container"> <div id="content"> <main role="main"> <h1 class="title">WDECAccountInfo Class Reference</h1> <div class="section section-specification"><table cellspacing="0"><tbody> <tr> <th>Inherits from</th> <td>NSObject</td> </tr><tr> <th>Declared in</th> <td>WDECAccountInfo.h</td> </tr> </tbody></table></div> <div class="section section-tasks"> <a title="Tasks" name="tasks"></a> <div class="task-list"> <div class="section-method"> <a name="//api/name/creationDate" title="creationDate"></a> <h3 class="method-title"><code><a href="#//api/name/creationDate">&nbsp;&nbsp;creationDate</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Date that the cardholder opened the account with the 3DS Requestor. Date format = YYYYMMDD.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (strong, nonatomic, nullable) NSDate *creationDate</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/updateDate" title="updateDate"></a> <h3 class="method-title"><code><a href="#//api/name/updateDate">&nbsp;&nbsp;updateDate</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Date that the cardholder’s account with the 3DS Requestor was last changed. Including Billing or Shipping address, new payment account, or new user(s) added. Date format = YYYYMMDD.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (strong, nonatomic, nullable) NSDate *updateDate</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/passwordChangeDate" title="passwordChangeDate"></a> <h3 class="method-title"><code><a href="#//api/name/passwordChangeDate">&nbsp;&nbsp;passwordChangeDate</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Date that cardholder’s account with the 3DS Requestor had a password change or account reset. Date format must be YYYYMMDD.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (strong, nonatomic, nullable) NSDate *passwordChangeDate</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/shippingAddressFirstUse" title="shippingAddressFirstUse"></a> <h3 class="method-title"><code><a href="#//api/name/shippingAddressFirstUse">&nbsp;&nbsp;shippingAddressFirstUse</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Date when the shipping address used for this transaction was first used with the 3DS Requestor. Date format must be YYYYMMDD.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (strong, nonatomic, nullable) NSDate *shippingAddressFirstUse</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/transactionsLastDay" title="transactionsLastDay"></a> <h3 class="method-title"><code><a href="#//api/name/transactionsLastDay">&nbsp;&nbsp;transactionsLastDay</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous 24 hours.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (assign, nonatomic) NSInteger transactionsLastDay</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/transactionsLastYear" title="transactionsLastYear"></a> <h3 class="method-title"><code><a href="#//api/name/transactionsLastYear">&nbsp;&nbsp;transactionsLastYear</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Number of transactions (successful and abandoned) for this cardholder account with the 3DS Requestor across all payment accounts in the previous year.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (assign, nonatomic) NSInteger transactionsLastYear</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/cardTransactionsLastDay" title="cardTransactionsLastDay"></a> <h3 class="method-title"><code><a href="#//api/name/cardTransactionsLastDay">&nbsp;&nbsp;cardTransactionsLastDay</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Number of Add Card attempts in the last 24 hours.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (assign, nonatomic) NSInteger cardTransactionsLastDay</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/purchasesLastSixMonths" title="purchasesLastSixMonths"></a> <h3 class="method-title"><code><a href="#//api/name/purchasesLastSixMonths">&nbsp;&nbsp;purchasesLastSixMonths</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Number of purchases with this cardholder account during the previous six months.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (assign, nonatomic) NSInteger purchasesLastSixMonths</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/suspiciousActivity" title="suspiciousActivity"></a> <h3 class="method-title"><code><a href="#//api/name/suspiciousActivity">&nbsp;&nbsp;suspiciousActivity</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Indicates whether the 3DS Requestor has experienced suspicious activity(including previous fraud) on the cardholder account. Accepted values are: true -> No suspicious activity has been observed false -> Suspicious activity has been observed</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (assign, nonatomic) BOOL suspiciousActivity</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/cardCreationDate" title="cardCreationDate"></a> <h3 class="method-title"><code><a href="#//api/name/cardCreationDate">&nbsp;&nbsp;cardCreationDate</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Date that the payment account was enrolled in the cardholder’s account with the 3DS Requestor. Date format must be YYYYMMDD.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (strong, nonatomic, nullable) NSDate *cardCreationDate</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/authenticationMethod" title="authenticationMethod"></a> <h3 class="method-title"><code><a href="#//api/name/authenticationMethod">&nbsp;&nbsp;authenticationMethod</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Indicates the type of the cardholder login in the merchant’s shop by the <a href="../Constants/WDECAuthenticationMethod.html">WDECAuthenticationMethod</a> enum.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (assign, nonatomic) WDECAuthenticationMethod authenticationMethod</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/authenticationTimestamp" title="authenticationTimestamp"></a> <h3 class="method-title"><code><a href="#//api/name/authenticationTimestamp">&nbsp;&nbsp;authenticationTimestamp</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Date and time (UTC) of the consumer login in the merchant’s shop. Date Format: YYYY-MM-DDThh:mm:ssZ. For guest checkout, the timestamp is now.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (strong, nonatomic, nullable) NSDate *authenticationTimestamp</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/challengeIndicator" title="challengeIndicator"></a> <h3 class="method-title"><code><a href="#//api/name/challengeIndicator">&nbsp;&nbsp;challengeIndicator</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Indicates whether a challenge is requested for this transaction with the 3DS Requestor. If the element is not provided, the ACS will interpret this as WDECChallengeIndicatorNoPreference.</p> </div> <div class="method-subsection method-declaration"><pre><code>@property (assign, nonatomic) WDECChallengeIndicator challengeIndicator</code></pre></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">WDECAccountInfo.h</code></p> </div> </div> </div> </div> </div> </div> </main> <footer> <div class="footer-copyright"> <p class="copyright">Copyright &copy; 2020 Wirecard AG. All rights reserved. Updated: 2020-05-26</p> <p class="generator">Generated by <a href="http://appledoc.gentlebytes.com">appledoc 2.2.1 (build 1333)</a>.</p> </div> </footer> </div> </div> </article> <script src="../js/script.js"></script> </body> </html>
wirecard/paymentSDK-iOS
docs/api/4.4.1/Classes/WDECAccountInfo.html
HTML
mit
16,408
#ifndef DATASTREAM_H #define DATASTREAM_H #include <stdint.h> #define nofree false class datastream { public: datastream(bool del = true, int initSize = 0x100); virtual ~datastream(); datastream& operator<< (uint32_t data); datastream& operator<< (uint16_t data); datastream& operator<< (uint8_t data); datastream& operator<< (float data); datastream& operator<< (double data); /*datastream& operator<< (int32_t &data) { return operator<<((uint32_t&)data); } datastream& operator<< (int16_t &data) { return operator<<((uint16_t&)data); } datastream& operator<< (int8_t &data) { return operator<<((uint8_t&)data); }*/ datastream& operator<< (const char *data); datastream& operator= (const datastream &paketti); int Length() const { return size; } const uint8_t *GetData() const { return buf; } const uint8_t *GetEnd() const { return GetData() + Length(); } void Insert(const void *buf, int length, int pos); void Append(const void *buf, int len); void Seek(int amount); void Clear(); protected: private: void ExpBuf(int newSize); unsigned char *buf; int size; int datalen; bool del; }; #endif // DATASTREAM_H
SCMapsAndMods/teippi
src/datastream.h
C
mit
1,320
IntlMessageFormat.__addLocaleData({"locale":"teo"}); IntlMessageFormat.__addLocaleData({"locale":"teo-KE","parentLocale":"teo"});
joeyparrish/cdnjs
ajax/libs/intl-messageformat/3.0.0/locale-data/teo.js
JavaScript
mit
130
version https://git-lfs.github.com/spec/v1 oid sha256:01a0b9b010be5c2601c0de9d5752ef6f1a3c913dcb19be10299e63a26649d86b size 1189
yogeshsaroya/new-cdnjs
ajax/libs/insightjs/1.0.1/insight.min.css
CSS
mit
129
/** * 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/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', 'onError'], visibilityKey = "durandal-visibility-data", composeBindings = ['compose:']; function onError(context, error, element) { try { if (context.onError) { try { context.onError(error, element); } catch (e) { system.error(e); } } else { system.error(error); } } finally { endComposition(context, element, true); } } 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(context, element, error) { compositionCount--; if(compositionCount === 0) { var callBacks = compositionCompleteCallbacks; compositionCompleteCallbacks = []; if (!error) { setTimeout(function () { var i = callBacks.length; while (i--) { try { callBacks[i](); } catch (e) { onError(context, e, element); } } }, 1); } } cleanUp(context); } function cleanUp(context){ delete context.activeView; delete context.viewElements; } function tryActivate(context, successCallback, skipActivation, element) { 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) { onError(context, reason, element); successCallback(); }); } else if(result || result === undefined) { successCallback(); } else { endComposition(context, element); } } catch(e){ onError(context, e, element); } } else { successCallback(); } } function triggerAttach(context, element) { 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){ onError(context, e2, element); } }); } }catch(e){ onError(context, e, element); } } 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); var standardParts = composition.getParts(context.child); for (var partId in replacementParts) { var toReplace = standardParts[partId]; if (!toReplace) { toReplace = $('[data-part="' + partId + '"]', context.child).get(0); if (!toReplace) { system.log('Could not find part to override: ' + partId); continue; } } toReplace.parentNode.replaceChild(replacementParts[partId], toReplace); } } 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) { var displayStyle = ko.utils.domData.get(view, visibilityKey); view.style.display = displayStyle === 'none' ? 'block' : displayStyle; } 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) { 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], id; if (element.getAttribute) { id = element.getAttribute(partAttributeName); if (id) { parts[id] = element; } if (element.hasChildNodes() && !hasComposition(element)) { composition.getParts(element.childNodes, parts); } } } return parts; }, cloneNodes:cloneNodes, finalize: function (context, element) { if(context.transition === undefined) { context.transition = this.defaultTransitionName; } if(!context.child && !context.activeView){ if (!context.cacheViews) { ko.virtualElements.emptyNode(context.parent); } context.triggerAttach(context, element); endComposition(context, element); } 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); }else{ hide(context.activeView); } } if (context.child) { show(context.child); } context.triggerAttach(context, element); endComposition(context, element); }); }).fail(function(err){ onError(context, 'Failed to load transition (' + transitionModuleId + '). Details: ' + err.message, element); }); } 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(context, element); endComposition(context, element); } }, bindAndShow: function (child, element, context, skipActivation) { context.child = child; context.parent.__composition_context = context; if (context.cacheViews) { context.composingNewView = (ko.utils.arrayIndexOf(context.viewElements, child) == -1); } else { context.composingNewView = true; } tryActivate(context, function () { if (context.parent.__composition_context == context) { try { delete context.parent.__composition_context; } catch(e) { context.parent.__composition_context = undefined; } 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, context.as); } } 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, element, context, true); }); return; } if(context.parts){ replaceParts(context); } hide(child); ko.virtualElements.prepend(context.parent, child); binder.bind(modelToBind, child); } } composition.finalize(context, element); } else { endComposition(context, element); } }, skipActivation, element); }, /** * 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: !activatorPresent }; } return settings; } moduleId = system.getModuleId(settings); if (moduleId) { settings = { model: settings, activate: !activatorPresent }; 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, element) { context.strategy(context).then(function (child) { composition.bindAndShow(child, element, context); }); }, inject: function (context, element) { if (!context.model) { this.bindAndShow(null, element, context); return; } if (context.view) { viewLocator.locateView(context.view, context.area, context.viewElements).then(function (child) { composition.bindAndShow(child, element, 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, element); }).fail(function (err) { onError(context, 'Failed to load view strategy (' + context.strategy + '). Details: ' + err.message, element); }); } else { this.executeStrategy(context, element); } }, /** * 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, element, settings); } else { settings.area = settings.area || 'partial'; settings.preserveContext = true; viewLocator.locateView(settings.view, settings.area, settings.viewElements).then(function (child) { composition.bindAndShow(child, element, settings); }); } } else if (system.isString(settings.model)) { system.acquire(settings.model).then(function (module) { settings.model = system.resolveObject(module); composition.inject(settings, element); }).fail(function (err) { onError(settings, 'Failed to load composed module (' + settings.model + '). Details: ' + err.message, element); }); } else { composition.inject(settings, element); } } }; 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; });
Craga89/Durandal
src/durandal/js/composition.js
JavaScript
mit
27,354
var ns = {}; /** @interface */ ns.I = function() {}; /** @const */ var nsConst = {}; /** @interface */ nsConst.I = function() {};
angular/clutz
src/test/java/com/google/javascript/clutz/testdata/extern_ns.externs.js
JavaScript
mit
132
/* --- name: Slick.Parser description: Standalone CSS3 Selector parser provides: Slick.Parser ... */ ;(function(){ var parsed, separatorIndex, combinatorIndex, reversed, cache = {}, reverseCache = {}, reUnescape = /\\/g; var parse = function(expression, isReversed){ if (expression == null) return null; if (expression.Slick === true) return expression; expression = ('' + expression).replace(/^\s+|\s+$/g, ''); reversed = !!isReversed; var currentCache = (reversed) ? reverseCache : cache; if (currentCache[expression]) return currentCache[expression]; parsed = { Slick: true, expressions: [], raw: expression, reverse: function(){ return parse(this.raw, true); } }; separatorIndex = -1; while (expression != (expression = expression.replace(regexp, parser))); parsed.length = parsed.expressions.length; return currentCache[parsed.raw] = (reversed) ? reverse(parsed) : parsed; }; var reverseCombinator = function(combinator){ if (combinator === '!') return ' '; else if (combinator === ' ') return '!'; else if ((/^!/).test(combinator)) return combinator.replace(/^!/, ''); else return '!' + combinator; }; var reverse = function(expression){ var expressions = expression.expressions; for (var i = 0; i < expressions.length; i++){ var exp = expressions[i]; var last = {parts: [], tag: '*', combinator: reverseCombinator(exp[0].combinator)}; for (var j = 0; j < exp.length; j++){ var cexp = exp[j]; if (!cexp.reverseCombinator) cexp.reverseCombinator = ' '; cexp.combinator = cexp.reverseCombinator; delete cexp.reverseCombinator; } exp.reverse().push(last); } return expression; }; var escapeRegExp = function(string){// Credit: XRegExp 0.6.1 (c) 2007-2008 Steven Levithan <http://stevenlevithan.com/regex/xregexp/> MIT License return string.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, function(match){ return '\\' + match; }); }; var regexp = new RegExp( /* #!/usr/bin/env ruby puts "\t\t" + DATA.read.gsub(/\(\?x\)|\s+#.*$|\s+|\\$|\\n/,'') __END__ "(?x)^(?:\ \\s* ( , ) \\s* # Separator \n\ | \\s* ( <combinator>+ ) \\s* # Combinator \n\ | ( \\s+ ) # CombinatorChildren \n\ | ( <unicode>+ | \\* ) # Tag \n\ | \\# ( <unicode>+ ) # ID \n\ | \\. ( <unicode>+ ) # ClassName \n\ | # Attribute \n\ \\[ \ \\s* (<unicode1>+) (?: \ \\s* ([*^$!~|]?=) (?: \ \\s* (?:\ ([\"']?)(.*?)\\9 \ )\ ) \ )? \\s* \ \\](?!\\]) \n\ | :+ ( <unicode>+ )(?:\ \\( (?:\ (?:([\"'])([^\\12]*)\\12)|((?:\\([^)]+\\)|[^()]*)+)\ ) \\)\ )?\ )" */ "^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)" .replace(/<combinator>/, '[' + escapeRegExp(">+~`!@$%^&={}\\;</") + ']') .replace(/<unicode>/g, '(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])') .replace(/<unicode1>/g, '(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])') ); function parser( rawMatch, separator, combinator, combinatorChildren, tagName, id, className, attributeKey, attributeOperator, attributeQuote, attributeValue, pseudoMarker, pseudoClass, pseudoQuote, pseudoClassQuotedValue, pseudoClassValue ){ if (separator || separatorIndex === -1){ parsed.expressions[++separatorIndex] = []; combinatorIndex = -1; if (separator) return ''; } if (combinator || combinatorChildren || combinatorIndex === -1){ combinator = combinator || ' '; var currentSeparator = parsed.expressions[separatorIndex]; if (reversed && currentSeparator[combinatorIndex]) currentSeparator[combinatorIndex].reverseCombinator = reverseCombinator(combinator); currentSeparator[++combinatorIndex] = {combinator: combinator, tag: '*'}; } var currentParsed = parsed.expressions[separatorIndex][combinatorIndex]; if (tagName){ currentParsed.tag = tagName.replace(reUnescape, ''); } else if (id){ currentParsed.id = id.replace(reUnescape, ''); } else if (className){ className = className.replace(reUnescape, ''); if (!currentParsed.classList) currentParsed.classList = []; if (!currentParsed.classes) currentParsed.classes = []; currentParsed.classList.push(className); currentParsed.classes.push({ value: className, regexp: new RegExp('(^|\\s)' + escapeRegExp(className) + '(\\s|$)') }); } else if (pseudoClass){ pseudoClassValue = pseudoClassValue || pseudoClassQuotedValue; pseudoClassValue = pseudoClassValue ? pseudoClassValue.replace(reUnescape, '') : null; if (!currentParsed.pseudos) currentParsed.pseudos = []; currentParsed.pseudos.push({ key: pseudoClass.replace(reUnescape, ''), value: pseudoClassValue, type: pseudoMarker.length == 1 ? 'class' : 'element' }); } else if (attributeKey){ attributeKey = attributeKey.replace(reUnescape, ''); attributeValue = (attributeValue || '').replace(reUnescape, ''); var test, regexp; switch (attributeOperator){ case '^=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) ); break; case '$=' : regexp = new RegExp( escapeRegExp(attributeValue) +'$' ); break; case '~=' : regexp = new RegExp( '(^|\\s)'+ escapeRegExp(attributeValue) +'(\\s|$)' ); break; case '|=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) +'(-|$)' ); break; case '=' : test = function(value){ return attributeValue == value; }; break; case '*=' : test = function(value){ return value && value.indexOf(attributeValue) > -1; }; break; case '!=' : test = function(value){ return attributeValue != value; }; break; default : test = function(value){ return !!value; }; } if (attributeValue == '' && (/^[*$^]=$/).test(attributeOperator)) test = function(){ return false; }; if (!test) test = function(value){ return value && regexp.test(value); }; if (!currentParsed.attributes) currentParsed.attributes = []; currentParsed.attributes.push({ key: attributeKey, operator: attributeOperator, value: attributeValue, test: test }); } return ''; }; // Slick NS var Slick = (this.Slick || {}); Slick.parse = function(expression){ return parse(expression); }; Slick.escapeRegExp = escapeRegExp; if (!this.Slick) this.Slick = Slick; }).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
SupriyaVenkatesh/meanjsnew
node_modules/email-templates/node_modules/juice/node_modules/mootools-slick-parser/Source/Slick.Parser.js
JavaScript
mit
6,587
<?php defined('C5_EXECUTE') or die('Access Denied.'); use Concrete\Core\Page\Type\Composer\FormLayoutSetControl as PageTypeComposerFormLayoutSetControl; use Concrete\Core\Url\Resolver\Manager\ResolverManagerInterface; $resolverManager = app(ResolverManagerInterface::class); ?> <div style="display: none"> <div id="ccm-page-type-composer-add-set" class="ccm-ui"> <form method="post" action="<?= $view->action('add_set', $pagetype->getPageTypeID()) ?>"> <?php $token->output('add_set') ?> <div class="form-group"> <?= $form->label('ptComposerFormLayoutSetName', tc('Name of a set', 'Set Name')) ?> <?= $form->text('ptComposerFormLayoutSetName') ?> </div> <div class="form-group"> <?= $form->label('ptComposerFormLayoutSetDescription', tc('Description of a set', 'Set Description')) ?> <?= $form->textarea('ptComposerFormLayoutSetDescription') ?> </div> </form> <div class="dialog-buttons"> <button class="btn btn-secondary float-left" onclick="jQuery.fn.dialog.closeTop()"><?= t('Cancel') ?></button> <button class="btn btn-primary float-right" onclick="$('#ccm-page-type-composer-add-set form').submit()"><?= t('Add Set') ?></button> </div> </div> </div> <div class="ccm-dashboard-header-buttons btn-group"> <a href="#" data-dialog="add_set" class="btn btn-secondary"><?= t('Add Set') ?></a> <a href="<?=URL::to('/dashboard/pages/types') ?>" class="btn btn-secondary"><?= t('Back to List') ?></a> </div> <div class="ccm-pane-body ccm-pane-body-footer"> <p class="lead"><?= $pagetype->getPageTypeDisplayName() ?></p> <?php if (count($sets) > 0) { // @var Concrete\Core\Page\Type\Composer\FormLayoutSet $set foreach ($sets as $set) { ?> <div class="ccm-item-set card " data-page-type-composer-form-layout-control-set-id="<?= $set->getPageTypeComposerFormLayoutSetID() ?>"> <div class="card-header"> <ul class="ccm-item-set-controls" style=" float: right;"> <li><a href="<?= h($resolverManager->resolve(['/ccm/system/page/type/composer/form/add_control']) . '?ptComposerFormLayoutSetID=' . $set->getPageTypeComposerFormLayoutSetID()) ?>" dialog-title="<?=t('Add Form Control') ?>" dialog-width="640" dialog-height="400" data-command="add-form-set-control"><i class="fas fa-plus"></i></a></li> <li><a href="#" data-command="move_set" style="cursor: move"><i class="fas fa-arrows-alt"></i></a></li> <li><a href="#" data-edit-set="<?= $set->getPageTypeComposerFormLayoutSetID() ?>"><i class="fas fa-edit"></i></a></li> <li><a href="#" data-delete-set="<?= $set->getPageTypeComposerFormLayoutSetID() ?>"><i class="fas fa-trash-alt"></i></a></li> </ul> <div class="ccm-item-set-name" ><?php if ($set->getPageTypeComposerFormLayoutSetDisplayName()) { echo $set->getPageTypeComposerFormLayoutSetDisplayName(); } else { echo t('(No Name)'); } ?></div> </div> <div style="display: none"> <div data-delete-set-dialog="<?= $set->getPageTypeComposerFormLayoutSetID() ?>"> <form data-delete-set-form="<?= $set->getPageTypeComposerFormLayoutSetID() ?>" action="<?= $view->action('delete_set', $set->getPageTypeComposerFormLayoutSetID()) ?>" method="post"> <?= t('Delete this form layout set? This cannot be undone.') ?> <?php $token->output('delete_set') ?> </form> <div class="dialog-buttons"> <button class="btn btn-secondary float-left" onclick="jQuery.fn.dialog.closeTop()"><?= t('Cancel') ?></button> <button class="btn btn-danger float-right" onclick="$('form[data-delete-set-form=<?= $set->getPageTypeComposerFormLayoutSetID() ?>]').submit()"><?=t('Delete Set') ?></button> </div> </div> </div> <div style="display: none"> <div data-edit-set-dialog="<?= $set->getPageTypeComposerFormLayoutSetID() ?>" class="ccm-ui"> <form data-edit-set-form="<?= $set->getPageTypeComposerFormLayoutSetID() ?>" action="<?= $view->action('update_set', $set->getPageTypeComposerFormLayoutSetID()) ?>" method="post"> <div class="form-group"> <?= $form->label('ptComposerFormLayoutSetName', tc('Name of a set', 'Set Name')) ?> <?= $form->text('ptComposerFormLayoutSetName', $set->getPageTypeComposerFormLayoutSetName()) ?> </div> <div class="form-group"> <?= $form->label('ptComposerFormLayoutSetDescription', tc('Description of a set', 'Set Description')) ?> <?= $form->textarea('ptComposerFormLayoutSetDescription', $set->getPageTypeComposerFormLayoutSetDescription()) ?> </div> <div class="dialog-buttons"> <button class="btn btn-secondary float-left" onclick="jQuery.fn.dialog.closeTop();"><?= t('Cancel') ?></button> <button class="btn btn-primary float-right" onclick="$('form[data-edit-set-form=<?= $set->getPageTypeComposerFormLayoutSetID() ?>]').submit();"><?=t('Update Set') ?></button> </div> <?php $token->output('update_set') ?> </form> </div> </div> <table class="table table-hover" style="width: 100%;"> <tbody class="ccm-item-set-inner"> <?php $controls = PageTypeComposerFormLayoutSetControl::getList($set); foreach ($controls as $cnt) { echo View::element('page_types/composer/form/layout_set/control', ['control' => $cnt]); } ?> </tbody> </table> </div> <?php } ?> <?php } else { ?> <p><?= t('You have not added any composer form layout control sets.') ?></p> <?php } ?> </div> <script type="text/javascript"> var Composer = { deleteFromLayoutSetControl: function(ptComposerFormLayoutSetControlID) { jQuery.fn.dialog.showLoader(); var formData = [{ 'name': 'token', 'value': '<?= $token->generate('delete_set_control') ?>' }, { 'name': 'ptComposerFormLayoutSetControlID', 'value': ptComposerFormLayoutSetControlID }]; $.ajax({ type: 'post', data: formData, url: '<?= $view->action('delete_set_control') ?>', success: function() { jQuery.fn.dialog.hideLoader(); jQuery.fn.dialog.closeAll(); $('tr[data-page-type-composer-form-layout-control-set-control-id=' + ptComposerFormLayoutSetControlID + ']').remove(); } }); } } $(function() { $('a[data-dialog=add_set]').on('click', function() { jQuery.fn.dialog.open({ element: '#ccm-page-type-composer-add-set', modal: true, width: 320, title: '<?= t('Add Control Set') ?>', height: 'auto' }); }); $('a[data-delete-set]').on('click', function() { var ptComposerFormLayoutSetID = $(this).attr('data-delete-set'); jQuery.fn.dialog.open({ element: 'div[data-delete-set-dialog=' + ptComposerFormLayoutSetID + ']', modal: true, width: 320, title: '<?=t('Delete Control Set'); ?>', height: 'auto' }); }); $('a[data-edit-set]').on('click', function() { var ptComposerFormLayoutSetID = $(this).attr('data-edit-set'); jQuery.fn.dialog.open({ element: 'div[data-edit-set-dialog=' + ptComposerFormLayoutSetID + ']', modal: true, width: 320, title: '<?=t('Update Control Set'); ?>', height: 'auto' }); }); $('div.ccm-pane-body').sortable({ handle: 'a[data-command=move_set]', items: '.ccm-item-set', cursor: 'move', axis: 'y', stop: function() { var formData = [{ 'name': 'token', 'value': '<?= $token->generate('update_set_display_order') ?>' }, { 'name': 'ptID', 'value': <?= $pagetype->getPageTypeID(); ?> }]; $('.ccm-item-set').each(function() { formData.push({'name': 'ptComposerFormLayoutSetID[]', 'value': $(this).attr('data-page-type-composer-form-layout-control-set-id')}); }); $.ajax({ type: 'post', data: formData, url: '<?= $view->action('update_set_display_order') ?>', success: function() { } }); } }); $('a[data-command=add-form-set-control]').dialog(); $('a[data-command=edit-form-set-control]').dialog(); $('.ccm-item-set-inner').sortable({ handle: 'a[data-command=move-set-control]', items: '.ccm-item-set-control', cursor: 'move', axis: 'y', helper: function(e, ui) { // prevent table columns from collapsing ui.addClass('active'); ui.children().each(function () { $(this).width($(this).width()); }); return ui; }, stop: function(e, ui) { ui.item.removeClass('active'); var formData = [{ 'name': 'token', 'value': '<?= $token->generate('update_set_control_display_order') ?>' }, { 'name': 'ptComposerFormLayoutSetID', 'value': $(this).parent().parent().attr('data-page-type-composer-form-layout-control-set-id') }]; $(this).find('.ccm-item-set-control').each(function() { formData.push({'name': 'ptComposerFormLayoutSetControlID[]', 'value': $(this).attr('data-page-type-composer-form-layout-control-set-control-id')}); }); $.ajax({ type: 'post', data: formData, url: '<?= $view->action('update_set_control_display_order') ?>', success: function() {} }); } }); $('.ccm-item-set-inner').on('click', 'a[data-delete-set-control]', function() { var ptComposerFormLayoutSetControlID = $(this).attr('data-delete-set-control'); jQuery.fn.dialog.open({ element: 'div[data-delete-set-control-dialog=' + ptComposerFormLayoutSetControlID + ']', modal: true, width: 320, title: '<?=t('Delete Control'); ?>', height: 'auto' }); return false; }); }); </script>
mainio/concrete5
concrete/single_pages/dashboard/pages/types/form.php
PHP
mit
10,024
#require 'coveralls' #Coveralls.wear! # This file was generated by the `rails generate rspec:install` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause this # file to always be loaded, without a need to explicitly require it in any files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. config.filter_run :focus config.run_all_when_everything_filtered = true # Limits the available syntax to the non-monkey patched syntax that is recommended. # For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching config.disable_monkey_patching! # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end
kexline4710/gdi-new-site
spec/spec_helper.rb
Ruby
mit
4,133
version https://git-lfs.github.com/spec/v1 oid sha256:617a326a65f3c917869c9c1f6dc58da7dc99f042ecb70ee9c36246edc56f510c size 540
yogeshsaroya/new-cdnjs
ajax/libs/yui/3.2.0/datatype/lang/datatype-date-format_ca.js
JavaScript
mit
128
.nex-tree { margin: 0; padding: 0; list-style-type: none; } .nex-tree li { white-space: nowrap; } .nex-tree li ul { list-style-type: none; margin: 0; padding: 0; } .nex-tree-item { cursor:pointer;} .nex-tree-title { display: inline-block; text-decoration: none; vertical-align: top; white-space: nowrap; font:normal 11px/15px helvetica,tahoma, arial, verdana, sans-serif; font-size: 12px; /*text-overflow: ellipsis;*/ /*overflow:hidden;*/ padding:0 2px; height: 20px; line-height: 20px; } .nex-tree-expander, .nex-tree-line, .nex-tree-empty, .nex-tree-collapsed, .nex-tree-icon, .nex-tree-checkbox, .nex-tree-indent { display: inline-block; width: 16px; height: 20px; vertical-align: top; overflow: hidden; background-repeat:no-repeat; } .nex-tree-expander { background-image: url('./images/elbow-plus.gif'); } .nex-tree-expander-nl { background-image: url('./images/elbow-plus-nl.gif'); } .nex-tree-expander-end { background-image: url('./images/elbow-end-plus.gif'); } .nex-tree-first-all .nex-tree-expander { background-image: url('./images/elbow-plus.gif'); } .nex-tree-open .nex-tree-expander-nl { background-image: url('./images/elbow-minus-nl.gif'); } .nex-tree-open .nex-tree-expander { background-image: url('./images/elbow-minus.gif'); } .nex-tree-open .nex-tree-expander-end { background-image: url('./images/elbow-end-minus.gif'); } .nex-tree-first-all .nex-tree-open .nex-tree-expander { background-image: url('./images/elbow-minus.gif'); } .nex-tree-loading .nex-tree-expander, .nex-tree-loading .nex-tree-expander-nl, .nex-tree-loading .nex-tree-expander-end { background-position:0 2px; background-image: url('./images/loading.gif'); } .nex-tree-line { background-image: url('./images/elbow-line.gif'); } .nex-tree-elbow{ background-image: url('./images/elbow.gif'); } .nex-tree-elbow-end { background-image: url('./images/elbow-end.gif'); } .nex-tree-item-over { background-color: #efefef; } .nex-tree-item-selected { background-color: #dfe8f6 !important; } .nex-tree-folder { background-position:0 3px; background-image: url('./images/folder.gif'); } .nex-tree-open .nex-tree-folder { background-image: url('./images/folder-open.gif'); } .nex-tree-file { background-position:0 2px; background-image: url('./images/leaf.gif'); } .nex-tree-checkbox0 { background: url('./images/tree_icons.png') no-repeat -208px -16px; } .nex-tree-checkbox1 { background: url('./images/tree_icons.png') no-repeat -224px -16px; } .nex-tree-checkbox2 { background: url('./images/tree_icons.png') no-repeat -240px -16px; } .nex-tree-node-proxy { font-size: 12px; line-height: 20px; padding: 0 2px 0 20px; border-width: 1px; border-style: solid; z-index: 9900000; } .nex-tree-editor { border: 1px solid #ccc; font-size: 12px; height: 14px !important; height: 18px; line-height: 14px; padding: 1px 2px; width: 80px; position: absolute; top: 0; } .nex-tree-node-proxy { background-color: #ffffff; color: #000000; border-color: #95B8E7; } /* drag drop */ .nex-tree-item-clone { position:absolute; filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=85); opacity: 0.85; padding: 5px; padding-left: 20px; white-space: nowrap; color: #000; font: normal 11px tahoma, arial, verdana, sans-serif; border: 1px solid; border-color: #ddd #bbb #bbb #ddd; background-color: #fff; } .nex-tree-item-line { position: absolute; overflow: hidden; zoom: 1; height: 0px; border-width: 1px 0px 0px; border-style: dotted; border-color: green; display: block; } .nex-tree-clone-center { background:url(images/drop-add.gif) 2px 4px no-repeat; } .nex-tree-clone-deny { background:url(images/drop-deny.gif) 2px 4px no-repeat; } .nex-tree-clone-top { background:url(images/drop-top.gif) 2px 4px no-repeat; } .nex-tree-clone-bottom { background:url(images/drop-bottom.gif) 2px 4px no-repeat; }
bplok20010/nex
tag/v1.1.0/src/themes/default/tree/nexTree.css
CSS
mit
3,910
[CmdletBinding()] param() # Arrange. . $PSScriptRoot\..\..\..\..\Tests\lib\Initialize-Test.ps1 $global:DebugPreference = 'Continue' Unregister-Mock Import-Module Register-Mock Write-VstsTaskError Register-Mock Get-VstsWebProxy { } # Act. Microsoft.PowerShell.Core\Import-Module $PSScriptRoot\.. # Assert. Assert-AreEqual 'SilentlyContinue' $global:DebugPreference
maikvandergaag/msft-vsts-extensions
azuredevops/azureresourcegroup/azureresourcegroup/ps_modules/VstsAzureHelpers_/Tests/OverriddesGlobalDebugPreference.ps1
PowerShell
mit
367
version https://git-lfs.github.com/spec/v1 oid sha256:318b87e677c2f0652dcf2ee8e4a4fb8dcb0124a9f9f80acef6d4fcf41f5fb9e6 size 1919
yogeshsaroya/new-cdnjs
ajax/libs/dojo/1.9.7/has.js
JavaScript
mit
129
package network import ( "net" "testing" "github.com/kelda/kelda/db" "github.com/miekg/dns" "github.com/stretchr/testify/assert" ) func TestUpdateTable(t *testing.T) { t.Parallel() listenAndServe = func(table *dnsTable) error { return assert.AnError } assert.Nil(t, updateTable(nil, nil)) listenAndServe = func(table *dnsTable) error { table.server.NotifyStartedFunc() return nil } table := updateTable(nil, []db.Hostname{{Hostname: "foo", IP: "1.2.3.4"}}) assert.NotNil(t, table) assert.Equal(t, map[string]net.IP{"foo": net.IPv4(1, 2, 3, 4)}, table.records) newTable := updateTable(table, []db.Hostname{{Hostname: "foo", IP: "5.6.7.8"}}) assert.NotNil(t, newTable) assert.True(t, table == newTable) // Pointer Equality. assert.Equal(t, map[string]net.IP{"foo": net.IPv4(5, 6, 7, 8)}, newTable.records) } func TestGenResponse(t *testing.T) { t.Parallel() table := makeTable(map[string]net.IP{ "a": net.IPv4(1, 2, 3, 4), }) req := &dns.Msg{} req.SetQuestion("foo.", dns.TypeMX) resp := table.genResponse(req) assert.Equal(t, req.Id, resp.Id) assert.Equal(t, resp.Rcode, dns.RcodeNotImplemented) req = &dns.Msg{} req.SetQuestion("foo.", dns.TypeAAAA) resp = table.genResponse(req) assert.Equal(t, req.Id, resp.Id) assert.Equal(t, resp.Rcode, dns.RcodeSuccess) assert.Empty(t, resp.Answer) req.Question = nil resp = table.genResponse(req) assert.Equal(t, req.Id, resp.Id) assert.Equal(t, dns.RcodeNotImplemented, resp.Rcode) req.SetQuestion("bad", dns.TypeA) resp = table.genResponse(req) assert.Nil(t, resp) req.SetQuestion("a", dns.TypeA) resp = table.genResponse(req) exp := *req exp.Response = true exp.Rcode = dns.RcodeSuccess exp.Answer = []dns.RR{&dns.A{ Hdr: dns.RR_Header{ Name: "a", Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: dnsTTL, }, A: net.IPv4(1, 2, 3, 4), }} assert.Equal(t, &exp, resp) } func TestLookupA(t *testing.T) { t.Parallel() table := makeTable(map[string]net.IP{ "a": net.IPv4(1, 2, 3, 4), }) assert.Empty(t, table.lookupA("bad")) assert.Equal(t, []net.IP{net.IPv4(1, 2, 3, 4)}, table.lookupA("a")) assert.Equal(t, []net.IP{net.IPv4(1, 2, 3, 4)}, table.lookupA("A")) lookupHost = func(string) ([]string, error) { return nil, assert.AnError } assert.Empty(t, table.lookupA("kelda.io.")) lookupHost = func(string) ([]string, error) { return []string{"bad"}, nil } assert.Empty(t, table.lookupA("kelda.io.")) lookupHost = func(string) ([]string, error) { return []string{"2601:644:380:cde:fc06:2533:adf9:2891"}, nil } assert.Empty(t, table.lookupA("kelda.io.")) lookupHost = func(string) ([]string, error) { return []string{"1.2.3.4", "5.6.7.8"}, nil } assert.Equal(t, []net.IP{net.IPv4(1, 2, 3, 4), net.IPv4(5, 6, 7, 8)}, table.lookupA("kelda.io.")) } func TestMakeTable(t *testing.T) { t.Parallel() records := map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)} tbl := makeTable(records) assert.Equal(t, tbl.records, records) assert.Equal(t, tbl.server.Addr, "10.0.0.1:53") assert.Equal(t, tbl.server.Net, "udp") } func TestHostnamesToDNS(t *testing.T) { t.Parallel() res := hostnamesToDNS([]db.Hostname{{ Hostname: "h1", }, { Hostname: "h2", IP: "badIP", }, { Hostname: "h3", IP: "1.2.3.4", }, { Hostname: "h4", IP: "5.6.7.8", }}) exp := map[string]net.IP{ "h3": net.IPv4(1, 2, 3, 4), "h4": net.IPv4(5, 6, 7, 8), } assert.Equal(t, exp, res) } func TestSyncHostnamesWorker(t *testing.T) { conn := db.New() conn.Txn(db.AllTables...).Run(func(view db.Database) error { dbl := view.InsertLoadBalancer() dbl.Name = "lb" dbl.IP = "IP" view.Commit(dbl) return nil }) syncHostnamesOnce(conn) assert.Empty(t, conn.SelectFromHostname(nil)) conn.Txn(db.AllTables...).Run(func(view db.Database) error { etcd := view.InsertEtcd() etcd.Leader = true view.Commit(etcd) return nil }) syncHostnamesOnce(conn) assert.Equal(t, []db.Hostname{{ID: 3, Hostname: "lb", IP: "IP"}}, conn.SelectFromHostname(nil)) } type syncHostnameTest struct { loadBalancers []db.LoadBalancer containers []db.Container oldHostnames, expHostnames []db.Hostname } func TestSyncHostnames(t *testing.T) { tests := []syncHostnameTest{ { loadBalancers: []db.LoadBalancer{ { Name: "foo", IP: "fooIP", }, }, expHostnames: []db.Hostname{ {Hostname: "foo", IP: "fooIP"}, }, }, { loadBalancers: []db.LoadBalancer{ { Name: "foo", IP: "fooIP", }, { Name: "bar", IP: "barIP", }, }, oldHostnames: []db.Hostname{ {Hostname: "foo", IP: "fooIP"}, }, expHostnames: []db.Hostname{ {Hostname: "foo", IP: "fooIP"}, {Hostname: "bar", IP: "barIP"}, }, }, { loadBalancers: []db.LoadBalancer{ { Name: "bar", IP: "barIP", }, }, oldHostnames: []db.Hostname{ {Hostname: "foo", IP: "fooIP"}, {Hostname: "bar", IP: "barIP"}, }, expHostnames: []db.Hostname{ {Hostname: "bar", IP: "barIP"}, }, }, { loadBalancers: []db.LoadBalancer{ { Name: "foo", IP: "fooIP", }, }, containers: []db.Container{ { Hostname: "container", IP: "containerIP", }, }, oldHostnames: []db.Hostname{ {Hostname: "foo", IP: "fooIP"}, }, expHostnames: []db.Hostname{ {Hostname: "foo", IP: "fooIP"}, {Hostname: "container", IP: "containerIP"}, }, }, } for _, test := range tests { conn := db.New() conn.Txn(db.AllTables...).Run(func(view db.Database) error { etcd := view.InsertEtcd() etcd.Leader = true view.Commit(etcd) for _, l := range test.loadBalancers { dbl := view.InsertLoadBalancer() l.ID = dbl.ID view.Commit(l) } for _, h := range test.oldHostnames { dbh := view.InsertHostname() h.ID = dbh.ID view.Commit(h) } for _, c := range test.containers { dbc := view.InsertContainer() c.ID = dbc.ID view.Commit(c) } return nil }) syncHostnamesOnce(conn) assertHostnamesEqual(t, test.expHostnames, conn.SelectFromHostname(nil)) } } func assertHostnamesEqual(t *testing.T, exp, actual []db.Hostname) { assert.Len(t, actual, len(exp)) assert.Equal(t, toHostnameMap(exp), toHostnameMap(actual)) } func toHostnameMap(hostnames []db.Hostname) map[db.Hostname]struct{} { hostnameMap := map[db.Hostname]struct{}{} for _, h := range hostnames { h.ID = 0 hostnameMap[h] = struct{}{} } return hostnameMap }
NetSys/quilt
minion/network/dns_test.go
GO
mit
6,506
package com.github.jvmgo.classpath; import java.nio.file.*; class ZipEntry implements Entry { private Path absPath; ZipEntry(String path) { absPath = Paths.get(path).toAbsolutePath(); } @Override public byte[] readClass(String className) throws Exception { try (FileSystem zipFs = FileSystems.newFileSystem(absPath, null)) { return Files.readAllBytes(zipFs.getPath(className)); } } }
zxh0/jvmgo-book
v1/code/java/jvmgo_java/ch05/src/main/java/com/github/jvmgo/classpath/ZipEntry.java
Java
mit
450
<!DOCTYPE html> <html lang="en" > <head> <title>Tags - 2015FALL KMOL 課程</title> <!-- Using the latest rendering mode for IE --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style type="text/css"> /*some stuff for output/input prompts*/ div.cell{border:1px solid transparent;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch}div.cell.selected{border-radius:4px;border:thin #ababab solid} div.cell.edit_mode{border-radius:4px;border:thin #008000 solid} div.cell{width:100%;padding:5px 5px 5px 0;margin:0;outline:none} div.prompt{min-width:11ex;padding:.4em;margin:0;font-family:monospace;text-align:right;line-height:1.21429em} @media (max-width:480px){div.prompt{text-align:left}}div.inner_cell{display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch;-webkit-box-flex:1;-moz-box-flex:1;box-flex:1;flex:1} div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;line-height:1.21429em} div.prompt:empty{padding-top:0;padding-bottom:0} div.input{page-break-inside:avoid;display:-webkit-box;-webkit-box-orient:horizontal;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:horizontal;-moz-box-align:stretch;display:box;box-orient:horizontal;box-align:stretch;} div.inner_cell{width:90%;} div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;} div.input_prompt{color:navy;border-top:1px solid transparent;} div.output_wrapper{margin-top:5px;position:relative;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;} div.output_scroll{height:24em;width:100%;overflow:auto;border-radius:4px;-webkit-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);-moz-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);} div.output_collapsed{margin:0px;padding:0px;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;} div.out_prompt_overlay{height:100%;padding:0px 0.4em;position:absolute;border-radius:4px;} div.out_prompt_overlay:hover{-webkit-box-shadow:inset 0 0 1px #000000;-moz-box-shadow:inset 0 0 1px #000000;box-shadow:inset 0 0 1px #000000;background:rgba(240, 240, 240, 0.5);} div.output_prompt{color:darkred;} a.anchor-link:link{text-decoration:none;padding:0px 20px;visibility:hidden;} h1:hover .anchor-link,h2:hover .anchor-link,h3:hover .anchor-link,h4:hover .anchor-link,h5:hover .anchor-link,h6:hover .anchor-link{visibility:visible;} /* end stuff for output/input prompts*/ .highlight-ipynb .hll { background-color: #ffffcc } .highlight-ipynb { background: #f8f8f8; } .highlight-ipynb .c { color: #408080; font-style: italic } /* Comment */ .highlight-ipynb .err { border: 1px solid #FF0000 } /* Error */ .highlight-ipynb .k { color: #008000; font-weight: bold } /* Keyword */ .highlight-ipynb .o { color: #666666 } /* Operator */ .highlight-ipynb .cm { color: #408080; font-style: italic } /* Comment.Multiline */ .highlight-ipynb .cp { color: #BC7A00 } /* Comment.Preproc */ .highlight-ipynb .c1 { color: #408080; font-style: italic } /* Comment.Single */ .highlight-ipynb .cs { color: #408080; font-style: italic } /* Comment.Special */ .highlight-ipynb .gd { color: #A00000 } /* Generic.Deleted */ .highlight-ipynb .ge { font-style: italic } /* Generic.Emph */ .highlight-ipynb .gr { color: #FF0000 } /* Generic.Error */ .highlight-ipynb .gh { color: #000080; font-weight: bold } /* Generic.Heading */ .highlight-ipynb .gi { color: #00A000 } /* Generic.Inserted */ .highlight-ipynb .go { color: #888888 } /* Generic.Output */ .highlight-ipynb .gp { color: #000080; font-weight: bold } /* Generic.Prompt */ .highlight-ipynb .gs { font-weight: bold } /* Generic.Strong */ .highlight-ipynb .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ .highlight-ipynb .gt { color: #0044DD } /* Generic.Traceback */ .highlight-ipynb .kc { color: #008000; font-weight: bold } /* Keyword.Constant */ .highlight-ipynb .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */ .highlight-ipynb .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */ .highlight-ipynb .kp { color: #008000 } /* Keyword.Pseudo */ .highlight-ipynb .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */ .highlight-ipynb .kt { color: #B00040 } /* Keyword.Type */ .highlight-ipynb .m { color: #666666 } /* Literal.Number */ .highlight-ipynb .s { color: #BA2121 } /* Literal.String */ .highlight-ipynb .na { color: #7D9029 } /* Name.Attribute */ .highlight-ipynb .nb { color: #008000 } /* Name.Builtin */ .highlight-ipynb .nc { color: #0000FF; font-weight: bold } /* Name.Class */ .highlight-ipynb .no { color: #880000 } /* Name.Constant */ .highlight-ipynb .nd { color: #AA22FF } /* Name.Decorator */ .highlight-ipynb .ni { color: #999999; font-weight: bold } /* Name.Entity */ .highlight-ipynb .ne { color: #D2413A; font-weight: bold } /* Name.Exception */ .highlight-ipynb .nf { color: #0000FF } /* Name.Function */ .highlight-ipynb .nl { color: #A0A000 } /* Name.Label */ .highlight-ipynb .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */ .highlight-ipynb .nt { color: #008000; font-weight: bold } /* Name.Tag */ .highlight-ipynb .nv { color: #19177C } /* Name.Variable */ .highlight-ipynb .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */ .highlight-ipynb .w { color: #bbbbbb } /* Text.Whitespace */ .highlight-ipynb .mf { color: #666666 } /* Literal.Number.Float */ .highlight-ipynb .mh { color: #666666 } /* Literal.Number.Hex */ .highlight-ipynb .mi { color: #666666 } /* Literal.Number.Integer */ .highlight-ipynb .mo { color: #666666 } /* Literal.Number.Oct */ .highlight-ipynb .sb { color: #BA2121 } /* Literal.String.Backtick */ .highlight-ipynb .sc { color: #BA2121 } /* Literal.String.Char */ .highlight-ipynb .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */ .highlight-ipynb .s2 { color: #BA2121 } /* Literal.String.Double */ .highlight-ipynb .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */ .highlight-ipynb .sh { color: #BA2121 } /* Literal.String.Heredoc */ .highlight-ipynb .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */ .highlight-ipynb .sx { color: #008000 } /* Literal.String.Other */ .highlight-ipynb .sr { color: #BB6688 } /* Literal.String.Regex */ .highlight-ipynb .s1 { color: #BA2121 } /* Literal.String.Single */ .highlight-ipynb .ss { color: #19177C } /* Literal.String.Symbol */ .highlight-ipynb .bp { color: #008000 } /* Name.Builtin.Pseudo */ .highlight-ipynb .vc { color: #19177C } /* Name.Variable.Class */ .highlight-ipynb .vg { color: #19177C } /* Name.Variable.Global */ .highlight-ipynb .vi { color: #19177C } /* Name.Variable.Instance */ .highlight-ipynb .il { color: #666666 } /* Literal.Number.Integer.Long */ </style> <style type="text/css"> /* Overrides of notebook CSS for static HTML export */ div.entry-content { overflow: visible; padding: 8px; } .input_area { padding: 0.2em; } a.heading-anchor { white-space: normal; } .rendered_html code { font-size: .8em; } pre.ipynb { color: black; background: #f7f7f7; border: none; box-shadow: none; margin-bottom: 0; padding: 0; margin: 0px; font-size: 13px; } /* remove the prompt div from text cells */ div.text_cell .prompt { display: none; } /* remove horizontal padding from text cells, */ /* so it aligns with outer body text */ div.text_cell_render { padding: 0.5em 0em; } img.anim_icon{padding:0; border:0; vertical-align:middle; -webkit-box-shadow:none; -box-shadow:none} </style> <script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script> <script type="text/javascript"> init_mathjax = function() { if (window.MathJax) { // MathJax loaded MathJax.Hub.Config({ tex2jax: { inlineMath: [ ['$','$'], ["\\(","\\)"] ], displayMath: [ ['$$','$$'], ["\\[","\\]"] ] }, displayAlign: 'left', // Change this to 'center' to center equations. "HTML-CSS": { styles: {'.MathJax_Display': {"margin": 0}} } }); MathJax.Hub.Queue(["Typeset",MathJax.Hub]); } } init_mathjax(); </script> <meta name="author" content="KMOL" /> <!-- Open Graph tags --> <meta property="og:site_name" content="2015FALL KMOL 課程" /> <meta property="og:type" content="website"/> <meta property="og:title" content="2015FALL KMOL 課程"/> <meta property="og:url" content="."/> <meta property="og:description" content="2015FALL KMOL 課程"/> <!-- Bootstrap --> <link rel="stylesheet" href="./theme/css/bootstrap.min.css" type="text/css"/> <link href="./theme/css/font-awesome.min.css" rel="stylesheet"> <link href="./theme/css/pygments/native.css" rel="stylesheet"> <link rel="stylesheet" href="./theme/css/style.css" type="text/css"/> <link href="./feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="2015FALL KMOL 課程 ATOM Feed"/> </head> <body> <div class="navbar navbar-default navbar-fixed-top" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a href="./" class="navbar-brand"> 2015FALL KMOL 課程 </a> </div> <div class="collapse navbar-collapse navbar-ex1-collapse"> <ul class="nav navbar-nav"> <li > <a href="./category/python.html">Python</a> </li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="./archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li> </ul> </div> <!-- /.navbar-collapse --> </div> </div> <!-- /.navbar --> <!-- Banner --> <!-- End Banner --> <div class="container"> <div class="row"> <div class="col-sm-9"> <section id="tags"> <h1>Tags for 2015FALL KMOL 課程</h1> <div class="panel-group" id="accordion"> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapse-ipython">IPython <span class="badge pull-right">1</span></a> </h4> </div> <div id="collapse-ipython" class="panel-collapse collapse"> <div class="panel-body"> <p><span class="categories-timestamp"><time datetime="2015-09-19T21:41:00+08:00">六 19 九月 2015</time></span> <a href="./2015cp_note1.html">2015 計算機程式 Jupyter</a></p> </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapse-jupyter">Jupyter <span class="badge pull-right">1</span></a> </h4> </div> <div id="collapse-jupyter" class="panel-collapse collapse"> <div class="panel-body"> <p><span class="categories-timestamp"><time datetime="2015-09-19T21:41:00+08:00">六 19 九月 2015</time></span> <a href="./2015cp_note1.html">2015 計算機程式 Jupyter</a></p> </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapse-pelican">pelican <span class="badge pull-right">1</span></a> </h4> </div> <div id="collapse-pelican" class="panel-collapse collapse"> <div class="panel-body"> <p><span class="categories-timestamp"><time datetime="2015-09-19T11:41:00+08:00">六 19 九月 2015</time></span> <a href="./2015cp_hw_w1.html">2015 計算機程式 作業一</a></p> </div> </div> </div> <div class="panel panel-default"> <div class="panel-heading"> <h4 class="panel-title"> <a data-toggle="collapse" data-parent="#accordion" href="#collapse-publishing">publishing <span class="badge pull-right">1</span></a> </h4> </div> <div id="collapse-publishing" class="panel-collapse collapse"> <div class="panel-body"> <p><span class="categories-timestamp"><time datetime="2015-09-19T11:41:00+08:00">六 19 九月 2015</time></span> <a href="./2015cp_hw_w1.html">2015 計算機程式 作業一</a></p> </div> </div> </div> </div> </section> </div> <div class="col-sm-3" id="sidebar"> <aside> <section class="well well-sm"> <ul class="list-group list-group-flush"> <li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Social</span></h4> <ul class="list-group" id="social"> <li class="list-group-item"><a href="#"><i class="fa fa-you-can-add-links-in-your-config-file-square fa-lg"></i> You can add links in your config file</a></li> <li class="list-group-item"><a href="#"><i class="fa fa-another-social-link-square fa-lg"></i> Another social link</a></li> </ul> </li> <li class="list-group-item"><a href="./"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a> <ul class="list-group " id="tags"> </ul> </li> <li class="list-group-item"><h4><i class="fa fa-external-link-square fa-lg"></i><span class="icon-label">Links</span></h4> <ul class="list-group" id="links"> <li class="list-group-item"> <a href="http://wordpress-2015course.rhcloud.com/" target="_blank"> 2015課程網頁 </a> </li> <li class="list-group-item"> <a href="http://python.org/" target="_blank"> Python </a> </li> <li class="list-group-item"> <a href="#" target="_blank"> You can modify those links in your config file </a> </li> </ul> </li> </ul> </section> </aside> </div> </div> </div> <footer> <div class="container"> <hr> <div class="row"> <div class="col-xs-10">&copy; 2015 KMOL &middot; Powered by <a href="https://github.com/DandyDev/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>, <a href="http://docs.getpelican.com/" target="_blank">Pelican</a>, <a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div> <div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div> </div> </div> </footer> <script src="./theme/js/jquery.min.js"></script> <!-- Include all compiled plugins (below), or include individual files as needed --> <script src="./theme/js/bootstrap.min.js"></script> <!-- Enable responsive features in IE8 with Respond.js (https://github.com/scottjehl/Respond) --> <script src="./theme/js/respond.min.js"></script> <!-- Disqus --> <script type="text/javascript"> /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */ var disqus_shortname = '2015fall'; // required: replace example with your forum shortname /* * * DON'T EDIT BELOW THIS LINE * * */ (function () { var s = document.createElement('script'); s.async = true; s.type = 'text/javascript'; s.src = '//' + disqus_shortname + '.disqus.com/count.js'; (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s); }()); </script> <!-- End Disqus Code --> </body> </html>
40323155/cadpaw2
tags.html
HTML
mit
17,368
#include <dae.h> #include <dae/daeDom.h> #include <1.5/dom/domImage.h> #include <dae/daeMetaCMPolicy.h> #include <dae/daeMetaSequence.h> #include <dae/daeMetaChoice.h> #include <dae/daeMetaGroup.h> #include <dae/daeMetaAny.h> #include <dae/daeMetaElementAttribute.h> namespace ColladaDOM150 { daeElementRef domImage::create(DAE& dae) { domImageRef ref = new domImage(dae); return ref; } daeMetaElement * domImage::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "image" ); meta->registerClass(domImage::create); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 0, 1 ); mea->setName( "asset" ); mea->setOffset( daeOffsetOf(domImage,elemAsset) ); mea->setElementType( domAsset::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 0, 1 ); mea->setName( "renderable" ); mea->setOffset( daeOffsetOf(domImage,elemRenderable) ); mea->setElementType( domImage::domRenderable::registerElement(dae) ); cm->appendChild( mea ); cm = new daeMetaChoice( meta, cm, 0, 2, 0, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "init_from" ); mea->setOffset( daeOffsetOf(domImage,elemInit_from) ); mea->setElementType( domImage::domInit_from::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "create_2d" ); mea->setOffset( daeOffsetOf(domImage,elemCreate_2d) ); mea->setElementType( domImage::domCreate_2d::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "create_3d" ); mea->setOffset( daeOffsetOf(domImage,elemCreate_3d) ); mea->setElementType( domImage::domCreate_3d::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "create_cube" ); mea->setOffset( daeOffsetOf(domImage,elemCreate_cube) ); mea->setElementType( domImage::domCreate_cube::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); mea = new daeMetaElementArrayAttribute( meta, cm, 3, 0, -1 ); mea->setName( "extra" ); mea->setOffset( daeOffsetOf(domImage,elemExtra_array) ); mea->setElementType( domExtra::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 3 ); meta->setCMRoot( cm ); // Ordered list of sub-elements meta->addContents(daeOffsetOf(domImage,_contents)); meta->addContentsOrder(daeOffsetOf(domImage,_contentsOrder)); meta->addCMDataArray(daeOffsetOf(domImage,_CMData), 1); // Add attribute: id { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "id" ); ma->setType( dae.getAtomicTypes().get("xsID")); ma->setOffset( daeOffsetOf( domImage , attrId )); ma->setContainer( meta ); meta->appendAttribute(ma); } // Add attribute: sid { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "sid" ); ma->setType( dae.getAtomicTypes().get("Sid")); ma->setOffset( daeOffsetOf( domImage , attrSid )); ma->setContainer( meta ); meta->appendAttribute(ma); } // Add attribute: name { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "name" ); ma->setType( dae.getAtomicTypes().get("xsToken")); ma->setOffset( daeOffsetOf( domImage , attrName )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage)); meta->validate(); return meta; } daeElementRef domImage::domRenderable::create(DAE& dae) { domImage::domRenderableRef ref = new domImage::domRenderable(dae); return ref; } daeMetaElement * domImage::domRenderable::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "renderable" ); meta->registerClass(domImage::domRenderable::create); meta->setIsInnerClass( true ); // Add attribute: share { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "share" ); ma->setType( dae.getAtomicTypes().get("xsBoolean")); ma->setOffset( daeOffsetOf( domImage::domRenderable , attrShare )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domRenderable)); meta->validate(); return meta; } daeElementRef domImage::domInit_from::create(DAE& dae) { domImage::domInit_fromRef ref = new domImage::domInit_from(dae); return ref; } daeMetaElement * domImage::domInit_from::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "init_from" ); meta->registerClass(domImage::domInit_from::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); cm = new daeMetaChoice( meta, cm, 0, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "ref" ); mea->setOffset( daeOffsetOf(domImage::domInit_from,elemRef) ); mea->setElementType( domRef::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "hex" ); mea->setOffset( daeOffsetOf(domImage::domInit_from,elemHex) ); mea->setElementType( domHex::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm->setMaxOrdinal( 0 ); meta->setCMRoot( cm ); // Ordered list of sub-elements meta->addContents(daeOffsetOf(domImage::domInit_from,_contents)); meta->addContentsOrder(daeOffsetOf(domImage::domInit_from,_contentsOrder)); meta->addCMDataArray(daeOffsetOf(domImage::domInit_from,_CMData), 1); // Add attribute: mips_generate { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "mips_generate" ); ma->setType( dae.getAtomicTypes().get("xsBoolean")); ma->setOffset( daeOffsetOf( domImage::domInit_from , attrMips_generate )); ma->setContainer( meta ); ma->setDefaultString( "true"); ma->setIsRequired( false ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domInit_from)); meta->validate(); return meta; } daeElementRef domImage::domCreate_2d::create(DAE& dae) { domImage::domCreate_2dRef ref = new domImage::domCreate_2d(dae); return ref; } daeMetaElement * domImage::domCreate_2d::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "create_2d" ); meta->registerClass(domImage::domCreate_2d::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); cm = new daeMetaChoice( meta, cm, 0, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "size_exact" ); mea->setOffset( daeOffsetOf(domImage::domCreate_2d,elemSize_exact) ); mea->setElementType( domImage::domCreate_2d::domSize_exact::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "size_ratio" ); mea->setOffset( daeOffsetOf(domImage::domCreate_2d,elemSize_ratio) ); mea->setElementType( domImage::domCreate_2d::domSize_ratio::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm = new daeMetaChoice( meta, cm, 1, 1, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "mips" ); mea->setOffset( daeOffsetOf(domImage::domCreate_2d,elemMips) ); mea->setElementType( domImage_mips::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "unnormalized" ); mea->setOffset( daeOffsetOf(domImage::domCreate_2d,elemUnnormalized) ); mea->setElementType( domImage::domCreate_2d::domUnnormalized::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); mea = new daeMetaElementAttribute( meta, cm, 2, 0, 1 ); mea->setName( "array" ); mea->setOffset( daeOffsetOf(domImage::domCreate_2d,elemArray) ); mea->setElementType( domImage::domCreate_2d::domArray::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 3, 0, 1 ); mea->setName( "format" ); mea->setOffset( daeOffsetOf(domImage::domCreate_2d,elemFormat) ); mea->setElementType( domImage::domCreate_2d::domFormat::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementArrayAttribute( meta, cm, 4, 0, -1 ); mea->setName( "init_from" ); mea->setOffset( daeOffsetOf(domImage::domCreate_2d,elemInit_from_array) ); mea->setElementType( domImage::domCreate_2d::domInit_from::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 4 ); meta->setCMRoot( cm ); // Ordered list of sub-elements meta->addContents(daeOffsetOf(domImage::domCreate_2d,_contents)); meta->addContentsOrder(daeOffsetOf(domImage::domCreate_2d,_contentsOrder)); meta->addCMDataArray(daeOffsetOf(domImage::domCreate_2d,_CMData), 2); meta->setElementSize(sizeof(domImage::domCreate_2d)); meta->validate(); return meta; } daeElementRef domImage::domCreate_2d::domSize_exact::create(DAE& dae) { domImage::domCreate_2d::domSize_exactRef ref = new domImage::domCreate_2d::domSize_exact(dae); return ref; } daeMetaElement * domImage::domCreate_2d::domSize_exact::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "size_exact" ); meta->registerClass(domImage::domCreate_2d::domSize_exact::create); meta->setIsInnerClass( true ); // Add attribute: width { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "width" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domSize_exact , attrWidth )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: height { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "height" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domSize_exact , attrHeight )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_2d::domSize_exact)); meta->validate(); return meta; } daeElementRef domImage::domCreate_2d::domSize_ratio::create(DAE& dae) { domImage::domCreate_2d::domSize_ratioRef ref = new domImage::domCreate_2d::domSize_ratio(dae); return ref; } daeMetaElement * domImage::domCreate_2d::domSize_ratio::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "size_ratio" ); meta->registerClass(domImage::domCreate_2d::domSize_ratio::create); meta->setIsInnerClass( true ); // Add attribute: width { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "width" ); ma->setType( dae.getAtomicTypes().get("xsFloat")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domSize_ratio , attrWidth )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: height { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "height" ); ma->setType( dae.getAtomicTypes().get("xsFloat")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domSize_ratio , attrHeight )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_2d::domSize_ratio)); meta->validate(); return meta; } daeElementRef domImage::domCreate_2d::domUnnormalized::create(DAE& dae) { domImage::domCreate_2d::domUnnormalizedRef ref = new domImage::domCreate_2d::domUnnormalized(dae); return ref; } daeMetaElement * domImage::domCreate_2d::domUnnormalized::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "unnormalized" ); meta->registerClass(domImage::domCreate_2d::domUnnormalized::create); meta->setIsInnerClass( true ); meta->setElementSize(sizeof(domImage::domCreate_2d::domUnnormalized)); meta->validate(); return meta; } daeElementRef domImage::domCreate_2d::domArray::create(DAE& dae) { domImage::domCreate_2d::domArrayRef ref = new domImage::domCreate_2d::domArray(dae); return ref; } daeMetaElement * domImage::domCreate_2d::domArray::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "array" ); meta->registerClass(domImage::domCreate_2d::domArray::create); meta->setIsInnerClass( true ); // Add attribute: length { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "length" ); ma->setType( dae.getAtomicTypes().get("xsPositiveInteger")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domArray , attrLength )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_2d::domArray)); meta->validate(); return meta; } daeElementRef domImage::domCreate_2d::domFormat::create(DAE& dae) { domImage::domCreate_2d::domFormatRef ref = new domImage::domCreate_2d::domFormat(dae); return ref; } daeMetaElement * domImage::domCreate_2d::domFormat::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "format" ); meta->registerClass(domImage::domCreate_2d::domFormat::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "hint" ); mea->setOffset( daeOffsetOf(domImage::domCreate_2d::domFormat,elemHint) ); mea->setElementType( domImage::domCreate_2d::domFormat::domHint::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 0, 1 ); mea->setName( "exact" ); mea->setOffset( daeOffsetOf(domImage::domCreate_2d::domFormat,elemExact) ); mea->setElementType( domImage::domCreate_2d::domFormat::domExact::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 1 ); meta->setCMRoot( cm ); meta->setElementSize(sizeof(domImage::domCreate_2d::domFormat)); meta->validate(); return meta; } daeElementRef domImage::domCreate_2d::domFormat::domHint::create(DAE& dae) { domImage::domCreate_2d::domFormat::domHintRef ref = new domImage::domCreate_2d::domFormat::domHint(dae); return ref; } daeMetaElement * domImage::domCreate_2d::domFormat::domHint::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "hint" ); meta->registerClass(domImage::domCreate_2d::domFormat::domHint::create); meta->setIsInnerClass( true ); // Add attribute: channels { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "channels" ); ma->setType( dae.getAtomicTypes().get("Image_format_hint_channels")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domFormat::domHint , attrChannels )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: range { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "range" ); ma->setType( dae.getAtomicTypes().get("Image_format_hint_range")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domFormat::domHint , attrRange )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: precision { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "precision" ); ma->setType( dae.getAtomicTypes().get("Image_format_hint_precision")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domFormat::domHint , attrPrecision )); ma->setContainer( meta ); ma->setDefaultString( "DEFAULT"); meta->appendAttribute(ma); } // Add attribute: space { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "space" ); ma->setType( dae.getAtomicTypes().get("xsToken")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domFormat::domHint , attrSpace )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_2d::domFormat::domHint)); meta->validate(); return meta; } daeElementRef domImage::domCreate_2d::domFormat::domExact::create(DAE& dae) { domImage::domCreate_2d::domFormat::domExactRef ref = new domImage::domCreate_2d::domFormat::domExact(dae); return ref; } daeMetaElement * domImage::domCreate_2d::domFormat::domExact::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "exact" ); meta->registerClass(domImage::domCreate_2d::domFormat::domExact::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsToken")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domFormat::domExact , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_2d::domFormat::domExact)); meta->validate(); return meta; } daeElementRef domImage::domCreate_2d::domInit_from::create(DAE& dae) { domImage::domCreate_2d::domInit_fromRef ref = new domImage::domCreate_2d::domInit_from(dae); return ref; } daeMetaElement * domImage::domCreate_2d::domInit_from::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "init_from" ); meta->registerClass(domImage::domCreate_2d::domInit_from::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); cm = new daeMetaChoice( meta, cm, 0, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "ref" ); mea->setOffset( daeOffsetOf(domImage::domCreate_2d::domInit_from,elemRef) ); mea->setElementType( domRef::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "hex" ); mea->setOffset( daeOffsetOf(domImage::domCreate_2d::domInit_from,elemHex) ); mea->setElementType( domHex::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm->setMaxOrdinal( 0 ); meta->setCMRoot( cm ); // Ordered list of sub-elements meta->addContents(daeOffsetOf(domImage::domCreate_2d::domInit_from,_contents)); meta->addContentsOrder(daeOffsetOf(domImage::domCreate_2d::domInit_from,_contentsOrder)); meta->addCMDataArray(daeOffsetOf(domImage::domCreate_2d::domInit_from,_CMData), 1); // Add attribute: mip_index { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "mip_index" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domInit_from , attrMip_index )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: array_index { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "array_index" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_2d::domInit_from , attrArray_index )); ma->setContainer( meta ); ma->setDefaultString( "0"); ma->setIsRequired( false ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_2d::domInit_from)); meta->validate(); return meta; } daeElementRef domImage::domCreate_3d::create(DAE& dae) { domImage::domCreate_3dRef ref = new domImage::domCreate_3d(dae); return ref; } daeMetaElement * domImage::domCreate_3d::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "create_3d" ); meta->registerClass(domImage::domCreate_3d::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "size" ); mea->setOffset( daeOffsetOf(domImage::domCreate_3d,elemSize) ); mea->setElementType( domImage::domCreate_3d::domSize::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 1, 1 ); mea->setName( "mips" ); mea->setOffset( daeOffsetOf(domImage::domCreate_3d,elemMips) ); mea->setElementType( domImage_mips::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 2, 0, 1 ); mea->setName( "array" ); mea->setOffset( daeOffsetOf(domImage::domCreate_3d,elemArray) ); mea->setElementType( domImage::domCreate_3d::domArray::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 3, 0, 1 ); mea->setName( "format" ); mea->setOffset( daeOffsetOf(domImage::domCreate_3d,elemFormat) ); mea->setElementType( domImage::domCreate_3d::domFormat::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementArrayAttribute( meta, cm, 4, 0, -1 ); mea->setName( "init_from" ); mea->setOffset( daeOffsetOf(domImage::domCreate_3d,elemInit_from_array) ); mea->setElementType( domImage::domCreate_3d::domInit_from::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 4 ); meta->setCMRoot( cm ); meta->setElementSize(sizeof(domImage::domCreate_3d)); meta->validate(); return meta; } daeElementRef domImage::domCreate_3d::domSize::create(DAE& dae) { domImage::domCreate_3d::domSizeRef ref = new domImage::domCreate_3d::domSize(dae); return ref; } daeMetaElement * domImage::domCreate_3d::domSize::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "size" ); meta->registerClass(domImage::domCreate_3d::domSize::create); meta->setIsInnerClass( true ); // Add attribute: width { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "width" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domSize , attrWidth )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: height { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "height" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domSize , attrHeight )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: depth { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "depth" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domSize , attrDepth )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_3d::domSize)); meta->validate(); return meta; } daeElementRef domImage::domCreate_3d::domArray::create(DAE& dae) { domImage::domCreate_3d::domArrayRef ref = new domImage::domCreate_3d::domArray(dae); return ref; } daeMetaElement * domImage::domCreate_3d::domArray::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "array" ); meta->registerClass(domImage::domCreate_3d::domArray::create); meta->setIsInnerClass( true ); // Add attribute: length { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "length" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domArray , attrLength )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_3d::domArray)); meta->validate(); return meta; } daeElementRef domImage::domCreate_3d::domFormat::create(DAE& dae) { domImage::domCreate_3d::domFormatRef ref = new domImage::domCreate_3d::domFormat(dae); return ref; } daeMetaElement * domImage::domCreate_3d::domFormat::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "format" ); meta->registerClass(domImage::domCreate_3d::domFormat::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "hint" ); mea->setOffset( daeOffsetOf(domImage::domCreate_3d::domFormat,elemHint) ); mea->setElementType( domImage::domCreate_3d::domFormat::domHint::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 0, 1 ); mea->setName( "exact" ); mea->setOffset( daeOffsetOf(domImage::domCreate_3d::domFormat,elemExact) ); mea->setElementType( domImage::domCreate_3d::domFormat::domExact::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 1 ); meta->setCMRoot( cm ); meta->setElementSize(sizeof(domImage::domCreate_3d::domFormat)); meta->validate(); return meta; } daeElementRef domImage::domCreate_3d::domFormat::domHint::create(DAE& dae) { domImage::domCreate_3d::domFormat::domHintRef ref = new domImage::domCreate_3d::domFormat::domHint(dae); return ref; } daeMetaElement * domImage::domCreate_3d::domFormat::domHint::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "hint" ); meta->registerClass(domImage::domCreate_3d::domFormat::domHint::create); meta->setIsInnerClass( true ); // Add attribute: channels { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "channels" ); ma->setType( dae.getAtomicTypes().get("Image_format_hint_channels")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domFormat::domHint , attrChannels )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: range { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "range" ); ma->setType( dae.getAtomicTypes().get("Image_format_hint_range")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domFormat::domHint , attrRange )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: precision { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "precision" ); ma->setType( dae.getAtomicTypes().get("Image_format_hint_precision")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domFormat::domHint , attrPrecision )); ma->setContainer( meta ); ma->setDefaultString( "DEFAULT"); meta->appendAttribute(ma); } // Add attribute: space { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "space" ); ma->setType( dae.getAtomicTypes().get("xsToken")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domFormat::domHint , attrSpace )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_3d::domFormat::domHint)); meta->validate(); return meta; } daeElementRef domImage::domCreate_3d::domFormat::domExact::create(DAE& dae) { domImage::domCreate_3d::domFormat::domExactRef ref = new domImage::domCreate_3d::domFormat::domExact(dae); return ref; } daeMetaElement * domImage::domCreate_3d::domFormat::domExact::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "exact" ); meta->registerClass(domImage::domCreate_3d::domFormat::domExact::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsToken")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domFormat::domExact , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_3d::domFormat::domExact)); meta->validate(); return meta; } daeElementRef domImage::domCreate_3d::domInit_from::create(DAE& dae) { domImage::domCreate_3d::domInit_fromRef ref = new domImage::domCreate_3d::domInit_from(dae); return ref; } daeMetaElement * domImage::domCreate_3d::domInit_from::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "init_from" ); meta->registerClass(domImage::domCreate_3d::domInit_from::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); cm = new daeMetaChoice( meta, cm, 0, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "ref" ); mea->setOffset( daeOffsetOf(domImage::domCreate_3d::domInit_from,elemRef) ); mea->setElementType( domRef::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "hex" ); mea->setOffset( daeOffsetOf(domImage::domCreate_3d::domInit_from,elemHex) ); mea->setElementType( domHex::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm->setMaxOrdinal( 0 ); meta->setCMRoot( cm ); // Ordered list of sub-elements meta->addContents(daeOffsetOf(domImage::domCreate_3d::domInit_from,_contents)); meta->addContentsOrder(daeOffsetOf(domImage::domCreate_3d::domInit_from,_contentsOrder)); meta->addCMDataArray(daeOffsetOf(domImage::domCreate_3d::domInit_from,_CMData), 1); // Add attribute: depth { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "depth" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domInit_from , attrDepth )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: mip_index { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "mip_index" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domInit_from , attrMip_index )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: array_index { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "array_index" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_3d::domInit_from , attrArray_index )); ma->setContainer( meta ); ma->setDefaultString( "0"); ma->setIsRequired( false ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_3d::domInit_from)); meta->validate(); return meta; } daeElementRef domImage::domCreate_cube::create(DAE& dae) { domImage::domCreate_cubeRef ref = new domImage::domCreate_cube(dae); return ref; } daeMetaElement * domImage::domCreate_cube::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "create_cube" ); meta->registerClass(domImage::domCreate_cube::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "size" ); mea->setOffset( daeOffsetOf(domImage::domCreate_cube,elemSize) ); mea->setElementType( domImage::domCreate_cube::domSize::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 1, 1 ); mea->setName( "mips" ); mea->setOffset( daeOffsetOf(domImage::domCreate_cube,elemMips) ); mea->setElementType( domImage_mips::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 2, 0, 1 ); mea->setName( "array" ); mea->setOffset( daeOffsetOf(domImage::domCreate_cube,elemArray) ); mea->setElementType( domImage::domCreate_cube::domArray::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 3, 0, 1 ); mea->setName( "format" ); mea->setOffset( daeOffsetOf(domImage::domCreate_cube,elemFormat) ); mea->setElementType( domImage::domCreate_cube::domFormat::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementArrayAttribute( meta, cm, 4, 0, -1 ); mea->setName( "init_from" ); mea->setOffset( daeOffsetOf(domImage::domCreate_cube,elemInit_from_array) ); mea->setElementType( domImage::domCreate_cube::domInit_from::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 4 ); meta->setCMRoot( cm ); meta->setElementSize(sizeof(domImage::domCreate_cube)); meta->validate(); return meta; } daeElementRef domImage::domCreate_cube::domSize::create(DAE& dae) { domImage::domCreate_cube::domSizeRef ref = new domImage::domCreate_cube::domSize(dae); return ref; } daeMetaElement * domImage::domCreate_cube::domSize::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "size" ); meta->registerClass(domImage::domCreate_cube::domSize::create); meta->setIsInnerClass( true ); // Add attribute: width { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "width" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_cube::domSize , attrWidth )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_cube::domSize)); meta->validate(); return meta; } daeElementRef domImage::domCreate_cube::domArray::create(DAE& dae) { domImage::domCreate_cube::domArrayRef ref = new domImage::domCreate_cube::domArray(dae); return ref; } daeMetaElement * domImage::domCreate_cube::domArray::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "array" ); meta->registerClass(domImage::domCreate_cube::domArray::create); meta->setIsInnerClass( true ); // Add attribute: length { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "length" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_cube::domArray , attrLength )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_cube::domArray)); meta->validate(); return meta; } daeElementRef domImage::domCreate_cube::domFormat::create(DAE& dae) { domImage::domCreate_cube::domFormatRef ref = new domImage::domCreate_cube::domFormat(dae); return ref; } daeMetaElement * domImage::domCreate_cube::domFormat::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "format" ); meta->registerClass(domImage::domCreate_cube::domFormat::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "hint" ); mea->setOffset( daeOffsetOf(domImage::domCreate_cube::domFormat,elemHint) ); mea->setElementType( domImage::domCreate_cube::domFormat::domHint::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 1, 0, 1 ); mea->setName( "exact" ); mea->setOffset( daeOffsetOf(domImage::domCreate_cube::domFormat,elemExact) ); mea->setElementType( domImage::domCreate_cube::domFormat::domExact::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 1 ); meta->setCMRoot( cm ); meta->setElementSize(sizeof(domImage::domCreate_cube::domFormat)); meta->validate(); return meta; } daeElementRef domImage::domCreate_cube::domFormat::domHint::create(DAE& dae) { domImage::domCreate_cube::domFormat::domHintRef ref = new domImage::domCreate_cube::domFormat::domHint(dae); return ref; } daeMetaElement * domImage::domCreate_cube::domFormat::domHint::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "hint" ); meta->registerClass(domImage::domCreate_cube::domFormat::domHint::create); meta->setIsInnerClass( true ); // Add attribute: channels { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "channels" ); ma->setType( dae.getAtomicTypes().get("Image_format_hint_channels")); ma->setOffset( daeOffsetOf( domImage::domCreate_cube::domFormat::domHint , attrChannels )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: range { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "range" ); ma->setType( dae.getAtomicTypes().get("Image_format_hint_range")); ma->setOffset( daeOffsetOf( domImage::domCreate_cube::domFormat::domHint , attrRange )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: precision { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "precision" ); ma->setType( dae.getAtomicTypes().get("Image_format_hint_precision")); ma->setOffset( daeOffsetOf( domImage::domCreate_cube::domFormat::domHint , attrPrecision )); ma->setContainer( meta ); ma->setDefaultString( "DEFAULT"); meta->appendAttribute(ma); } // Add attribute: space { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "space" ); ma->setType( dae.getAtomicTypes().get("xsToken")); ma->setOffset( daeOffsetOf( domImage::domCreate_cube::domFormat::domHint , attrSpace )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_cube::domFormat::domHint)); meta->validate(); return meta; } daeElementRef domImage::domCreate_cube::domFormat::domExact::create(DAE& dae) { domImage::domCreate_cube::domFormat::domExactRef ref = new domImage::domCreate_cube::domFormat::domExact(dae); return ref; } daeMetaElement * domImage::domCreate_cube::domFormat::domExact::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "exact" ); meta->registerClass(domImage::domCreate_cube::domFormat::domExact::create); meta->setIsInnerClass( true ); // Add attribute: _value { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "_value" ); ma->setType( dae.getAtomicTypes().get("xsToken")); ma->setOffset( daeOffsetOf( domImage::domCreate_cube::domFormat::domExact , _value )); ma->setContainer( meta ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_cube::domFormat::domExact)); meta->validate(); return meta; } daeElementRef domImage::domCreate_cube::domInit_from::create(DAE& dae) { domImage::domCreate_cube::domInit_fromRef ref = new domImage::domCreate_cube::domInit_from(dae); return ref; } daeMetaElement * domImage::domCreate_cube::domInit_from::registerElement(DAE& dae) { daeMetaElement* meta = dae.getMeta(ID()); if ( meta != NULL ) return meta; meta = new daeMetaElement(dae); dae.setMeta(ID(), *meta); meta->setName( "init_from" ); meta->registerClass(domImage::domCreate_cube::domInit_from::create); meta->setIsInnerClass( true ); daeMetaCMPolicy *cm = NULL; daeMetaElementAttribute *mea = NULL; cm = new daeMetaSequence( meta, cm, 0, 1, 1 ); cm = new daeMetaChoice( meta, cm, 0, 0, 1, 1 ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "ref" ); mea->setOffset( daeOffsetOf(domImage::domCreate_cube::domInit_from,elemRef) ); mea->setElementType( domRef::registerElement(dae) ); cm->appendChild( mea ); mea = new daeMetaElementAttribute( meta, cm, 0, 1, 1 ); mea->setName( "hex" ); mea->setOffset( daeOffsetOf(domImage::domCreate_cube::domInit_from,elemHex) ); mea->setElementType( domHex::registerElement(dae) ); cm->appendChild( mea ); cm->setMaxOrdinal( 0 ); cm->getParent()->appendChild( cm ); cm = cm->getParent(); cm->setMaxOrdinal( 0 ); meta->setCMRoot( cm ); // Ordered list of sub-elements meta->addContents(daeOffsetOf(domImage::domCreate_cube::domInit_from,_contents)); meta->addContentsOrder(daeOffsetOf(domImage::domCreate_cube::domInit_from,_contentsOrder)); meta->addCMDataArray(daeOffsetOf(domImage::domCreate_cube::domInit_from,_CMData), 1); // Add attribute: face { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "face" ); ma->setType( dae.getAtomicTypes().get("Image_face")); ma->setOffset( daeOffsetOf( domImage::domCreate_cube::domInit_from , attrFace )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: mip_index { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "mip_index" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_cube::domInit_from , attrMip_index )); ma->setContainer( meta ); ma->setIsRequired( true ); meta->appendAttribute(ma); } // Add attribute: array_index { daeMetaAttribute *ma = new daeMetaAttribute; ma->setName( "array_index" ); ma->setType( dae.getAtomicTypes().get("xsUnsignedInt")); ma->setOffset( daeOffsetOf( domImage::domCreate_cube::domInit_from , attrArray_index )); ma->setContainer( meta ); ma->setDefaultString( "0"); ma->setIsRequired( false ); meta->appendAttribute(ma); } meta->setElementSize(sizeof(domImage::domCreate_cube::domInit_from)); meta->validate(); return meta; } } // ColladaDOM150
jdsika/TUM_HOly
openrave/3rdparty/collada-2.4.0/src/1.5/dom/domImage.cpp
C++
mit
43,590
<?php return [ 'maintenance' => [ 'access' ], 'control_panel' => [ 'access' ] ];
whuailin/dogdie
vendor/anomaly/streams-platform/resources/config/permissions.php
PHP
mit
116
package nxt.http; import nxt.DigitalGoodsStore; import nxt.NxtException; import nxt.db.DbIterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONStreamAware; import javax.servlet.http.HttpServletRequest; import static nxt.http.JSONResponses.MISSING_SELLER; public final class GetDGSPendingPurchases extends APIServlet.APIRequestHandler { static final GetDGSPendingPurchases instance = new GetDGSPendingPurchases(); private GetDGSPendingPurchases() { super(new APITag[] {APITag.DGS}, "seller", "firstIndex", "lastIndex"); } @Override JSONStreamAware processRequest(HttpServletRequest req) throws NxtException { long sellerId = ParameterParser.getSellerId(req); if (sellerId == 0) { return MISSING_SELLER; } int firstIndex = ParameterParser.getFirstIndex(req); int lastIndex = ParameterParser.getLastIndex(req); JSONObject response = new JSONObject(); JSONArray purchasesJSON = new JSONArray(); try (DbIterator<DigitalGoodsStore.Purchase> purchases = DigitalGoodsStore.Purchase.getPendingSellerPurchases(sellerId, firstIndex, lastIndex)) { while (purchases.hasNext()) { purchasesJSON.add(JSONData.purchase(purchases.next())); } } response.put("purchases", purchasesJSON); return response; } }
fimkrypto/nxt
src/java/nxt/http/GetDGSPendingPurchases.java
Java
mit
1,425
<?php namespace Dime\TimetrackerBundle\Entity; use Dime\TimetrackerBundle\Entity\EntityRepository; use Doctrine\ORM\QueryBuilder; /** * UserRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class UserRepository extends EntityRepository { /** * * @param string $text * @param QueryBuilder $qb * * @return UserRepository */ public function search($text, QueryBuilder $qb = null) { return $this; } /** * * @param $date * @param QueryBuilder $qb * * @return UserRepository */ public function scopeByDate($date, QueryBuilder $qb = null) { return $this; } }
JHeimbach/Dime
src/Dime/TimetrackerBundle/Entity/UserRepository.php
PHP
mit
771
wget --quiet \ --method POST \ --header 'content-type: application/json' \ --body-data '{"number":1,"string":"f\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":{}}],"boolean":false}' \ --output-document \ - http://mockbin.com/har
restlet/httpsnippet
test/fixtures/output/shell/wget/application-json.sh
Shell
mit
265
#ifndef THREAD_H #define THREAD_H #include <queue> #include <vector> #include <thread> #include <condition_variable> #include "console/windows_wrap.h" #include "common/ll-deque.h" #include "types.h" template <typename Tvar> class ThreadPool; template <typename Tvar> class ThreadedTask; template <typename Tvar> struct ThreadParams; template <typename Tvar> class Task { public: Task() { } Task(const volatile Task<Tvar> &other) { *this = other; } Task(void (*a)(Tvar *, void *), void *b) { func = a; param = b; } void operator=(const Task &other) { func = other.func; param = other.param; } void operator=(const Task &other) volatile { func = other.func; param = other.param; } void operator=(const volatile Task &other) volatile { func = other.func; param = other.param; } void (*func)(Tvar *, void *); void *param; }; template <typename Tvar> class Thread { public: Thread() { thread_variables = nullptr; } void Init(void *parent, unsigned long (*ThreadProc)(void *)) { ThreadParams<Tvar> *params = new ThreadParams<Tvar>; cv.reset(new std::condition_variable); mutex.reset(new std::mutex); params->parent = parent; params->thread = this; params->vars = new Tvar; running.store(true, std::memory_order_release); thread = std::move(std::thread(ThreadProc, params)); } ~Thread() { delete thread_variables; } Thread(const Thread &other) = delete; std::atomic<bool> running; std::thread thread; Task<Tvar> task; ptr<std::mutex> mutex; ptr<std::condition_variable> cv; Tvar *thread_variables; }; template <typename Tvar> struct ThreadParams { void *parent; Thread<Tvar> *thread; Tvar *vars; }; template <typename Tvar> class PoolThread : public Thread<Tvar> { public: PoolThread() { should_sleep.store(false, std::memory_order_relaxed); } void Init(ThreadPool<Tvar> *pool) { next_free = nullptr; Thread<Tvar>::Init(pool, &PoolThreadProc); } ~PoolThread() {} PoolThread(const PoolThread &other) = delete; void Wake() { { std::lock_guard<std::mutex> lock(*this->mutex); this->running.store(true, std::memory_order_release); } this->cv->notify_one(); } bool IsRunning() const { return this->running.load(std::memory_order_acquire); } private: static unsigned long PoolThreadProc(void *param) { ThreadParams<Tvar> *params = (ThreadParams<Tvar> *)param; ThreadPool<Tvar> *pool = (ThreadPool<Tvar> *)params->parent; PoolThread<Tvar> *thread = (PoolThread<Tvar> *)params->thread; thread->thread_variables = params->vars; delete params; while (true) { while (!pool->RequestTask(thread)) thread->Sleep(); // Täs pitäs olla joku if (killed) break; auto param = thread->task.param; (*thread->task.func)(thread->thread_variables, param); } return 0; } void Sleep() { // RequestTask sets runnign to false as it has to be done before adding thread to idle list std::unique_lock<std::mutex> lock(*this->mutex); this->cv->wait(lock, [this](){ return this->running.load(std::memory_order_acquire) == true; }); should_sleep.store(false, std::memory_order_relaxed); } public: std::atomic<bool> should_sleep; PoolThread *next_free; }; template <typename Tvar> class ThreadPool { public: ThreadPool() { state.store(0, std::memory_order_relaxed); sleep_count.store(0, std::memory_order_relaxed); free_threads.store(nullptr, std::memory_order_relaxed); } ThreadPool(int size) { Init(size); } void Init(int size) { for (int i = 0; i < size; i++) { threads.emplace_back(new PoolThread<Tvar>); } for (auto &thread : threads) { thread->Init(this); } } ~ThreadPool() {} int GetThreadCount() { return threads.size(); } void ClearAll() { Task<Tvar> tmp; tasks.clear(); for (auto &thread : threads) { thread->should_sleep.store(true, std::memory_order_relaxed); } for (auto &thread : threads) { while (thread->IsRunning()) { Sleep(0); // The first should_sleep may get overwritten if thread had just awaken thread->should_sleep.store(true, std::memory_order_relaxed); } } } // Ironically, this function can only be called from one thread at time template <typename Param> void AddTask(void (*func)(Tvar *, Param *), Param *param) { auto old_state = state.load(std::memory_order_acquire); tasks.push_back(Task<Tvar>((void (*)(Tvar *, void *))func, param)); while (true) { PoolThread<Tvar> *thread = free_threads.load(std::memory_order_acquire); if (thread == ThreadsBusy) { // Return if no workers have gone sleep during this if (state.compare_exchange_strong(old_state, old_state + 1, std::memory_order_release, std::memory_order_relaxed) == true) { return; } // However, the sleeping thread might not have yet added itself to the free_threads list while (thread == ThreadsBusy) thread = free_threads.load(std::memory_order_acquire); } // Now there is at least one sleeping thread, fight until we get one of them while (true) { if (free_threads.compare_exchange_strong(thread, thread->next_free, std::memory_order_release, std::memory_order_relaxed) == true) { thread->Wake(); return; } } } } bool RequestTask(PoolThread<Tvar> *thread) { Task<Tvar> task; auto old_state = state.load(std::memory_order_acquire); while (true) { int spincount = 1000; while (spincount--) { if (tasks.pop_front(&thread->task)) // Success { return true; } if (thread->should_sleep.load(std::memory_order_relaxed) == true || SwitchToThread() == 0) break; } // Either new task has been added or false alarm (Other worker thread doing same thing) if (state.compare_exchange_strong(old_state, old_state + 1, std::memory_order_release, std::memory_order_acquire) == false) continue; thread->running.store(false, std::memory_order_release); if (PerfTest) sleep_count.fetch_add(1, std::memory_order_relaxed); PoolThread<Tvar> *free_threads_head = free_threads.load(std::memory_order_acquire); while (true) { thread->next_free = free_threads_head; if (free_threads.compare_exchange_strong(free_threads_head, thread, std::memory_order_release, std::memory_order_relaxed) == true) return false; } } } template <typename Func> void ForEachThread(Func func) { for (auto &thread : threads) func(thread->thread_variables); } // Can be used to tell how many sleep calls have occured int GetSleepCount() { return sleep_count.load(std::memory_order_relaxed); } private: std::atomic<unsigned int> sleep_count; std::vector<ptr<PoolThread<Tvar>>> threads; Common::LocklessQueue<Task<Tvar>> tasks; std::atomic<PoolThread<Tvar> *> free_threads; // linked list head std::atomic<unsigned int> state; static constexpr PoolThread<Tvar> *const ThreadsBusy = (PoolThread<Tvar> *)0x0; }; #endif // THREAD_H
SCMapsAndMods/teippi
src/thread.h
C
mit
8,969
goog.provide('used.not.provided.a'); /** * @interface * @template T */ used.not.provided.I = function() {}; /** * @constructor * @implements {used.not.provided.I<number>} */ used.not.provided.C = function() {}; /** * @type {!used.not.provided.C} */ used.not.provided.a = new used.not.provided.C();
rehmsen/clutz
src/test/java/com/google/javascript/clutz/type_used_but_not_provided.js
JavaScript
mit
308
# frozen_string_literal: true FactoryBot.define do factory :application_setting do default_projects_limit { 42 } import_sources { [] } end end
mmkassem/gitlabhq
spec/factories/application_settings.rb
Ruby
mit
156
--- name: Albertsons address_1: 220 E Bonita Ave address_2: '' city: San Dimas state: CA zip: '91773' phone: (909) 599-8836 latitude: '34.105927' longitude: '-117.803449' category: Supermarket website: 'http://www.albertsons.com' active: '' daycode1: Mon day1_open: '700' day1_close: '2300' daycode2: Tue day2_open: '700' day2_close: '2300' daycode3: Wed day3_open: '700' day3_close: '2300' daycode4: Thu day4_open: '700' day4_close: '2300' daycode5: Fri day5_open: '700' day5_close: '2300' daycode6: Sat day6_open: '700' day6_close: '2300' daycode7: Sun day7_open: '700' day7_close: '2300' title: 'Albertsons, Food Oasis Los Angeles' uri: /supermarket/albertsons-220-e-bonita-ave/ formatted_daycode1: Monday formatted_day1_open: 7am formatted_day1_close: 11pm formatted_daycode2: Tuesday formatted_day2_open: 7am formatted_day2_close: 11pm formatted_daycode3: Wednesday formatted_day3_open: 7am formatted_day3_close: 11pm formatted_daycode4: Thursday formatted_day4_open: 7am formatted_day4_close: 11pm formatted_daycode5: Friday formatted_day5_open: 7am formatted_day5_close: 11pm formatted_daycode6: Saturday formatted_day6_open: 7am formatted_day6_close: 11pm formatted_daycode7: Sunday formatted_day7_open: 7am formatted_day7_close: 11pm ---
kathwang21/site
_supermarket/albertsons-220-e-bonita-ave.md
Markdown
mit
1,250
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<1fa15bfe295a3f3408fcd20cddce639f>> * @flow * @lightSyntaxTransform * @nogrep */ /* eslint-disable */ 'use strict'; /*:: import type { ConcreteRequest, Query } from 'relay-runtime'; type RelayMockPayloadGeneratorTest2Fragment$fragmentType = any; export type RelayMockPayloadGeneratorTest3Query$variables = {| condition: boolean, |}; export type RelayMockPayloadGeneratorTest3Query$data = {| +node: ?{| +$fragmentSpreads: RelayMockPayloadGeneratorTest2Fragment$fragmentType, |}, |}; export type RelayMockPayloadGeneratorTest3Query = {| variables: RelayMockPayloadGeneratorTest3Query$variables, response: RelayMockPayloadGeneratorTest3Query$data, |}; */ var node/*: ConcreteRequest*/ = (function(){ var v0 = [ { "defaultValue": null, "kind": "LocalArgument", "name": "condition" } ], v1 = [ { "kind": "Literal", "name": "id", "value": "my-id" } ], v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }; return { "fragment": { "argumentDefinitions": (v0/*: any*/), "kind": "Fragment", "metadata": null, "name": "RelayMockPayloadGeneratorTest3Query", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "RelayMockPayloadGeneratorTest2Fragment" } ], "storageKey": "node(id:\"my-id\")" } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": (v0/*: any*/), "kind": "Operation", "name": "RelayMockPayloadGeneratorTest3Query", "selections": [ { "alias": null, "args": (v1/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, (v2/*: any*/), { "kind": "InlineFragment", "selections": [ (v3/*: any*/), { "alias": null, "args": null, "concreteType": "User", "kind": "LinkedField", "name": "author", "plural": false, "selections": [ (v2/*: any*/), (v3/*: any*/), { "alias": "authorID", "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "username", "storageKey": null } ], "storageKey": null }, { "condition": "condition", "kind": "Condition", "passingValue": true, "selections": [ { "alias": null, "args": null, "concreteType": "User", "kind": "LinkedField", "name": "author", "plural": false, "selections": [ { "alias": "myId", "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, { "alias": "myUsername", "args": null, "kind": "ScalarField", "name": "username", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "emailAddresses", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Date", "kind": "LinkedField", "name": "birthdate", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "day", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "month", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "year", "storageKey": null } ], "storageKey": null } ], "storageKey": null } ] } ], "type": "User", "abstractKey": null } ], "storageKey": "node(id:\"my-id\")" } ] }, "params": { "cacheID": "7b4112ccf5fd820c35c73aa9b6a4f3c8", "id": null, "metadata": {}, "name": "RelayMockPayloadGeneratorTest3Query", "operationKind": "query", "text": "query RelayMockPayloadGeneratorTest3Query(\n $condition: Boolean!\n) {\n node(id: \"my-id\") {\n __typename\n ...RelayMockPayloadGeneratorTest2Fragment\n id\n }\n}\n\nfragment RelayMockPayloadGeneratorTest2Fragment on User {\n id\n name\n author {\n id\n name\n authorID: id\n username\n }\n author @include(if: $condition) {\n myId: id\n myUsername: username\n emailAddresses\n birthdate {\n day\n month\n year\n }\n id\n }\n}\n" } }; })(); if (__DEV__) { (node/*: any*/).hash = "02749249be24669737cad13a3b9b3559"; } module.exports = ((node/*: any*/)/*: Query< RelayMockPayloadGeneratorTest3Query$variables, RelayMockPayloadGeneratorTest3Query$data, >*/);
facebook/relay
packages/relay-test-utils/__tests__/__generated__/RelayMockPayloadGeneratorTest3Query.graphql.js
JavaScript
mit
7,225
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/id_map.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class TestObject { }; class DestructorCounter { public: explicit DestructorCounter(int* counter) : counter_(counter) {} ~DestructorCounter() { ++(*counter_); } private: int* counter_; }; TEST(IDMapTest, Basic) { IDMap<TestObject> map; EXPECT_TRUE(map.IsEmpty()); EXPECT_EQ(0U, map.size()); TestObject obj1; TestObject obj2; int32 id1 = map.Add(&obj1); EXPECT_FALSE(map.IsEmpty()); EXPECT_EQ(1U, map.size()); EXPECT_EQ(&obj1, map.Lookup(id1)); int32 id2 = map.Add(&obj2); EXPECT_FALSE(map.IsEmpty()); EXPECT_EQ(2U, map.size()); EXPECT_EQ(&obj1, map.Lookup(id1)); EXPECT_EQ(&obj2, map.Lookup(id2)); map.Remove(id1); EXPECT_FALSE(map.IsEmpty()); EXPECT_EQ(1U, map.size()); map.Remove(id2); EXPECT_TRUE(map.IsEmpty()); EXPECT_EQ(0U, map.size()); map.AddWithID(&obj1, 1); map.AddWithID(&obj2, 2); EXPECT_EQ(&obj1, map.Lookup(1)); EXPECT_EQ(&obj2, map.Lookup(2)); EXPECT_EQ(&obj2, map.Replace(2, &obj1)); EXPECT_EQ(&obj1, map.Lookup(2)); EXPECT_EQ(0, map.iteration_depth()); } TEST(IDMapTest, IteratorRemainsValidWhenRemovingCurrentElement) { IDMap<TestObject> map; TestObject obj1; TestObject obj2; TestObject obj3; map.Add(&obj1); map.Add(&obj2); map.Add(&obj3); { IDMap<TestObject>::const_iterator iter(&map); EXPECT_EQ(1, map.iteration_depth()); while (!iter.IsAtEnd()) { map.Remove(iter.GetCurrentKey()); iter.Advance(); } // Test that while an iterator is still in scope, we get the map emptiness // right (http://crbug.com/35571). EXPECT_TRUE(map.IsEmpty()); EXPECT_EQ(0U, map.size()); } EXPECT_TRUE(map.IsEmpty()); EXPECT_EQ(0U, map.size()); EXPECT_EQ(0, map.iteration_depth()); } TEST(IDMapTest, IteratorRemainsValidWhenRemovingOtherElements) { IDMap<TestObject> map; const int kCount = 5; TestObject obj[kCount]; for (int i = 0; i < kCount; i++) map.Add(&obj[i]); // IDMap uses a hash_map, which has no predictable iteration order. int32 ids_in_iteration_order[kCount]; const TestObject* objs_in_iteration_order[kCount]; int counter = 0; for (IDMap<TestObject>::const_iterator iter(&map); !iter.IsAtEnd(); iter.Advance()) { ids_in_iteration_order[counter] = iter.GetCurrentKey(); objs_in_iteration_order[counter] = iter.GetCurrentValue(); counter++; } counter = 0; for (IDMap<TestObject>::const_iterator iter(&map); !iter.IsAtEnd(); iter.Advance()) { EXPECT_EQ(1, map.iteration_depth()); switch (counter) { case 0: EXPECT_EQ(ids_in_iteration_order[0], iter.GetCurrentKey()); EXPECT_EQ(objs_in_iteration_order[0], iter.GetCurrentValue()); map.Remove(ids_in_iteration_order[1]); break; case 1: EXPECT_EQ(ids_in_iteration_order[2], iter.GetCurrentKey()); EXPECT_EQ(objs_in_iteration_order[2], iter.GetCurrentValue()); map.Remove(ids_in_iteration_order[3]); break; case 2: EXPECT_EQ(ids_in_iteration_order[4], iter.GetCurrentKey()); EXPECT_EQ(objs_in_iteration_order[4], iter.GetCurrentValue()); map.Remove(ids_in_iteration_order[0]); break; default: FAIL() << "should not have that many elements"; break; } counter++; } EXPECT_EQ(0, map.iteration_depth()); } TEST(IDMapTest, CopyIterator) { IDMap<TestObject> map; TestObject obj1; TestObject obj2; TestObject obj3; map.Add(&obj1); map.Add(&obj2); map.Add(&obj3); EXPECT_EQ(0, map.iteration_depth()); { IDMap<TestObject>::const_iterator iter1(&map); EXPECT_EQ(1, map.iteration_depth()); // Make sure that copying the iterator correctly increments // map's iteration depth. IDMap<TestObject>::const_iterator iter2(iter1); EXPECT_EQ(2, map.iteration_depth()); } // Make sure after destroying all iterators the map's iteration depth // returns to initial state. EXPECT_EQ(0, map.iteration_depth()); } TEST(IDMapTest, AssignIterator) { IDMap<TestObject> map; TestObject obj1; TestObject obj2; TestObject obj3; map.Add(&obj1); map.Add(&obj2); map.Add(&obj3); EXPECT_EQ(0, map.iteration_depth()); { IDMap<TestObject>::const_iterator iter1(&map); EXPECT_EQ(1, map.iteration_depth()); IDMap<TestObject>::const_iterator iter2(&map); EXPECT_EQ(2, map.iteration_depth()); // Make sure that assigning the iterator correctly updates // map's iteration depth (-1 for destruction, +1 for assignment). EXPECT_EQ(2, map.iteration_depth()); } // Make sure after destroying all iterators the map's iteration depth // returns to initial state. EXPECT_EQ(0, map.iteration_depth()); } TEST(IDMapTest, IteratorRemainsValidWhenClearing) { IDMap<TestObject> map; const int kCount = 5; TestObject obj[kCount]; for (int i = 0; i < kCount; i++) map.Add(&obj[i]); // IDMap uses a hash_map, which has no predictable iteration order. int32 ids_in_iteration_order[kCount]; const TestObject* objs_in_iteration_order[kCount]; int counter = 0; for (IDMap<TestObject>::const_iterator iter(&map); !iter.IsAtEnd(); iter.Advance()) { ids_in_iteration_order[counter] = iter.GetCurrentKey(); objs_in_iteration_order[counter] = iter.GetCurrentValue(); counter++; } counter = 0; for (IDMap<TestObject>::const_iterator iter(&map); !iter.IsAtEnd(); iter.Advance()) { switch (counter) { case 0: EXPECT_EQ(ids_in_iteration_order[0], iter.GetCurrentKey()); EXPECT_EQ(objs_in_iteration_order[0], iter.GetCurrentValue()); break; case 1: EXPECT_EQ(ids_in_iteration_order[1], iter.GetCurrentKey()); EXPECT_EQ(objs_in_iteration_order[1], iter.GetCurrentValue()); map.Clear(); EXPECT_TRUE(map.IsEmpty()); EXPECT_EQ(0U, map.size()); break; default: FAIL() << "should not have that many elements"; break; } counter++; } EXPECT_TRUE(map.IsEmpty()); EXPECT_EQ(0U, map.size()); } TEST(IDMapTest, OwningPointersDeletesThemOnRemove) { const int kCount = 3; int external_del_count = 0; DestructorCounter* external_obj[kCount]; int map_external_ids[kCount]; int owned_del_count = 0; DestructorCounter* owned_obj[kCount]; int map_owned_ids[kCount]; IDMap<DestructorCounter> map_external; IDMap<DestructorCounter, IDMapOwnPointer> map_owned; for (int i = 0; i < kCount; ++i) { external_obj[i] = new DestructorCounter(&external_del_count); map_external_ids[i] = map_external.Add(external_obj[i]); owned_obj[i] = new DestructorCounter(&owned_del_count); map_owned_ids[i] = map_owned.Add(owned_obj[i]); } for (int i = 0; i < kCount; ++i) { EXPECT_EQ(external_del_count, 0); EXPECT_EQ(owned_del_count, i); map_external.Remove(map_external_ids[i]); map_owned.Remove(map_owned_ids[i]); } for (int i = 0; i < kCount; ++i) { delete external_obj[i]; } EXPECT_EQ(external_del_count, kCount); EXPECT_EQ(owned_del_count, kCount); } TEST(IDMapTest, OwningPointersDeletesThemOnClear) { const int kCount = 3; int external_del_count = 0; DestructorCounter* external_obj[kCount]; int owned_del_count = 0; DestructorCounter* owned_obj[kCount]; IDMap<DestructorCounter> map_external; IDMap<DestructorCounter, IDMapOwnPointer> map_owned; for (int i = 0; i < kCount; ++i) { external_obj[i] = new DestructorCounter(&external_del_count); map_external.Add(external_obj[i]); owned_obj[i] = new DestructorCounter(&owned_del_count); map_owned.Add(owned_obj[i]); } EXPECT_EQ(external_del_count, 0); EXPECT_EQ(owned_del_count, 0); map_external.Clear(); map_owned.Clear(); EXPECT_EQ(external_del_count, 0); EXPECT_EQ(owned_del_count, kCount); for (int i = 0; i < kCount; ++i) { delete external_obj[i]; } EXPECT_EQ(external_del_count, kCount); EXPECT_EQ(owned_del_count, kCount); } TEST(IDMapTest, OwningPointersDeletesThemOnDestruct) { const int kCount = 3; int external_del_count = 0; DestructorCounter* external_obj[kCount]; int owned_del_count = 0; DestructorCounter* owned_obj[kCount]; { IDMap<DestructorCounter> map_external; IDMap<DestructorCounter, IDMapOwnPointer> map_owned; for (int i = 0; i < kCount; ++i) { external_obj[i] = new DestructorCounter(&external_del_count); map_external.Add(external_obj[i]); owned_obj[i] = new DestructorCounter(&owned_del_count); map_owned.Add(owned_obj[i]); } } EXPECT_EQ(external_del_count, 0); for (int i = 0; i < kCount; ++i) { delete external_obj[i]; } EXPECT_EQ(external_del_count, kCount); EXPECT_EQ(owned_del_count, kCount); } TEST(IDMapTest, Int64KeyType) { IDMap<TestObject, IDMapExternalPointer, int64_t> map; TestObject obj1; const int64_t kId1 = 999999999999999999; map.AddWithID(&obj1, kId1); EXPECT_EQ(&obj1, map.Lookup(kId1)); map.Remove(kId1); EXPECT_TRUE(map.IsEmpty()); } } // namespace
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/base/id_map_unittest.cc
C++
mit
9,277
<!DOCTYPE html> <html> <head> <title>Test QuarantineMode</title> </head> <body> </body> </html>
VasilyStrelyaev/testcafe
test/functional/fixtures/quarantine/pages/index.html
HTML
mit
100
/** * @license Angular v4.0.2 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */ import { EventEmitter, Injectable } from '@angular/core'; import { LocationStrategy } from '@angular/common'; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A spy for {@link Location} that allows tests to fire simulated location events. * * @experimental */ class SpyLocation { constructor() { this.urlChanges = []; this._history = [new LocationState('', '')]; this._historyIndex = 0; /** @internal */ this._subject = new EventEmitter(); /** @internal */ this._baseHref = ''; /** @internal */ this._platformStrategy = null; } setInitialPath(url) { this._history[this._historyIndex].path = url; } setBaseHref(url) { this._baseHref = url; } path() { return this._history[this._historyIndex].path; } isCurrentPathEqualTo(path, query = '') { const givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path; const currPath = this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path(); return currPath == givenPath + (query.length > 0 ? ('?' + query) : ''); } simulateUrlPop(pathname) { this._subject.emit({ 'url': pathname, 'pop': true }); } simulateHashChange(pathname) { // Because we don't prevent the native event, the browser will independently update the path this.setInitialPath(pathname); this.urlChanges.push('hash: ' + pathname); this._subject.emit({ 'url': pathname, 'pop': true, 'type': 'hashchange' }); } prepareExternalUrl(url) { if (url.length > 0 && !url.startsWith('/')) { url = '/' + url; } return this._baseHref + url; } go(path, query = '') { path = this.prepareExternalUrl(path); if (this._historyIndex > 0) { this._history.splice(this._historyIndex + 1); } this._history.push(new LocationState(path, query)); this._historyIndex = this._history.length - 1; const locationState = this._history[this._historyIndex - 1]; if (locationState.path == path && locationState.query == query) { return; } const url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push(url); this._subject.emit({ 'url': url, 'pop': false }); } replaceState(path, query = '') { path = this.prepareExternalUrl(path); const history = this._history[this._historyIndex]; if (history.path == path && history.query == query) { return; } history.path = path; history.query = query; const url = path + (query.length > 0 ? ('?' + query) : ''); this.urlChanges.push('replace: ' + url); } forward() { if (this._historyIndex < (this._history.length - 1)) { this._historyIndex++; this._subject.emit({ 'url': this.path(), 'pop': true }); } } back() { if (this._historyIndex > 0) { this._historyIndex--; this._subject.emit({ 'url': this.path(), 'pop': true }); } } subscribe(onNext, onThrow = null, onReturn = null) { return this._subject.subscribe({ next: onNext, error: onThrow, complete: onReturn }); } normalize(url) { return null; } } SpyLocation.decorators = [ { type: Injectable }, ]; /** @nocollapse */ SpyLocation.ctorParameters = () => []; class LocationState { constructor(path, query) { this.path = path; this.query = query; } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * A mock implementation of {@link LocationStrategy} that allows tests to fire simulated * location events. * * @stable */ class MockLocationStrategy extends LocationStrategy { constructor() { super(); this.internalBaseHref = '/'; this.internalPath = '/'; this.internalTitle = ''; this.urlChanges = []; /** @internal */ this._subject = new EventEmitter(); } simulatePopState(url) { this.internalPath = url; this._subject.emit(new _MockPopStateEvent(this.path())); } path(includeHash = false) { return this.internalPath; } prepareExternalUrl(internal) { if (internal.startsWith('/') && this.internalBaseHref.endsWith('/')) { return this.internalBaseHref + internal.substring(1); } return this.internalBaseHref + internal; } pushState(ctx, title, path, query) { this.internalTitle = title; const url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; const externalUrl = this.prepareExternalUrl(url); this.urlChanges.push(externalUrl); } replaceState(ctx, title, path, query) { this.internalTitle = title; const url = path + (query.length > 0 ? ('?' + query) : ''); this.internalPath = url; const externalUrl = this.prepareExternalUrl(url); this.urlChanges.push('replace: ' + externalUrl); } onPopState(fn) { this._subject.subscribe({ next: fn }); } getBaseHref() { return this.internalBaseHref; } back() { if (this.urlChanges.length > 0) { this.urlChanges.pop(); const nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : ''; this.simulatePopState(nextUrl); } } forward() { throw 'not implemented'; } } MockLocationStrategy.decorators = [ { type: Injectable }, ]; /** @nocollapse */ MockLocationStrategy.ctorParameters = () => []; class _MockPopStateEvent { constructor(newUrl) { this.newUrl = newUrl; this.pop = true; this.type = 'popstate'; } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of the common/testing package. */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of the core/testing package. */ export { SpyLocation, MockLocationStrategy }; //# sourceMappingURL=testing.js.map
Kasperr93/VHS
node_modules/@angular/common/@angular/common/testing.js
JavaScript
mit
6,852
/*! * Start Bootstrap - Createive v4.0.0-beta (https://startbootstrap.com/template-overviews/creative) * Copyright 2013-2017 Start Bootstrap * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap-creative/blob/master/LICENSE) */ body, html { width: 100%; height: 100%; } body { font-family: 'Merriweather', 'Helvetica Neue', Arial, sans-serif; } hr { max-width: 50px; border-width: 3px; border-color: #F05F40; } hr.light { border-color: white; } a { color: #F05F40; -webkit-transition: all 0.2s; -moz-transition: all 0.2s; transition: all 0.2s; } a:focus, a:hover { color: #f05f40; } h1, h2, h3, h4, h5, h6 { font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif; } p { font-size: 16px; line-height: 1.5; margin-bottom: 20px; } .bg-primary { background-color: #F05F40 !important; } .bg-dark { color: white; background-color: #222222 !important; } .text-faded { color: rgba(255, 255, 255, 0.7); } section { padding: 100px 0; } .section-heading { margin-top: 0; } ::-moz-selection { color: white; background: #222222; text-shadow: none; } ::selection { color: white; background: #222222; text-shadow: none; } img::selection { color: white; background: transparent; } img::-moz-selection { color: white; background: transparent; } body { -webkit-tap-highlight-color: #222222; } #mainNav { border-color: rgba(34, 34, 34, 0.05); background-color: white; font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif; -webkit-transition: all 0.2s; -moz-transition: all 0.2s; transition: all 0.2s; } #mainNav .navbar-brand { font-weight: 700; text-transform: uppercase; color: #F05F40; font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif; } #mainNav .navbar-brand:focus, #mainNav .navbar-brand:hover { color: #f05f40; } #mainNav .navbar-toggle { font-size: 12px; font-weight: 700; text-transform: uppercase; color: #222222; } #mainNav .navbar-nav > li.nav-item > a.nav-link:focus, #mainNav .navbar-nav > li.nav-item > a.nav-link { font-size: 13px; font-weight: 700; text-transform: uppercase; color: #222222; } #mainNav .navbar-nav > li.nav-item > a.nav-link:focus:hover, #mainNav .navbar-nav > li.nav-item > a.nav-link:hover { color: #F05F40; } #mainNav .navbar-nav > li.nav-item > a.nav-link:focus.active, #mainNav .navbar-nav > li.nav-item > a.nav-link.active { color: #F05F40 !important; background-color: transparent; } #mainNav .navbar-nav > li.nav-item > a.nav-link:focus.active:hover, #mainNav .navbar-nav > li.nav-item > a.nav-link.active:hover { background-color: transparent; } @media (min-width: 992px) { #mainNav { border-color: rgba(255, 255, 255, 0.3); background-color: transparent; } #mainNav .navbar-brand { color: rgba(255, 255, 255, 0.7); } #mainNav .navbar-brand:focus, #mainNav .navbar-brand:hover { color: white; } #mainNav .navbar-nav > li.nav-item > a.nav-link, #mainNav .navbar-nav > li.nav-item > a.nav-link:focus { color: rgba(255, 255, 255, 0.7); } #mainNav .navbar-nav > li.nav-item > a.nav-link:hover, #mainNav .navbar-nav > li.nav-item > a.nav-link:focus:hover { color: white; } #mainNav.navbar-shrink { border-color: rgba(34, 34, 34, 0.05); background-color: white; } #mainNav.navbar-shrink .navbar-brand { font-size: 16px; color: #F05F40; } #mainNav.navbar-shrink .navbar-brand:focus, #mainNav.navbar-shrink .navbar-brand:hover { color: #f05f40; } #mainNav.navbar-shrink .navbar-nav > li.nav-item > a.nav-link, #mainNav.navbar-shrink .navbar-nav > li.nav-item > a.nav-link:focus { color: #222222; } #mainNav.navbar-shrink .navbar-nav > li.nav-item > a.nav-link:hover, #mainNav.navbar-shrink .navbar-nav > li.nav-item > a.nav-link:focus:hover { color: #F05F40; } } header.masthead { position: relative; width: 100%; min-height: auto; text-align: center; color: white; background-image: url("../img/header.jpg"); background-position: center; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } header.masthead .header-content { position: relative; width: 100%; padding: 150px 15px 100px; text-align: center; } header.masthead .header-content .header-content-inner h1 { font-size: 30px; font-weight: 700; margin-top: 0; margin-bottom: 0; text-transform: uppercase; } header.masthead .header-content .header-content-inner hr { margin: 30px auto; } header.masthead .header-content .header-content-inner p { font-size: 16px; font-weight: 300; margin-bottom: 50px; color: rgba(255, 255, 255, 0.7); } @media (min-width: 768px) { header.masthead { height: 100%; min-height: 600px; } header.masthead .header-content { position: absolute; top: 50%; padding: 0 50px; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); } header.masthead .header-content .header-content-inner { max-width: 1000px; margin-right: auto; margin-left: auto; } header.masthead .header-content .header-content-inner h1 { font-size: 50px; } header.masthead .header-content .header-content-inner p { font-size: 18px; max-width: 80%; margin-right: auto; margin-left: auto; } } .service-box { max-width: 400px; margin: 50px auto 0; } @media (min-width: 992px) { .service-box { margin: 20px auto 0; } } .service-box p { margin-bottom: 0; } .portfolio-box { position: relative; display: block; max-width: 650px; margin: 0 auto; } .portfolio-box .portfolio-box-caption { position: absolute; bottom: 0; display: block; width: 100%; height: 100%; text-align: center; opacity: 0; color: white; background: rgba(240, 95, 64, 0.9); -webkit-transition: all 0.2s; -moz-transition: all 0.2s; transition: all 0.2s; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content { position: absolute; top: 50%; width: 100%; transform: translateY(-50%); text-align: center; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category, .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name { padding: 0 15px; font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category { font-size: 14px; font-weight: 600; text-transform: uppercase; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name { font-size: 18px; } .portfolio-box:hover .portfolio-box-caption { opacity: 1; } .portfolio-box:focus { outline: none; } @media (min-width: 768px) { .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-category { font-size: 16px; } .portfolio-box .portfolio-box-caption .portfolio-box-caption-content .project-name { font-size: 22px; } } .call-to-action { padding: 50px 0; } .call-to-action h2 { margin: 0 auto 20px; } .text-primary { color: #F05F40 !important; } .no-gutter > [class*='col-'] { padding-right: 0; padding-left: 0; } .btn-default { color: #222222; border-color: white; background-color: white; } .btn-default.focus, .btn-default:focus { color: #222222; border-color: #bfbfbf; background-color: #e6e6e6; } .btn-default:hover { color: #222222; border-color: #e0e0e0; background-color: #e6e6e6; } .btn-default.active, .btn-default:active, .open > .btn-default.dropdown-toggle { color: #222222; border-color: #e0e0e0; background-color: #e6e6e6; } .btn-default.active.focus, .btn-default.active:focus, .btn-default.active:hover, .btn-default:active.focus, .btn-default:active:focus, .btn-default:active:hover, .open > .btn-default.dropdown-toggle.focus, .open > .btn-default.dropdown-toggle:focus, .open > .btn-default.dropdown-toggle:hover { color: #222222; border-color: #bfbfbf; background-color: #d4d4d4; } .btn-default.active, .btn-default:active, .open > .btn-default.dropdown-toggle { background-image: none; } .btn-default.disabled.focus, .btn-default.disabled:focus, .btn-default.disabled:hover, .btn-default[disabled].focus, .btn-default[disabled]:focus, .btn-default[disabled]:hover, fieldset[disabled] .btn-default.focus, fieldset[disabled] .btn-default:focus, fieldset[disabled] .btn-default:hover { border-color: white; background-color: white; } .btn-default .badge { color: white; background-color: #222222; } .btn-primary { color: white; border-color: #F05F40; background-color: #F05F40; } .btn-primary.focus, .btn-primary:focus { color: white; border-color: #a4270d; background-color: #eb3812; } .btn-primary:hover { color: white; border-color: #e13612; background-color: #eb3812; } .btn-primary.active, .btn-primary:active, .open > .btn-primary.dropdown-toggle { color: white; border-color: #e13612; background-color: #eb3812; } .btn-primary.active.focus, .btn-primary.active:focus, .btn-primary.active:hover, .btn-primary:active.focus, .btn-primary:active:focus, .btn-primary:active:hover, .open > .btn-primary.dropdown-toggle.focus, .open > .btn-primary.dropdown-toggle:focus, .open > .btn-primary.dropdown-toggle:hover { color: white; border-color: #a4270d; background-color: #c93110; } .btn-primary.active, .btn-primary:active, .open > .btn-primary.dropdown-toggle { background-image: none; } .btn-primary.disabled.focus, .btn-primary.disabled:focus, .btn-primary.disabled:hover, .btn-primary[disabled].focus, .btn-primary[disabled]:focus, .btn-primary[disabled]:hover, fieldset[disabled] .btn-primary.focus, fieldset[disabled] .btn-primary:focus, fieldset[disabled] .btn-primary:hover { border-color: #F05F40; background-color: #F05F40; } .btn-primary .badge { color: #F05F40; background-color: white; } .btn { font-weight: 700; text-transform: uppercase; border: none; border-radius: 300px; font-family: 'Open Sans', 'Helvetica Neue', Arial, sans-serif; } .btn-xl { padding: 15px 30px; }
MichaelZC/nyef
css/creative.css
CSS
mit
10,783
(function () { var value = { }; magazinesManager.magazinesApp.value('config', value); }());
TRex22/magazine-website-mvc-5
Cik.MagazineWeb.WebApp/app/services/config.js
JavaScript
mit
106
using System; using System.Web.Mvc; namespace TestStack.Seleno.AcceptanceTests.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult List() { return View(); } public ActionResult TestingEnvVariable() { var envVar = Environment.GetEnvironmentVariable("FunctionalTest"); if (envVar != "SomeVal") throw new Exception("Environment Variable was not injected!!"); return RedirectToAction("Index"); } } }
bendetat/TestStack.Seleno
src/TestStack.Seleno.AcceptanceTests.Web/Controllers/HomeController.cs
C#
mit
638
import { DecimalPipe } from '@angular/common'; import { Pipe, PipeTransform } from '@angular/core'; import { ConfigProvider } from '../providers/config/config'; import { RateProvider } from '../providers/rate/rate'; @Pipe({ name: 'satToFiat', pure: false }) export class SatToFiatPipe implements PipeTransform { private walletSettings; constructor( private configProvider: ConfigProvider, private rateProvider: RateProvider, private decimalPipe: DecimalPipe ) { this.walletSettings = this.configProvider.get().wallet.settings; } transform(amount: number, coin: string) { let amount_ = this.rateProvider.toFiat( amount, this.walletSettings.alternativeIsoCode, coin.toLowerCase() ); return ( this.decimalPipe.transform(amount_ || 0, '1.2-2') + ' ' + this.walletSettings.alternativeIsoCode ); } }
cmgustavo/copay
src/pipes/satToFiat.ts
TypeScript
mit
880
#ifdef USE_SYSTEM_SQLITE # include <sqlite3.h> #else #include "../../sqlite3.c" #endif /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** A TCL Interface to SQLite. Append this file to sqlite3.c and ** compile the whole thing to build a TCL-enabled version of SQLite. ** ** Compile-time options: ** ** -DTCLSH=1 Add a "main()" routine that works as a tclsh. ** ** -DSQLITE_TCLMD5 When used in conjuction with -DTCLSH=1, add ** four new commands to the TCL interpreter for ** generating MD5 checksums: md5, md5file, ** md5-10x8, and md5file-10x8. ** ** -DSQLITE_TEST When used in conjuction with -DTCLSH=1, add ** hundreds of new commands used for testing ** SQLite. This option implies -DSQLITE_TCLMD5. */ #include "tcl.h" #include <errno.h> /* ** Some additional include files are needed if this file is not ** appended to the amalgamation. */ #ifndef SQLITE_AMALGAMATION # include "sqlite3.h" # include <stdlib.h> # include <string.h> # include <assert.h> typedef unsigned char u8; #endif #include <ctype.h> /* * Windows needs to know which symbols to export. Unix does not. * BUILD_sqlite should be undefined for Unix. */ #ifdef BUILD_sqlite #undef TCL_STORAGE_CLASS #define TCL_STORAGE_CLASS DLLEXPORT #endif /* BUILD_sqlite */ #define NUM_PREPARED_STMTS 10 #define MAX_PREPARED_STMTS 100 /* ** If TCL uses UTF-8 and SQLite is configured to use iso8859, then we ** have to do a translation when going between the two. Set the ** UTF_TRANSLATION_NEEDED macro to indicate that we need to do ** this translation. */ #if defined(TCL_UTF_MAX) && !defined(SQLITE_UTF8) # define UTF_TRANSLATION_NEEDED 1 #endif /* ** New SQL functions can be created as TCL scripts. Each such function ** is described by an instance of the following structure. */ typedef struct SqlFunc SqlFunc; struct SqlFunc { Tcl_Interp *interp; /* The TCL interpret to execute the function */ Tcl_Obj *pScript; /* The Tcl_Obj representation of the script */ int useEvalObjv; /* True if it is safe to use Tcl_EvalObjv */ char *zName; /* Name of this function */ SqlFunc *pNext; /* Next function on the list of them all */ }; /* ** New collation sequences function can be created as TCL scripts. Each such ** function is described by an instance of the following structure. */ typedef struct SqlCollate SqlCollate; struct SqlCollate { Tcl_Interp *interp; /* The TCL interpret to execute the function */ char *zScript; /* The script to be run */ SqlCollate *pNext; /* Next function on the list of them all */ }; /* ** Prepared statements are cached for faster execution. Each prepared ** statement is described by an instance of the following structure. */ typedef struct SqlPreparedStmt SqlPreparedStmt; struct SqlPreparedStmt { SqlPreparedStmt *pNext; /* Next in linked list */ SqlPreparedStmt *pPrev; /* Previous on the list */ sqlite3_stmt *pStmt; /* The prepared statement */ int nSql; /* chars in zSql[] */ const char *zSql; /* Text of the SQL statement */ int nParm; /* Size of apParm array */ Tcl_Obj **apParm; /* Array of referenced object pointers */ }; typedef struct IncrblobChannel IncrblobChannel; /* ** There is one instance of this structure for each SQLite database ** that has been opened by the SQLite TCL interface. ** ** If this module is built with SQLITE_TEST defined (to create the SQLite ** testfixture executable), then it may be configured to use either ** sqlite3_prepare_v2() or sqlite3_prepare() to prepare SQL statements. ** If SqliteDb.bLegacyPrepare is true, sqlite3_prepare() is used. */ typedef struct SqliteDb SqliteDb; struct SqliteDb { sqlite3 *db; /* The "real" database structure. MUST BE FIRST */ Tcl_Interp *interp; /* The interpreter used for this database */ char *zBusy; /* The busy callback routine */ char *zCommit; /* The commit hook callback routine */ char *zTrace; /* The trace callback routine */ char *zProfile; /* The profile callback routine */ char *zProgress; /* The progress callback routine */ char *zAuth; /* The authorization callback routine */ int disableAuth; /* Disable the authorizer if it exists */ char *zNull; /* Text to substitute for an SQL NULL value */ SqlFunc *pFunc; /* List of SQL functions */ Tcl_Obj *pUpdateHook; /* Update hook script (if any) */ Tcl_Obj *pRollbackHook; /* Rollback hook script (if any) */ Tcl_Obj *pWalHook; /* WAL hook script (if any) */ Tcl_Obj *pUnlockNotify; /* Unlock notify script (if any) */ SqlCollate *pCollate; /* List of SQL collation functions */ int rc; /* Return code of most recent sqlite3_exec() */ Tcl_Obj *pCollateNeeded; /* Collation needed script */ SqlPreparedStmt *stmtList; /* List of prepared statements*/ SqlPreparedStmt *stmtLast; /* Last statement in the list */ int maxStmt; /* The next maximum number of stmtList */ int nStmt; /* Number of statements in stmtList */ IncrblobChannel *pIncrblob;/* Linked list of open incrblob channels */ int nStep, nSort, nIndex; /* Statistics for most recent operation */ int nTransaction; /* Number of nested [transaction] methods */ #ifdef SQLITE_TEST int bLegacyPrepare; /* True to use sqlite3_prepare() */ #endif }; struct IncrblobChannel { sqlite3_blob *pBlob; /* sqlite3 blob handle */ SqliteDb *pDb; /* Associated database connection */ int iSeek; /* Current seek offset */ Tcl_Channel channel; /* Channel identifier */ IncrblobChannel *pNext; /* Linked list of all open incrblob channels */ IncrblobChannel *pPrev; /* Linked list of all open incrblob channels */ }; /* ** Compute a string length that is limited to what can be stored in ** lower 30 bits of a 32-bit signed integer. */ static int strlen30(const char *z){ const char *z2 = z; while( *z2 ){ z2++; } return 0x3fffffff & (int)(z2 - z); } #ifndef SQLITE_OMIT_INCRBLOB /* ** Close all incrblob channels opened using database connection pDb. ** This is called when shutting down the database connection. */ static void closeIncrblobChannels(SqliteDb *pDb){ IncrblobChannel *p; IncrblobChannel *pNext; for(p=pDb->pIncrblob; p; p=pNext){ pNext = p->pNext; /* Note: Calling unregister here call Tcl_Close on the incrblob channel, ** which deletes the IncrblobChannel structure at *p. So do not ** call Tcl_Free() here. */ Tcl_UnregisterChannel(pDb->interp, p->channel); } } /* ** Close an incremental blob channel. */ static int incrblobClose(ClientData instanceData, Tcl_Interp *interp){ IncrblobChannel *p = (IncrblobChannel *)instanceData; int rc = sqlite3_blob_close(p->pBlob); sqlite3 *db = p->pDb->db; /* Remove the channel from the SqliteDb.pIncrblob list. */ if( p->pNext ){ p->pNext->pPrev = p->pPrev; } if( p->pPrev ){ p->pPrev->pNext = p->pNext; } if( p->pDb->pIncrblob==p ){ p->pDb->pIncrblob = p->pNext; } /* Free the IncrblobChannel structure */ Tcl_Free((char *)p); if( rc!=SQLITE_OK ){ Tcl_SetResult(interp, (char *)sqlite3_errmsg(db), TCL_VOLATILE); return TCL_ERROR; } return TCL_OK; } /* ** Read data from an incremental blob channel. */ static int incrblobInput( ClientData instanceData, char *buf, int bufSize, int *errorCodePtr ){ IncrblobChannel *p = (IncrblobChannel *)instanceData; int nRead = bufSize; /* Number of bytes to read */ int nBlob; /* Total size of the blob */ int rc; /* sqlite error code */ nBlob = sqlite3_blob_bytes(p->pBlob); if( (p->iSeek+nRead)>nBlob ){ nRead = nBlob-p->iSeek; } if( nRead<=0 ){ return 0; } rc = sqlite3_blob_read(p->pBlob, (void *)buf, nRead, p->iSeek); if( rc!=SQLITE_OK ){ *errorCodePtr = rc; return -1; } p->iSeek += nRead; return nRead; } /* ** Write data to an incremental blob channel. */ static int incrblobOutput( ClientData instanceData, CONST char *buf, int toWrite, int *errorCodePtr ){ IncrblobChannel *p = (IncrblobChannel *)instanceData; int nWrite = toWrite; /* Number of bytes to write */ int nBlob; /* Total size of the blob */ int rc; /* sqlite error code */ nBlob = sqlite3_blob_bytes(p->pBlob); if( (p->iSeek+nWrite)>nBlob ){ *errorCodePtr = EINVAL; return -1; } if( nWrite<=0 ){ return 0; } rc = sqlite3_blob_write(p->pBlob, (void *)buf, nWrite, p->iSeek); if( rc!=SQLITE_OK ){ *errorCodePtr = EIO; return -1; } p->iSeek += nWrite; return nWrite; } /* ** Seek an incremental blob channel. */ static int incrblobSeek( ClientData instanceData, long offset, int seekMode, int *errorCodePtr ){ IncrblobChannel *p = (IncrblobChannel *)instanceData; switch( seekMode ){ case SEEK_SET: p->iSeek = offset; break; case SEEK_CUR: p->iSeek += offset; break; case SEEK_END: p->iSeek = sqlite3_blob_bytes(p->pBlob) + offset; break; default: assert(!"Bad seekMode"); } return p->iSeek; } static void incrblobWatch(ClientData instanceData, int mode){ /* NO-OP */ } static int incrblobHandle(ClientData instanceData, int dir, ClientData *hPtr){ return TCL_ERROR; } static Tcl_ChannelType IncrblobChannelType = { "incrblob", /* typeName */ TCL_CHANNEL_VERSION_2, /* version */ incrblobClose, /* closeProc */ incrblobInput, /* inputProc */ incrblobOutput, /* outputProc */ incrblobSeek, /* seekProc */ 0, /* setOptionProc */ 0, /* getOptionProc */ incrblobWatch, /* watchProc (this is a no-op) */ incrblobHandle, /* getHandleProc (always returns error) */ 0, /* close2Proc */ 0, /* blockModeProc */ 0, /* flushProc */ 0, /* handlerProc */ 0, /* wideSeekProc */ }; /* ** Create a new incrblob channel. */ static int createIncrblobChannel( Tcl_Interp *interp, SqliteDb *pDb, const char *zDb, const char *zTable, const char *zColumn, sqlite_int64 iRow, int isReadonly ){ IncrblobChannel *p; sqlite3 *db = pDb->db; sqlite3_blob *pBlob; int rc; int flags = TCL_READABLE|(isReadonly ? 0 : TCL_WRITABLE); /* This variable is used to name the channels: "incrblob_[incr count]" */ static int count = 0; char zChannel[64]; rc = sqlite3_blob_open(db, zDb, zTable, zColumn, iRow, !isReadonly, &pBlob); if( rc!=SQLITE_OK ){ Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); return TCL_ERROR; } p = (IncrblobChannel *)Tcl_Alloc(sizeof(IncrblobChannel)); p->iSeek = 0; p->pBlob = pBlob; sqlite3_snprintf(sizeof(zChannel), zChannel, "incrblob_%d", ++count); p->channel = Tcl_CreateChannel(&IncrblobChannelType, zChannel, p, flags); Tcl_RegisterChannel(interp, p->channel); /* Link the new channel into the SqliteDb.pIncrblob list. */ p->pNext = pDb->pIncrblob; p->pPrev = 0; if( p->pNext ){ p->pNext->pPrev = p; } pDb->pIncrblob = p; p->pDb = pDb; Tcl_SetResult(interp, (char *)Tcl_GetChannelName(p->channel), TCL_VOLATILE); return TCL_OK; } #else /* else clause for "#ifndef SQLITE_OMIT_INCRBLOB" */ #define closeIncrblobChannels(pDb) #endif /* ** Look at the script prefix in pCmd. We will be executing this script ** after first appending one or more arguments. This routine analyzes ** the script to see if it is safe to use Tcl_EvalObjv() on the script ** rather than the more general Tcl_EvalEx(). Tcl_EvalObjv() is much ** faster. ** ** Scripts that are safe to use with Tcl_EvalObjv() consists of a ** command name followed by zero or more arguments with no [...] or $ ** or {...} or ; to be seen anywhere. Most callback scripts consist ** of just a single procedure name and they meet this requirement. */ static int safeToUseEvalObjv(Tcl_Interp *interp, Tcl_Obj *pCmd){ /* We could try to do something with Tcl_Parse(). But we will instead ** just do a search for forbidden characters. If any of the forbidden ** characters appear in pCmd, we will report the string as unsafe. */ const char *z; int n; z = Tcl_GetStringFromObj(pCmd, &n); while( n-- > 0 ){ int c = *(z++); if( c=='$' || c=='[' || c==';' ) return 0; } return 1; } /* ** Find an SqlFunc structure with the given name. Or create a new ** one if an existing one cannot be found. Return a pointer to the ** structure. */ static SqlFunc *findSqlFunc(SqliteDb *pDb, const char *zName){ SqlFunc *p, *pNew; int i; pNew = (SqlFunc*)Tcl_Alloc( sizeof(*pNew) + strlen30(zName) + 1 ); pNew->zName = (char*)&pNew[1]; for(i=0; zName[i]; i++){ pNew->zName[i] = tolower(zName[i]); } pNew->zName[i] = 0; for(p=pDb->pFunc; p; p=p->pNext){ if( strcmp(p->zName, pNew->zName)==0 ){ Tcl_Free((char*)pNew); return p; } } pNew->interp = pDb->interp; pNew->pScript = 0; pNew->pNext = pDb->pFunc; pDb->pFunc = pNew; return pNew; } /* ** Free a single SqlPreparedStmt object. */ static void dbFreeStmt(SqlPreparedStmt *pStmt){ #ifdef SQLITE_TEST if( sqlite3_sql(pStmt->pStmt)==0 ){ Tcl_Free((char *)pStmt->zSql); } #endif sqlite3_finalize(pStmt->pStmt); Tcl_Free((char *)pStmt); } /* ** Finalize and free a list of prepared statements */ static void flushStmtCache(SqliteDb *pDb){ SqlPreparedStmt *pPreStmt; SqlPreparedStmt *pNext; for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pNext){ pNext = pPreStmt->pNext; dbFreeStmt(pPreStmt); } pDb->nStmt = 0; pDb->stmtLast = 0; pDb->stmtList = 0; } /* ** TCL calls this procedure when an sqlite3 database command is ** deleted. */ static void DbDeleteCmd(void *db){ SqliteDb *pDb = (SqliteDb*)db; flushStmtCache(pDb); closeIncrblobChannels(pDb); sqlite3_close(pDb->db); while( pDb->pFunc ){ SqlFunc *pFunc = pDb->pFunc; pDb->pFunc = pFunc->pNext; Tcl_DecrRefCount(pFunc->pScript); Tcl_Free((char*)pFunc); } while( pDb->pCollate ){ SqlCollate *pCollate = pDb->pCollate; pDb->pCollate = pCollate->pNext; Tcl_Free((char*)pCollate); } if( pDb->zBusy ){ Tcl_Free(pDb->zBusy); } if( pDb->zTrace ){ Tcl_Free(pDb->zTrace); } if( pDb->zProfile ){ Tcl_Free(pDb->zProfile); } if( pDb->zAuth ){ Tcl_Free(pDb->zAuth); } if( pDb->zNull ){ Tcl_Free(pDb->zNull); } if( pDb->pUpdateHook ){ Tcl_DecrRefCount(pDb->pUpdateHook); } if( pDb->pRollbackHook ){ Tcl_DecrRefCount(pDb->pRollbackHook); } if( pDb->pWalHook ){ Tcl_DecrRefCount(pDb->pWalHook); } if( pDb->pCollateNeeded ){ Tcl_DecrRefCount(pDb->pCollateNeeded); } Tcl_Free((char*)pDb); } /* ** This routine is called when a database file is locked while trying ** to execute SQL. */ static int DbBusyHandler(void *cd, int nTries){ SqliteDb *pDb = (SqliteDb*)cd; int rc; char zVal[30]; sqlite3_snprintf(sizeof(zVal), zVal, "%d", nTries); rc = Tcl_VarEval(pDb->interp, pDb->zBusy, " ", zVal, (char*)0); if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ return 0; } return 1; } #ifndef SQLITE_OMIT_PROGRESS_CALLBACK /* ** This routine is invoked as the 'progress callback' for the database. */ static int DbProgressHandler(void *cd){ SqliteDb *pDb = (SqliteDb*)cd; int rc; assert( pDb->zProgress ); rc = Tcl_Eval(pDb->interp, pDb->zProgress); if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ return 1; } return 0; } #endif #ifndef SQLITE_OMIT_TRACE /* ** This routine is called by the SQLite trace handler whenever a new ** block of SQL is executed. The TCL script in pDb->zTrace is executed. */ static void DbTraceHandler(void *cd, const char *zSql){ SqliteDb *pDb = (SqliteDb*)cd; Tcl_DString str; Tcl_DStringInit(&str); Tcl_DStringAppend(&str, pDb->zTrace, -1); Tcl_DStringAppendElement(&str, zSql); Tcl_Eval(pDb->interp, Tcl_DStringValue(&str)); Tcl_DStringFree(&str); Tcl_ResetResult(pDb->interp); } #endif #ifndef SQLITE_OMIT_TRACE /* ** This routine is called by the SQLite profile handler after a statement ** SQL has executed. The TCL script in pDb->zProfile is evaluated. */ static void DbProfileHandler(void *cd, const char *zSql, sqlite_uint64 tm){ SqliteDb *pDb = (SqliteDb*)cd; Tcl_DString str; char zTm[100]; sqlite3_snprintf(sizeof(zTm)-1, zTm, "%lld", tm); Tcl_DStringInit(&str); Tcl_DStringAppend(&str, pDb->zProfile, -1); Tcl_DStringAppendElement(&str, zSql); Tcl_DStringAppendElement(&str, zTm); Tcl_Eval(pDb->interp, Tcl_DStringValue(&str)); Tcl_DStringFree(&str); Tcl_ResetResult(pDb->interp); } #endif /* ** This routine is called when a transaction is committed. The ** TCL script in pDb->zCommit is executed. If it returns non-zero or ** if it throws an exception, the transaction is rolled back instead ** of being committed. */ static int DbCommitHandler(void *cd){ SqliteDb *pDb = (SqliteDb*)cd; int rc; rc = Tcl_Eval(pDb->interp, pDb->zCommit); if( rc!=TCL_OK || atoi(Tcl_GetStringResult(pDb->interp)) ){ return 1; } return 0; } static void DbRollbackHandler(void *clientData){ SqliteDb *pDb = (SqliteDb*)clientData; assert(pDb->pRollbackHook); if( TCL_OK!=Tcl_EvalObjEx(pDb->interp, pDb->pRollbackHook, 0) ){ Tcl_BackgroundError(pDb->interp); } } /* ** This procedure handles wal_hook callbacks. */ static int DbWalHandler( void *clientData, sqlite3 *db, const char *zDb, int nEntry ){ int ret = SQLITE_OK; Tcl_Obj *p; SqliteDb *pDb = (SqliteDb*)clientData; Tcl_Interp *interp = pDb->interp; assert(pDb->pWalHook); p = Tcl_DuplicateObj(pDb->pWalHook); Tcl_IncrRefCount(p); Tcl_ListObjAppendElement(interp, p, Tcl_NewStringObj(zDb, -1)); Tcl_ListObjAppendElement(interp, p, Tcl_NewIntObj(nEntry)); if( TCL_OK!=Tcl_EvalObjEx(interp, p, 0) || TCL_OK!=Tcl_GetIntFromObj(interp, Tcl_GetObjResult(interp), &ret) ){ Tcl_BackgroundError(interp); } Tcl_DecrRefCount(p); return ret; } #if defined(SQLITE_TEST) && defined(SQLITE_ENABLE_UNLOCK_NOTIFY) static void setTestUnlockNotifyVars(Tcl_Interp *interp, int iArg, int nArg){ char zBuf[64]; sprintf(zBuf, "%d", iArg); Tcl_SetVar(interp, "sqlite_unlock_notify_arg", zBuf, TCL_GLOBAL_ONLY); sprintf(zBuf, "%d", nArg); Tcl_SetVar(interp, "sqlite_unlock_notify_argcount", zBuf, TCL_GLOBAL_ONLY); } #else # define setTestUnlockNotifyVars(x,y,z) #endif #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY static void DbUnlockNotify(void **apArg, int nArg){ int i; for(i=0; i<nArg; i++){ const int flags = (TCL_EVAL_GLOBAL|TCL_EVAL_DIRECT); SqliteDb *pDb = (SqliteDb *)apArg[i]; setTestUnlockNotifyVars(pDb->interp, i, nArg); assert( pDb->pUnlockNotify); Tcl_EvalObjEx(pDb->interp, pDb->pUnlockNotify, flags); Tcl_DecrRefCount(pDb->pUnlockNotify); pDb->pUnlockNotify = 0; } } #endif static void DbUpdateHandler( void *p, int op, const char *zDb, const char *zTbl, sqlite_int64 rowid ){ SqliteDb *pDb = (SqliteDb *)p; Tcl_Obj *pCmd; assert( pDb->pUpdateHook ); assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE ); pCmd = Tcl_DuplicateObj(pDb->pUpdateHook); Tcl_IncrRefCount(pCmd); Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj( ( (op==SQLITE_INSERT)?"INSERT":(op==SQLITE_UPDATE)?"UPDATE":"DELETE"), -1)); Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zDb, -1)); Tcl_ListObjAppendElement(0, pCmd, Tcl_NewStringObj(zTbl, -1)); Tcl_ListObjAppendElement(0, pCmd, Tcl_NewWideIntObj(rowid)); Tcl_EvalObjEx(pDb->interp, pCmd, TCL_EVAL_DIRECT); Tcl_DecrRefCount(pCmd); } static void tclCollateNeeded( void *pCtx, sqlite3 *db, int enc, const char *zName ){ SqliteDb *pDb = (SqliteDb *)pCtx; Tcl_Obj *pScript = Tcl_DuplicateObj(pDb->pCollateNeeded); Tcl_IncrRefCount(pScript); Tcl_ListObjAppendElement(0, pScript, Tcl_NewStringObj(zName, -1)); Tcl_EvalObjEx(pDb->interp, pScript, 0); Tcl_DecrRefCount(pScript); } /* ** This routine is called to evaluate an SQL collation function implemented ** using TCL script. */ static int tclSqlCollate( void *pCtx, int nA, const void *zA, int nB, const void *zB ){ SqlCollate *p = (SqlCollate *)pCtx; Tcl_Obj *pCmd; pCmd = Tcl_NewStringObj(p->zScript, -1); Tcl_IncrRefCount(pCmd); Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zA, nA)); Tcl_ListObjAppendElement(p->interp, pCmd, Tcl_NewStringObj(zB, nB)); Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT); Tcl_DecrRefCount(pCmd); return (atoi(Tcl_GetStringResult(p->interp))); } /* ** This routine is called to evaluate an SQL function implemented ** using TCL script. */ static void tclSqlFunc(sqlite3_context *context, int argc, sqlite3_value**argv){ SqlFunc *p = sqlite3_user_data(context); Tcl_Obj *pCmd; int i; int rc; if( argc==0 ){ /* If there are no arguments to the function, call Tcl_EvalObjEx on the ** script object directly. This allows the TCL compiler to generate ** bytecode for the command on the first invocation and thus make ** subsequent invocations much faster. */ pCmd = p->pScript; Tcl_IncrRefCount(pCmd); rc = Tcl_EvalObjEx(p->interp, pCmd, 0); Tcl_DecrRefCount(pCmd); }else{ /* If there are arguments to the function, make a shallow copy of the ** script object, lappend the arguments, then evaluate the copy. ** ** By "shallow" copy, we mean a only the outer list Tcl_Obj is duplicated. ** The new Tcl_Obj contains pointers to the original list elements. ** That way, when Tcl_EvalObjv() is run and shimmers the first element ** of the list to tclCmdNameType, that alternate representation will ** be preserved and reused on the next invocation. */ Tcl_Obj **aArg; int nArg; if( Tcl_ListObjGetElements(p->interp, p->pScript, &nArg, &aArg) ){ sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); return; } pCmd = Tcl_NewListObj(nArg, aArg); Tcl_IncrRefCount(pCmd); for(i=0; i<argc; i++){ sqlite3_value *pIn = argv[i]; Tcl_Obj *pVal; /* Set pVal to contain the i'th column of this row. */ switch( sqlite3_value_type(pIn) ){ case SQLITE_BLOB: { int bytes = sqlite3_value_bytes(pIn); pVal = Tcl_NewByteArrayObj(sqlite3_value_blob(pIn), bytes); break; } case SQLITE_INTEGER: { sqlite_int64 v = sqlite3_value_int64(pIn); if( v>=-2147483647 && v<=2147483647 ){ pVal = Tcl_NewIntObj((int)v); }else{ pVal = Tcl_NewWideIntObj(v); } break; } case SQLITE_FLOAT: { double r = sqlite3_value_double(pIn); pVal = Tcl_NewDoubleObj(r); break; } case SQLITE_NULL: { pVal = Tcl_NewStringObj("", 0); break; } default: { int bytes = sqlite3_value_bytes(pIn); pVal = Tcl_NewStringObj((char *)sqlite3_value_text(pIn), bytes); break; } } rc = Tcl_ListObjAppendElement(p->interp, pCmd, pVal); if( rc ){ Tcl_DecrRefCount(pCmd); sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); return; } } if( !p->useEvalObjv ){ /* Tcl_EvalObjEx() will automatically call Tcl_EvalObjv() if pCmd ** is a list without a string representation. To prevent this from ** happening, make sure pCmd has a valid string representation */ Tcl_GetString(pCmd); } rc = Tcl_EvalObjEx(p->interp, pCmd, TCL_EVAL_DIRECT); Tcl_DecrRefCount(pCmd); } if( rc && rc!=TCL_RETURN ){ sqlite3_result_error(context, Tcl_GetStringResult(p->interp), -1); }else{ Tcl_Obj *pVar = Tcl_GetObjResult(p->interp); int n; u8 *data; const char *zType = (pVar->typePtr ? pVar->typePtr->name : ""); char c = zType[0]; if( c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0 ){ /* Only return a BLOB type if the Tcl variable is a bytearray and ** has no string representation. */ data = Tcl_GetByteArrayFromObj(pVar, &n); sqlite3_result_blob(context, data, n, SQLITE_TRANSIENT); }else if( c=='b' && strcmp(zType,"boolean")==0 ){ Tcl_GetIntFromObj(0, pVar, &n); sqlite3_result_int(context, n); }else if( c=='d' && strcmp(zType,"double")==0 ){ double r; Tcl_GetDoubleFromObj(0, pVar, &r); sqlite3_result_double(context, r); }else if( (c=='w' && strcmp(zType,"wideInt")==0) || (c=='i' && strcmp(zType,"int")==0) ){ Tcl_WideInt v; Tcl_GetWideIntFromObj(0, pVar, &v); sqlite3_result_int64(context, v); }else{ data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n); sqlite3_result_text(context, (char *)data, n, SQLITE_TRANSIENT); } } } #ifndef SQLITE_OMIT_AUTHORIZATION /* ** This is the authentication function. It appends the authentication ** type code and the two arguments to zCmd[] then invokes the result ** on the interpreter. The reply is examined to determine if the ** authentication fails or succeeds. */ static int auth_callback( void *pArg, int code, const char *zArg1, const char *zArg2, const char *zArg3, const char *zArg4 ){ char *zCode; Tcl_DString str; int rc; const char *zReply; SqliteDb *pDb = (SqliteDb*)pArg; if( pDb->disableAuth ) return SQLITE_OK; switch( code ){ case SQLITE_COPY : zCode="SQLITE_COPY"; break; case SQLITE_CREATE_INDEX : zCode="SQLITE_CREATE_INDEX"; break; case SQLITE_CREATE_TABLE : zCode="SQLITE_CREATE_TABLE"; break; case SQLITE_CREATE_TEMP_INDEX : zCode="SQLITE_CREATE_TEMP_INDEX"; break; case SQLITE_CREATE_TEMP_TABLE : zCode="SQLITE_CREATE_TEMP_TABLE"; break; case SQLITE_CREATE_TEMP_TRIGGER: zCode="SQLITE_CREATE_TEMP_TRIGGER"; break; case SQLITE_CREATE_TEMP_VIEW : zCode="SQLITE_CREATE_TEMP_VIEW"; break; case SQLITE_CREATE_TRIGGER : zCode="SQLITE_CREATE_TRIGGER"; break; case SQLITE_CREATE_VIEW : zCode="SQLITE_CREATE_VIEW"; break; case SQLITE_DELETE : zCode="SQLITE_DELETE"; break; case SQLITE_DROP_INDEX : zCode="SQLITE_DROP_INDEX"; break; case SQLITE_DROP_TABLE : zCode="SQLITE_DROP_TABLE"; break; case SQLITE_DROP_TEMP_INDEX : zCode="SQLITE_DROP_TEMP_INDEX"; break; case SQLITE_DROP_TEMP_TABLE : zCode="SQLITE_DROP_TEMP_TABLE"; break; case SQLITE_DROP_TEMP_TRIGGER : zCode="SQLITE_DROP_TEMP_TRIGGER"; break; case SQLITE_DROP_TEMP_VIEW : zCode="SQLITE_DROP_TEMP_VIEW"; break; case SQLITE_DROP_TRIGGER : zCode="SQLITE_DROP_TRIGGER"; break; case SQLITE_DROP_VIEW : zCode="SQLITE_DROP_VIEW"; break; case SQLITE_INSERT : zCode="SQLITE_INSERT"; break; case SQLITE_PRAGMA : zCode="SQLITE_PRAGMA"; break; case SQLITE_READ : zCode="SQLITE_READ"; break; case SQLITE_SELECT : zCode="SQLITE_SELECT"; break; case SQLITE_TRANSACTION : zCode="SQLITE_TRANSACTION"; break; case SQLITE_UPDATE : zCode="SQLITE_UPDATE"; break; case SQLITE_ATTACH : zCode="SQLITE_ATTACH"; break; case SQLITE_DETACH : zCode="SQLITE_DETACH"; break; case SQLITE_ALTER_TABLE : zCode="SQLITE_ALTER_TABLE"; break; case SQLITE_REINDEX : zCode="SQLITE_REINDEX"; break; case SQLITE_ANALYZE : zCode="SQLITE_ANALYZE"; break; case SQLITE_CREATE_VTABLE : zCode="SQLITE_CREATE_VTABLE"; break; case SQLITE_DROP_VTABLE : zCode="SQLITE_DROP_VTABLE"; break; case SQLITE_FUNCTION : zCode="SQLITE_FUNCTION"; break; case SQLITE_SAVEPOINT : zCode="SQLITE_SAVEPOINT"; break; default : zCode="????"; break; } Tcl_DStringInit(&str); Tcl_DStringAppend(&str, pDb->zAuth, -1); Tcl_DStringAppendElement(&str, zCode); Tcl_DStringAppendElement(&str, zArg1 ? zArg1 : ""); Tcl_DStringAppendElement(&str, zArg2 ? zArg2 : ""); Tcl_DStringAppendElement(&str, zArg3 ? zArg3 : ""); Tcl_DStringAppendElement(&str, zArg4 ? zArg4 : ""); rc = Tcl_GlobalEval(pDb->interp, Tcl_DStringValue(&str)); Tcl_DStringFree(&str); zReply = Tcl_GetStringResult(pDb->interp); if( strcmp(zReply,"SQLITE_OK")==0 ){ rc = SQLITE_OK; }else if( strcmp(zReply,"SQLITE_DENY")==0 ){ rc = SQLITE_DENY; }else if( strcmp(zReply,"SQLITE_IGNORE")==0 ){ rc = SQLITE_IGNORE; }else{ rc = 999; } return rc; } #endif /* SQLITE_OMIT_AUTHORIZATION */ /* ** zText is a pointer to text obtained via an sqlite3_result_text() ** or similar interface. This routine returns a Tcl string object, ** reference count set to 0, containing the text. If a translation ** between iso8859 and UTF-8 is required, it is preformed. */ static Tcl_Obj *dbTextToObj(char const *zText){ Tcl_Obj *pVal; #ifdef UTF_TRANSLATION_NEEDED Tcl_DString dCol; Tcl_DStringInit(&dCol); Tcl_ExternalToUtfDString(NULL, zText, -1, &dCol); pVal = Tcl_NewStringObj(Tcl_DStringValue(&dCol), -1); Tcl_DStringFree(&dCol); #else pVal = Tcl_NewStringObj(zText, -1); #endif return pVal; } /* ** This routine reads a line of text from FILE in, stores ** the text in memory obtained from malloc() and returns a pointer ** to the text. NULL is returned at end of file, or if malloc() ** fails. ** ** The interface is like "readline" but no command-line editing ** is done. ** ** copied from shell.c from '.import' command */ static char *local_getline(char *zPrompt, FILE *in){ char *zLine; int nLine; int n; int eol; nLine = 100; zLine = malloc( nLine ); if( zLine==0 ) return 0; n = 0; eol = 0; while( !eol ){ if( n+100>nLine ){ nLine = nLine*2 + 100; zLine = realloc(zLine, nLine); if( zLine==0 ) return 0; } if( fgets(&zLine[n], nLine - n, in)==0 ){ if( n==0 ){ free(zLine); return 0; } zLine[n] = 0; eol = 1; break; } while( zLine[n] ){ n++; } if( n>0 && zLine[n-1]=='\n' ){ n--; zLine[n] = 0; eol = 1; } } zLine = realloc( zLine, n+1 ); return zLine; } /* ** This function is part of the implementation of the command: ** ** $db transaction [-deferred|-immediate|-exclusive] SCRIPT ** ** It is invoked after evaluating the script SCRIPT to commit or rollback ** the transaction or savepoint opened by the [transaction] command. */ static int DbTransPostCmd( ClientData data[], /* data[0] is the Sqlite3Db* for $db */ Tcl_Interp *interp, /* Tcl interpreter */ int result /* Result of evaluating SCRIPT */ ){ static const char *azEnd[] = { "RELEASE _tcl_transaction", /* rc==TCL_ERROR, nTransaction!=0 */ "COMMIT", /* rc!=TCL_ERROR, nTransaction==0 */ "ROLLBACK TO _tcl_transaction ; RELEASE _tcl_transaction", "ROLLBACK" /* rc==TCL_ERROR, nTransaction==0 */ }; SqliteDb *pDb = (SqliteDb*)data[0]; int rc = result; const char *zEnd; pDb->nTransaction--; zEnd = azEnd[(rc==TCL_ERROR)*2 + (pDb->nTransaction==0)]; pDb->disableAuth++; if( sqlite3_exec(pDb->db, zEnd, 0, 0, 0) ){ /* This is a tricky scenario to handle. The most likely cause of an ** error is that the exec() above was an attempt to commit the ** top-level transaction that returned SQLITE_BUSY. Or, less likely, ** that an IO-error has occured. In either case, throw a Tcl exception ** and try to rollback the transaction. ** ** But it could also be that the user executed one or more BEGIN, ** COMMIT, SAVEPOINT, RELEASE or ROLLBACK commands that are confusing ** this method's logic. Not clear how this would be best handled. */ if( rc!=TCL_ERROR ){ Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0); rc = TCL_ERROR; } sqlite3_exec(pDb->db, "ROLLBACK", 0, 0, 0); } pDb->disableAuth--; return rc; } /* ** Unless SQLITE_TEST is defined, this function is a simple wrapper around ** sqlite3_prepare_v2(). If SQLITE_TEST is defined, then it uses either ** sqlite3_prepare_v2() or legacy interface sqlite3_prepare(), depending ** on whether or not the [db_use_legacy_prepare] command has been used to ** configure the connection. */ static int dbPrepare( SqliteDb *pDb, /* Database object */ const char *zSql, /* SQL to compile */ sqlite3_stmt **ppStmt, /* OUT: Prepared statement */ const char **pzOut /* OUT: Pointer to next SQL statement */ ){ #ifdef SQLITE_TEST if( pDb->bLegacyPrepare ){ return sqlite3_prepare(pDb->db, zSql, -1, ppStmt, pzOut); } #endif return sqlite3_prepare_v2(pDb->db, zSql, -1, ppStmt, pzOut); } /* ** Search the cache for a prepared-statement object that implements the ** first SQL statement in the buffer pointed to by parameter zIn. If ** no such prepared-statement can be found, allocate and prepare a new ** one. In either case, bind the current values of the relevant Tcl ** variables to any $var, :var or @var variables in the statement. Before ** returning, set *ppPreStmt to point to the prepared-statement object. ** ** Output parameter *pzOut is set to point to the next SQL statement in ** buffer zIn, or to the '\0' byte at the end of zIn if there is no ** next statement. ** ** If successful, TCL_OK is returned. Otherwise, TCL_ERROR is returned ** and an error message loaded into interpreter pDb->interp. */ static int dbPrepareAndBind( SqliteDb *pDb, /* Database object */ char const *zIn, /* SQL to compile */ char const **pzOut, /* OUT: Pointer to next SQL statement */ SqlPreparedStmt **ppPreStmt /* OUT: Object used to cache statement */ ){ const char *zSql = zIn; /* Pointer to first SQL statement in zIn */ sqlite3_stmt *pStmt; /* Prepared statement object */ SqlPreparedStmt *pPreStmt; /* Pointer to cached statement */ int nSql; /* Length of zSql in bytes */ int nVar; /* Number of variables in statement */ int iParm = 0; /* Next free entry in apParm */ int i; Tcl_Interp *interp = pDb->interp; *ppPreStmt = 0; /* Trim spaces from the start of zSql and calculate the remaining length. */ while( isspace(zSql[0]) ){ zSql++; } nSql = strlen30(zSql); for(pPreStmt = pDb->stmtList; pPreStmt; pPreStmt=pPreStmt->pNext){ int n = pPreStmt->nSql; if( nSql>=n && memcmp(pPreStmt->zSql, zSql, n)==0 && (zSql[n]==0 || zSql[n-1]==';') ){ pStmt = pPreStmt->pStmt; *pzOut = &zSql[pPreStmt->nSql]; /* When a prepared statement is found, unlink it from the ** cache list. It will later be added back to the beginning ** of the cache list in order to implement LRU replacement. */ if( pPreStmt->pPrev ){ pPreStmt->pPrev->pNext = pPreStmt->pNext; }else{ pDb->stmtList = pPreStmt->pNext; } if( pPreStmt->pNext ){ pPreStmt->pNext->pPrev = pPreStmt->pPrev; }else{ pDb->stmtLast = pPreStmt->pPrev; } pDb->nStmt--; nVar = sqlite3_bind_parameter_count(pStmt); break; } } /* If no prepared statement was found. Compile the SQL text. Also allocate ** a new SqlPreparedStmt structure. */ if( pPreStmt==0 ){ int nByte; if( SQLITE_OK!=dbPrepare(pDb, zSql, &pStmt, pzOut) ){ Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db))); return TCL_ERROR; } if( pStmt==0 ){ if( SQLITE_OK!=sqlite3_errcode(pDb->db) ){ /* A compile-time error in the statement. */ Tcl_SetObjResult(interp, dbTextToObj(sqlite3_errmsg(pDb->db))); return TCL_ERROR; }else{ /* The statement was a no-op. Continue to the next statement ** in the SQL string. */ return TCL_OK; } } assert( pPreStmt==0 ); nVar = sqlite3_bind_parameter_count(pStmt); nByte = sizeof(SqlPreparedStmt) + nVar*sizeof(Tcl_Obj *); pPreStmt = (SqlPreparedStmt*)Tcl_Alloc(nByte); memset(pPreStmt, 0, nByte); pPreStmt->pStmt = pStmt; pPreStmt->nSql = (*pzOut - zSql); pPreStmt->zSql = sqlite3_sql(pStmt); pPreStmt->apParm = (Tcl_Obj **)&pPreStmt[1]; #ifdef SQLITE_TEST if( pPreStmt->zSql==0 ){ char *zCopy = Tcl_Alloc(pPreStmt->nSql + 1); memcpy(zCopy, zSql, pPreStmt->nSql); zCopy[pPreStmt->nSql] = '\0'; pPreStmt->zSql = zCopy; } #endif } assert( pPreStmt ); assert( strlen30(pPreStmt->zSql)==pPreStmt->nSql ); assert( 0==memcmp(pPreStmt->zSql, zSql, pPreStmt->nSql) ); /* Bind values to parameters that begin with $ or : */ for(i=1; i<=nVar; i++){ const char *zVar = sqlite3_bind_parameter_name(pStmt, i); if( zVar!=0 && (zVar[0]=='$' || zVar[0]==':' || zVar[0]=='@') ){ Tcl_Obj *pVar = Tcl_GetVar2Ex(interp, &zVar[1], 0, 0); if( pVar ){ int n; u8 *data; const char *zType = (pVar->typePtr ? pVar->typePtr->name : ""); char c = zType[0]; if( zVar[0]=='@' || (c=='b' && strcmp(zType,"bytearray")==0 && pVar->bytes==0) ){ /* Load a BLOB type if the Tcl variable is a bytearray and ** it has no string representation or the host ** parameter name begins with "@". */ data = Tcl_GetByteArrayFromObj(pVar, &n); sqlite3_bind_blob(pStmt, i, data, n, SQLITE_STATIC); Tcl_IncrRefCount(pVar); pPreStmt->apParm[iParm++] = pVar; }else if( c=='b' && strcmp(zType,"boolean")==0 ){ Tcl_GetIntFromObj(interp, pVar, &n); sqlite3_bind_int(pStmt, i, n); }else if( c=='d' && strcmp(zType,"double")==0 ){ double r; Tcl_GetDoubleFromObj(interp, pVar, &r); sqlite3_bind_double(pStmt, i, r); }else if( (c=='w' && strcmp(zType,"wideInt")==0) || (c=='i' && strcmp(zType,"int")==0) ){ Tcl_WideInt v; Tcl_GetWideIntFromObj(interp, pVar, &v); sqlite3_bind_int64(pStmt, i, v); }else{ data = (unsigned char *)Tcl_GetStringFromObj(pVar, &n); sqlite3_bind_text(pStmt, i, (char *)data, n, SQLITE_STATIC); Tcl_IncrRefCount(pVar); pPreStmt->apParm[iParm++] = pVar; } }else{ sqlite3_bind_null(pStmt, i); } } } pPreStmt->nParm = iParm; *ppPreStmt = pPreStmt; return TCL_OK; } /* ** Release a statement reference obtained by calling dbPrepareAndBind(). ** There should be exactly one call to this function for each call to ** dbPrepareAndBind(). ** ** If the discard parameter is non-zero, then the statement is deleted ** immediately. Otherwise it is added to the LRU list and may be returned ** by a subsequent call to dbPrepareAndBind(). */ static void dbReleaseStmt( SqliteDb *pDb, /* Database handle */ SqlPreparedStmt *pPreStmt, /* Prepared statement handle to release */ int discard /* True to delete (not cache) the pPreStmt */ ){ int i; /* Free the bound string and blob parameters */ for(i=0; i<pPreStmt->nParm; i++){ Tcl_DecrRefCount(pPreStmt->apParm[i]); } pPreStmt->nParm = 0; if( pDb->maxStmt<=0 || discard ){ /* If the cache is turned off, deallocated the statement */ dbFreeStmt(pPreStmt); }else{ /* Add the prepared statement to the beginning of the cache list. */ pPreStmt->pNext = pDb->stmtList; pPreStmt->pPrev = 0; if( pDb->stmtList ){ pDb->stmtList->pPrev = pPreStmt; } pDb->stmtList = pPreStmt; if( pDb->stmtLast==0 ){ assert( pDb->nStmt==0 ); pDb->stmtLast = pPreStmt; }else{ assert( pDb->nStmt>0 ); } pDb->nStmt++; /* If we have too many statement in cache, remove the surplus from ** the end of the cache list. */ while( pDb->nStmt>pDb->maxStmt ){ SqlPreparedStmt *pLast = pDb->stmtLast; pDb->stmtLast = pLast->pPrev; pDb->stmtLast->pNext = 0; pDb->nStmt--; dbFreeStmt(pLast); } } } /* ** Structure used with dbEvalXXX() functions: ** ** dbEvalInit() ** dbEvalStep() ** dbEvalFinalize() ** dbEvalRowInfo() ** dbEvalColumnValue() */ typedef struct DbEvalContext DbEvalContext; struct DbEvalContext { SqliteDb *pDb; /* Database handle */ Tcl_Obj *pSql; /* Object holding string zSql */ const char *zSql; /* Remaining SQL to execute */ SqlPreparedStmt *pPreStmt; /* Current statement */ int nCol; /* Number of columns returned by pStmt */ Tcl_Obj *pArray; /* Name of array variable */ Tcl_Obj **apColName; /* Array of column names */ }; /* ** Release any cache of column names currently held as part of ** the DbEvalContext structure passed as the first argument. */ static void dbReleaseColumnNames(DbEvalContext *p){ if( p->apColName ){ int i; for(i=0; i<p->nCol; i++){ Tcl_DecrRefCount(p->apColName[i]); } Tcl_Free((char *)p->apColName); p->apColName = 0; } p->nCol = 0; } /* ** Initialize a DbEvalContext structure. ** ** If pArray is not NULL, then it contains the name of a Tcl array ** variable. The "*" member of this array is set to a list containing ** the names of the columns returned by the statement as part of each ** call to dbEvalStep(), in order from left to right. e.g. if the names ** of the returned columns are a, b and c, it does the equivalent of the ** tcl command: ** ** set ${pArray}(*) {a b c} */ static void dbEvalInit( DbEvalContext *p, /* Pointer to structure to initialize */ SqliteDb *pDb, /* Database handle */ Tcl_Obj *pSql, /* Object containing SQL script */ Tcl_Obj *pArray /* Name of Tcl array to set (*) element of */ ){ memset(p, 0, sizeof(DbEvalContext)); p->pDb = pDb; p->zSql = Tcl_GetString(pSql); p->pSql = pSql; Tcl_IncrRefCount(pSql); if( pArray ){ p->pArray = pArray; Tcl_IncrRefCount(pArray); } } /* ** Obtain information about the row that the DbEvalContext passed as the ** first argument currently points to. */ static void dbEvalRowInfo( DbEvalContext *p, /* Evaluation context */ int *pnCol, /* OUT: Number of column names */ Tcl_Obj ***papColName /* OUT: Array of column names */ ){ /* Compute column names */ if( 0==p->apColName ){ sqlite3_stmt *pStmt = p->pPreStmt->pStmt; int i; /* Iterator variable */ int nCol; /* Number of columns returned by pStmt */ Tcl_Obj **apColName = 0; /* Array of column names */ p->nCol = nCol = sqlite3_column_count(pStmt); if( nCol>0 && (papColName || p->pArray) ){ apColName = (Tcl_Obj**)Tcl_Alloc( sizeof(Tcl_Obj*)*nCol ); for(i=0; i<nCol; i++){ apColName[i] = dbTextToObj(sqlite3_column_name(pStmt,i)); Tcl_IncrRefCount(apColName[i]); } p->apColName = apColName; } /* If results are being stored in an array variable, then create ** the array(*) entry for that array */ if( p->pArray ){ Tcl_Interp *interp = p->pDb->interp; Tcl_Obj *pColList = Tcl_NewObj(); Tcl_Obj *pStar = Tcl_NewStringObj("*", -1); for(i=0; i<nCol; i++){ Tcl_ListObjAppendElement(interp, pColList, apColName[i]); } Tcl_IncrRefCount(pStar); Tcl_ObjSetVar2(interp, p->pArray, pStar, pColList, 0); Tcl_DecrRefCount(pStar); } } if( papColName ){ *papColName = p->apColName; } if( pnCol ){ *pnCol = p->nCol; } } /* ** Return one of TCL_OK, TCL_BREAK or TCL_ERROR. If TCL_ERROR is ** returned, then an error message is stored in the interpreter before ** returning. ** ** A return value of TCL_OK means there is a row of data available. The ** data may be accessed using dbEvalRowInfo() and dbEvalColumnValue(). This ** is analogous to a return of SQLITE_ROW from sqlite3_step(). If TCL_BREAK ** is returned, then the SQL script has finished executing and there are ** no further rows available. This is similar to SQLITE_DONE. */ static int dbEvalStep(DbEvalContext *p){ const char *zPrevSql = 0; /* Previous value of p->zSql */ while( p->zSql[0] || p->pPreStmt ){ int rc; if( p->pPreStmt==0 ){ zPrevSql = (p->zSql==zPrevSql ? 0 : p->zSql); rc = dbPrepareAndBind(p->pDb, p->zSql, &p->zSql, &p->pPreStmt); if( rc!=TCL_OK ) return rc; }else{ int rcs; SqliteDb *pDb = p->pDb; SqlPreparedStmt *pPreStmt = p->pPreStmt; sqlite3_stmt *pStmt = pPreStmt->pStmt; rcs = sqlite3_step(pStmt); if( rcs==SQLITE_ROW ){ return TCL_OK; } if( p->pArray ){ dbEvalRowInfo(p, 0, 0); } rcs = sqlite3_reset(pStmt); pDb->nStep = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_FULLSCAN_STEP,1); pDb->nSort = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_SORT,1); pDb->nIndex = sqlite3_stmt_status(pStmt,SQLITE_STMTSTATUS_AUTOINDEX,1); dbReleaseColumnNames(p); p->pPreStmt = 0; if( rcs!=SQLITE_OK ){ /* If a run-time error occurs, report the error and stop reading ** the SQL. */ dbReleaseStmt(pDb, pPreStmt, 1); #if SQLITE_TEST if( p->pDb->bLegacyPrepare && rcs==SQLITE_SCHEMA && zPrevSql ){ /* If the runtime error was an SQLITE_SCHEMA, and the database ** handle is configured to use the legacy sqlite3_prepare() ** interface, retry prepare()/step() on the same SQL statement. ** This only happens once. If there is a second SQLITE_SCHEMA ** error, the error will be returned to the caller. */ p->zSql = zPrevSql; continue; } #endif Tcl_SetObjResult(pDb->interp, dbTextToObj(sqlite3_errmsg(pDb->db))); return TCL_ERROR; }else{ dbReleaseStmt(pDb, pPreStmt, 0); } } } /* Finished */ return TCL_BREAK; } /* ** Free all resources currently held by the DbEvalContext structure passed ** as the first argument. There should be exactly one call to this function ** for each call to dbEvalInit(). */ static void dbEvalFinalize(DbEvalContext *p){ if( p->pPreStmt ){ sqlite3_reset(p->pPreStmt->pStmt); dbReleaseStmt(p->pDb, p->pPreStmt, 0); p->pPreStmt = 0; } if( p->pArray ){ Tcl_DecrRefCount(p->pArray); p->pArray = 0; } Tcl_DecrRefCount(p->pSql); dbReleaseColumnNames(p); } /* ** Return a pointer to a Tcl_Obj structure with ref-count 0 that contains ** the value for the iCol'th column of the row currently pointed to by ** the DbEvalContext structure passed as the first argument. */ static Tcl_Obj *dbEvalColumnValue(DbEvalContext *p, int iCol){ sqlite3_stmt *pStmt = p->pPreStmt->pStmt; switch( sqlite3_column_type(pStmt, iCol) ){ case SQLITE_BLOB: { int bytes = sqlite3_column_bytes(pStmt, iCol); const char *zBlob = sqlite3_column_blob(pStmt, iCol); if( !zBlob ) bytes = 0; return Tcl_NewByteArrayObj((u8*)zBlob, bytes); } case SQLITE_INTEGER: { sqlite_int64 v = sqlite3_column_int64(pStmt, iCol); if( v>=-2147483647 && v<=2147483647 ){ return Tcl_NewIntObj((int)v); }else{ return Tcl_NewWideIntObj(v); } } case SQLITE_FLOAT: { return Tcl_NewDoubleObj(sqlite3_column_double(pStmt, iCol)); } case SQLITE_NULL: { return dbTextToObj(p->pDb->zNull); } } return dbTextToObj((char *)sqlite3_column_text(pStmt, iCol)); } /* ** If using Tcl version 8.6 or greater, use the NR functions to avoid ** recursive evalution of scripts by the [db eval] and [db trans] ** commands. Even if the headers used while compiling the extension ** are 8.6 or newer, the code still tests the Tcl version at runtime. ** This allows stubs-enabled builds to be used with older Tcl libraries. */ #if TCL_MAJOR_VERSION>8 || (TCL_MAJOR_VERSION==8 && TCL_MINOR_VERSION>=6) # define SQLITE_TCL_NRE 1 static int DbUseNre(void){ int major, minor; Tcl_GetVersion(&major, &minor, 0, 0); return( (major==8 && minor>=6) || major>8 ); } #else /* ** Compiling using headers earlier than 8.6. In this case NR cannot be ** used, so DbUseNre() to always return zero. Add #defines for the other ** Tcl_NRxxx() functions to prevent them from causing compilation errors, ** even though the only invocations of them are within conditional blocks ** of the form: ** ** if( DbUseNre() ) { ... } */ # define SQLITE_TCL_NRE 0 # define DbUseNre() 0 # define Tcl_NRAddCallback(a,b,c,d,e,f) 0 # define Tcl_NREvalObj(a,b,c) 0 # define Tcl_NRCreateCommand(a,b,c,d,e,f) 0 #endif /* ** This function is part of the implementation of the command: ** ** $db eval SQL ?ARRAYNAME? SCRIPT */ static int DbEvalNextCmd( ClientData data[], /* data[0] is the (DbEvalContext*) */ Tcl_Interp *interp, /* Tcl interpreter */ int result /* Result so far */ ){ int rc = result; /* Return code */ /* The first element of the data[] array is a pointer to a DbEvalContext ** structure allocated using Tcl_Alloc(). The second element of data[] ** is a pointer to a Tcl_Obj containing the script to run for each row ** returned by the queries encapsulated in data[0]. */ DbEvalContext *p = (DbEvalContext *)data[0]; Tcl_Obj *pScript = (Tcl_Obj *)data[1]; Tcl_Obj *pArray = p->pArray; while( (rc==TCL_OK || rc==TCL_CONTINUE) && TCL_OK==(rc = dbEvalStep(p)) ){ int i; int nCol; Tcl_Obj **apColName; dbEvalRowInfo(p, &nCol, &apColName); for(i=0; i<nCol; i++){ Tcl_Obj *pVal = dbEvalColumnValue(p, i); if( pArray==0 ){ Tcl_ObjSetVar2(interp, apColName[i], 0, pVal, 0); }else{ Tcl_ObjSetVar2(interp, pArray, apColName[i], pVal, 0); } } /* The required interpreter variables are now populated with the data ** from the current row. If using NRE, schedule callbacks to evaluate ** script pScript, then to invoke this function again to fetch the next ** row (or clean up if there is no next row or the script throws an ** exception). After scheduling the callbacks, return control to the ** caller. ** ** If not using NRE, evaluate pScript directly and continue with the ** next iteration of this while(...) loop. */ if( DbUseNre() ){ Tcl_NRAddCallback(interp, DbEvalNextCmd, (void*)p, (void*)pScript, 0, 0); return Tcl_NREvalObj(interp, pScript, 0); }else{ rc = Tcl_EvalObjEx(interp, pScript, 0); } } Tcl_DecrRefCount(pScript); dbEvalFinalize(p); Tcl_Free((char *)p); if( rc==TCL_OK || rc==TCL_BREAK ){ Tcl_ResetResult(interp); rc = TCL_OK; } return rc; } /* ** The "sqlite" command below creates a new Tcl command for each ** connection it opens to an SQLite database. This routine is invoked ** whenever one of those connection-specific commands is executed ** in Tcl. For example, if you run Tcl code like this: ** ** sqlite3 db1 "my_database" ** db1 close ** ** The first command opens a connection to the "my_database" database ** and calls that connection "db1". The second command causes this ** subroutine to be invoked. */ static int DbObjCmd(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){ SqliteDb *pDb = (SqliteDb*)cd; int choice; int rc = TCL_OK; static const char *DB_strs[] = { "authorizer", "backup", "busy", "cache", "changes", "close", "collate", "collation_needed", "commit_hook", "complete", "copy", "enable_load_extension", "errorcode", "eval", "exists", "function", "incrblob", "interrupt", "last_insert_rowid", "nullvalue", "onecolumn", "profile", "progress", "rekey", "restore", "rollback_hook", "status", "timeout", "total_changes", "trace", "transaction", "unlock_notify", "update_hook", "version", "wal_hook", 0 }; enum DB_enum { DB_AUTHORIZER, DB_BACKUP, DB_BUSY, DB_CACHE, DB_CHANGES, DB_CLOSE, DB_COLLATE, DB_COLLATION_NEEDED, DB_COMMIT_HOOK, DB_COMPLETE, DB_COPY, DB_ENABLE_LOAD_EXTENSION, DB_ERRORCODE, DB_EVAL, DB_EXISTS, DB_FUNCTION, DB_INCRBLOB, DB_INTERRUPT, DB_LAST_INSERT_ROWID, DB_NULLVALUE, DB_ONECOLUMN, DB_PROFILE, DB_PROGRESS, DB_REKEY, DB_RESTORE, DB_ROLLBACK_HOOK, DB_STATUS, DB_TIMEOUT, DB_TOTAL_CHANGES, DB_TRACE, DB_TRANSACTION, DB_UNLOCK_NOTIFY, DB_UPDATE_HOOK, DB_VERSION, DB_WAL_HOOK }; /* don't leave trailing commas on DB_enum, it confuses the AIX xlc compiler */ if( objc<2 ){ Tcl_WrongNumArgs(interp, 1, objv, "SUBCOMMAND ..."); return TCL_ERROR; } if( Tcl_GetIndexFromObj(interp, objv[1], DB_strs, "option", 0, &choice) ){ return TCL_ERROR; } switch( (enum DB_enum)choice ){ /* $db authorizer ?CALLBACK? ** ** Invoke the given callback to authorize each SQL operation as it is ** compiled. 5 arguments are appended to the callback before it is ** invoked: ** ** (1) The authorization type (ex: SQLITE_CREATE_TABLE, SQLITE_INSERT, ...) ** (2) First descriptive name (depends on authorization type) ** (3) Second descriptive name ** (4) Name of the database (ex: "main", "temp") ** (5) Name of trigger that is doing the access ** ** The callback should return on of the following strings: SQLITE_OK, ** SQLITE_IGNORE, or SQLITE_DENY. Any other return value is an error. ** ** If this method is invoked with no arguments, the current authorization ** callback string is returned. */ case DB_AUTHORIZER: { #ifdef SQLITE_OMIT_AUTHORIZATION Tcl_AppendResult(interp, "authorization not available in this build", 0); return TCL_ERROR; #else if( objc>3 ){ Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); return TCL_ERROR; }else if( objc==2 ){ if( pDb->zAuth ){ Tcl_AppendResult(interp, pDb->zAuth, 0); } }else{ char *zAuth; int len; if( pDb->zAuth ){ Tcl_Free(pDb->zAuth); } zAuth = Tcl_GetStringFromObj(objv[2], &len); if( zAuth && len>0 ){ pDb->zAuth = Tcl_Alloc( len + 1 ); memcpy(pDb->zAuth, zAuth, len+1); }else{ pDb->zAuth = 0; } if( pDb->zAuth ){ pDb->interp = interp; sqlite3_set_authorizer(pDb->db, auth_callback, pDb); }else{ sqlite3_set_authorizer(pDb->db, 0, 0); } } #endif break; } /* $db backup ?DATABASE? FILENAME ** ** Open or create a database file named FILENAME. Transfer the ** content of local database DATABASE (default: "main") into the ** FILENAME database. */ case DB_BACKUP: { const char *zDestFile; const char *zSrcDb; sqlite3 *pDest; sqlite3_backup *pBackup; if( objc==3 ){ zSrcDb = "main"; zDestFile = Tcl_GetString(objv[2]); }else if( objc==4 ){ zSrcDb = Tcl_GetString(objv[2]); zDestFile = Tcl_GetString(objv[3]); }else{ Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME"); return TCL_ERROR; } rc = sqlite3_open(zDestFile, &pDest); if( rc!=SQLITE_OK ){ Tcl_AppendResult(interp, "cannot open target database: ", sqlite3_errmsg(pDest), (char*)0); sqlite3_close(pDest); return TCL_ERROR; } pBackup = sqlite3_backup_init(pDest, "main", pDb->db, zSrcDb); if( pBackup==0 ){ Tcl_AppendResult(interp, "backup failed: ", sqlite3_errmsg(pDest), (char*)0); sqlite3_close(pDest); return TCL_ERROR; } while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK ){} sqlite3_backup_finish(pBackup); if( rc==SQLITE_DONE ){ rc = TCL_OK; }else{ Tcl_AppendResult(interp, "backup failed: ", sqlite3_errmsg(pDest), (char*)0); rc = TCL_ERROR; } sqlite3_close(pDest); break; } /* $db busy ?CALLBACK? ** ** Invoke the given callback if an SQL statement attempts to open ** a locked database file. */ case DB_BUSY: { if( objc>3 ){ Tcl_WrongNumArgs(interp, 2, objv, "CALLBACK"); return TCL_ERROR; }else if( objc==2 ){ if( pDb->zBusy ){ Tcl_AppendResult(interp, pDb->zBusy, 0); } }else{ char *zBusy; int len; if( pDb->zBusy ){ Tcl_Free(pDb->zBusy); } zBusy = Tcl_GetStringFromObj(objv[2], &len); if( zBusy && len>0 ){ pDb->zBusy = Tcl_Alloc( len + 1 ); memcpy(pDb->zBusy, zBusy, len+1); }else{ pDb->zBusy = 0; } if( pDb->zBusy ){ pDb->interp = interp; sqlite3_busy_handler(pDb->db, DbBusyHandler, pDb); }else{ sqlite3_busy_handler(pDb->db, 0, 0); } } break; } /* $db cache flush ** $db cache size n ** ** Flush the prepared statement cache, or set the maximum number of ** cached statements. */ case DB_CACHE: { char *subCmd; int n; if( objc<=2 ){ Tcl_WrongNumArgs(interp, 1, objv, "cache option ?arg?"); return TCL_ERROR; } subCmd = Tcl_GetStringFromObj( objv[2], 0 ); if( *subCmd=='f' && strcmp(subCmd,"flush")==0 ){ if( objc!=3 ){ Tcl_WrongNumArgs(interp, 2, objv, "flush"); return TCL_ERROR; }else{ flushStmtCache( pDb ); } }else if( *subCmd=='s' && strcmp(subCmd,"size")==0 ){ if( objc!=4 ){ Tcl_WrongNumArgs(interp, 2, objv, "size n"); return TCL_ERROR; }else{ if( TCL_ERROR==Tcl_GetIntFromObj(interp, objv[3], &n) ){ Tcl_AppendResult( interp, "cannot convert \"", Tcl_GetStringFromObj(objv[3],0), "\" to integer", 0); return TCL_ERROR; }else{ if( n<0 ){ flushStmtCache( pDb ); n = 0; }else if( n>MAX_PREPARED_STMTS ){ n = MAX_PREPARED_STMTS; } pDb->maxStmt = n; } } }else{ Tcl_AppendResult( interp, "bad option \"", Tcl_GetStringFromObj(objv[2],0), "\": must be flush or size", 0); return TCL_ERROR; } break; } /* $db changes ** ** Return the number of rows that were modified, inserted, or deleted by ** the most recent INSERT, UPDATE or DELETE statement, not including ** any changes made by trigger programs. */ case DB_CHANGES: { Tcl_Obj *pResult; if( objc!=2 ){ Tcl_WrongNumArgs(interp, 2, objv, ""); return TCL_ERROR; } pResult = Tcl_GetObjResult(interp); Tcl_SetIntObj(pResult, sqlite3_changes(pDb->db)); break; } /* $db close ** ** Shutdown the database */ case DB_CLOSE: { Tcl_DeleteCommand(interp, Tcl_GetStringFromObj(objv[0], 0)); break; } /* ** $db collate NAME SCRIPT ** ** Create a new SQL collation function called NAME. Whenever ** that function is called, invoke SCRIPT to evaluate the function. */ case DB_COLLATE: { SqlCollate *pCollate; char *zName; char *zScript; int nScript; if( objc!=4 ){ Tcl_WrongNumArgs(interp, 2, objv, "NAME SCRIPT"); return TCL_ERROR; } zName = Tcl_GetStringFromObj(objv[2], 0); zScript = Tcl_GetStringFromObj(objv[3], &nScript); pCollate = (SqlCollate*)Tcl_Alloc( sizeof(*pCollate) + nScript + 1 ); if( pCollate==0 ) return TCL_ERROR; pCollate->interp = interp; pCollate->pNext = pDb->pCollate; pCollate->zScript = (char*)&pCollate[1]; pDb->pCollate = pCollate; memcpy(pCollate->zScript, zScript, nScript+1); if( sqlite3_create_collation(pDb->db, zName, SQLITE_UTF8, pCollate, tclSqlCollate) ){ Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); return TCL_ERROR; } break; } /* ** $db collation_needed SCRIPT ** ** Create a new SQL collation function called NAME. Whenever ** that function is called, invoke SCRIPT to evaluate the function. */ case DB_COLLATION_NEEDED: { if( objc!=3 ){ Tcl_WrongNumArgs(interp, 2, objv, "SCRIPT"); return TCL_ERROR; } if( pDb->pCollateNeeded ){ Tcl_DecrRefCount(pDb->pCollateNeeded); } pDb->pCollateNeeded = Tcl_DuplicateObj(objv[2]); Tcl_IncrRefCount(pDb->pCollateNeeded); sqlite3_collation_needed(pDb->db, pDb, tclCollateNeeded); break; } /* $db commit_hook ?CALLBACK? ** ** Invoke the given callback just before committing every SQL transaction. ** If the callback throws an exception or returns non-zero, then the ** transaction is aborted. If CALLBACK is an empty string, the callback ** is disabled. */ case DB_COMMIT_HOOK: { if( objc>3 ){ Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); return TCL_ERROR; }else if( objc==2 ){ if( pDb->zCommit ){ Tcl_AppendResult(interp, pDb->zCommit, 0); } }else{ char *zCommit; int len; if( pDb->zCommit ){ Tcl_Free(pDb->zCommit); } zCommit = Tcl_GetStringFromObj(objv[2], &len); if( zCommit && len>0 ){ pDb->zCommit = Tcl_Alloc( len + 1 ); memcpy(pDb->zCommit, zCommit, len+1); }else{ pDb->zCommit = 0; } if( pDb->zCommit ){ pDb->interp = interp; sqlite3_commit_hook(pDb->db, DbCommitHandler, pDb); }else{ sqlite3_commit_hook(pDb->db, 0, 0); } } break; } /* $db complete SQL ** ** Return TRUE if SQL is a complete SQL statement. Return FALSE if ** additional lines of input are needed. This is similar to the ** built-in "info complete" command of Tcl. */ case DB_COMPLETE: { #ifndef SQLITE_OMIT_COMPLETE Tcl_Obj *pResult; int isComplete; if( objc!=3 ){ Tcl_WrongNumArgs(interp, 2, objv, "SQL"); return TCL_ERROR; } isComplete = sqlite3_complete( Tcl_GetStringFromObj(objv[2], 0) ); pResult = Tcl_GetObjResult(interp); Tcl_SetBooleanObj(pResult, isComplete); #endif break; } /* $db copy conflict-algorithm table filename ?SEPARATOR? ?NULLINDICATOR? ** ** Copy data into table from filename, optionally using SEPARATOR ** as column separators. If a column contains a null string, or the ** value of NULLINDICATOR, a NULL is inserted for the column. ** conflict-algorithm is one of the sqlite conflict algorithms: ** rollback, abort, fail, ignore, replace ** On success, return the number of lines processed, not necessarily same ** as 'db changes' due to conflict-algorithm selected. ** ** This code is basically an implementation/enhancement of ** the sqlite3 shell.c ".import" command. ** ** This command usage is equivalent to the sqlite2.x COPY statement, ** which imports file data into a table using the PostgreSQL COPY file format: ** $db copy $conflit_algo $table_name $filename \t \\N */ case DB_COPY: { char *zTable; /* Insert data into this table */ char *zFile; /* The file from which to extract data */ char *zConflict; /* The conflict algorithm to use */ sqlite3_stmt *pStmt; /* A statement */ int nCol; /* Number of columns in the table */ int nByte; /* Number of bytes in an SQL string */ int i, j; /* Loop counters */ int nSep; /* Number of bytes in zSep[] */ int nNull; /* Number of bytes in zNull[] */ char *zSql; /* An SQL statement */ char *zLine; /* A single line of input from the file */ char **azCol; /* zLine[] broken up into columns */ char *zCommit; /* How to commit changes */ FILE *in; /* The input file */ int lineno = 0; /* Line number of input file */ char zLineNum[80]; /* Line number print buffer */ Tcl_Obj *pResult; /* interp result */ char *zSep; char *zNull; if( objc<5 || objc>7 ){ Tcl_WrongNumArgs(interp, 2, objv, "CONFLICT-ALGORITHM TABLE FILENAME ?SEPARATOR? ?NULLINDICATOR?"); return TCL_ERROR; } if( objc>=6 ){ zSep = Tcl_GetStringFromObj(objv[5], 0); }else{ zSep = "\t"; } if( objc>=7 ){ zNull = Tcl_GetStringFromObj(objv[6], 0); }else{ zNull = ""; } zConflict = Tcl_GetStringFromObj(objv[2], 0); zTable = Tcl_GetStringFromObj(objv[3], 0); zFile = Tcl_GetStringFromObj(objv[4], 0); nSep = strlen30(zSep); nNull = strlen30(zNull); if( nSep==0 ){ Tcl_AppendResult(interp,"Error: non-null separator required for copy",0); return TCL_ERROR; } if(strcmp(zConflict, "rollback") != 0 && strcmp(zConflict, "abort" ) != 0 && strcmp(zConflict, "fail" ) != 0 && strcmp(zConflict, "ignore" ) != 0 && strcmp(zConflict, "replace" ) != 0 ) { Tcl_AppendResult(interp, "Error: \"", zConflict, "\", conflict-algorithm must be one of: rollback, " "abort, fail, ignore, or replace", 0); return TCL_ERROR; } zSql = sqlite3_mprintf("SELECT * FROM '%q'", zTable); if( zSql==0 ){ Tcl_AppendResult(interp, "Error: no such table: ", zTable, 0); return TCL_ERROR; } nByte = strlen30(zSql); rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); if( rc ){ Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0); nCol = 0; }else{ nCol = sqlite3_column_count(pStmt); } sqlite3_finalize(pStmt); if( nCol==0 ) { return TCL_ERROR; } zSql = malloc( nByte + 50 + nCol*2 ); if( zSql==0 ) { Tcl_AppendResult(interp, "Error: can't malloc()", 0); return TCL_ERROR; } sqlite3_snprintf(nByte+50, zSql, "INSERT OR %q INTO '%q' VALUES(?", zConflict, zTable); j = strlen30(zSql); for(i=1; i<nCol; i++){ zSql[j++] = ','; zSql[j++] = '?'; } zSql[j++] = ')'; zSql[j] = 0; rc = sqlite3_prepare(pDb->db, zSql, -1, &pStmt, 0); free(zSql); if( rc ){ Tcl_AppendResult(interp, "Error: ", sqlite3_errmsg(pDb->db), 0); sqlite3_finalize(pStmt); return TCL_ERROR; } in = fopen(zFile, "rb"); if( in==0 ){ Tcl_AppendResult(interp, "Error: cannot open file: ", zFile, NULL); sqlite3_finalize(pStmt); return TCL_ERROR; } azCol = malloc( sizeof(azCol[0])*(nCol+1) ); if( azCol==0 ) { Tcl_AppendResult(interp, "Error: can't malloc()", 0); fclose(in); return TCL_ERROR; } (void)sqlite3_exec(pDb->db, "BEGIN", 0, 0, 0); zCommit = "COMMIT"; while( (zLine = local_getline(0, in))!=0 ){ char *z; i = 0; lineno++; azCol[0] = zLine; for(i=0, z=zLine; *z; z++){ if( *z==zSep[0] && strncmp(z, zSep, nSep)==0 ){ *z = 0; i++; if( i<nCol ){ azCol[i] = &z[nSep]; z += nSep-1; } } } if( i+1!=nCol ){ char *zErr; int nErr = strlen30(zFile) + 200; zErr = malloc(nErr); if( zErr ){ sqlite3_snprintf(nErr, zErr, "Error: %s line %d: expected %d columns of data but found %d", zFile, lineno, nCol, i+1); Tcl_AppendResult(interp, zErr, 0); free(zErr); } zCommit = "ROLLBACK"; break; } for(i=0; i<nCol; i++){ /* check for null data, if so, bind as null */ if( (nNull>0 && strcmp(azCol[i], zNull)==0) || strlen30(azCol[i])==0 ){ sqlite3_bind_null(pStmt, i+1); }else{ sqlite3_bind_text(pStmt, i+1, azCol[i], -1, SQLITE_STATIC); } } sqlite3_step(pStmt); rc = sqlite3_reset(pStmt); free(zLine); if( rc!=SQLITE_OK ){ Tcl_AppendResult(interp,"Error: ", sqlite3_errmsg(pDb->db), 0); zCommit = "ROLLBACK"; break; } } free(azCol); fclose(in); sqlite3_finalize(pStmt); (void)sqlite3_exec(pDb->db, zCommit, 0, 0, 0); if( zCommit[0] == 'C' ){ /* success, set result as number of lines processed */ pResult = Tcl_GetObjResult(interp); Tcl_SetIntObj(pResult, lineno); rc = TCL_OK; }else{ /* failure, append lineno where failed */ sqlite3_snprintf(sizeof(zLineNum), zLineNum,"%d",lineno); Tcl_AppendResult(interp,", failed while processing line: ",zLineNum,0); rc = TCL_ERROR; } break; } /* ** $db enable_load_extension BOOLEAN ** ** Turn the extension loading feature on or off. It if off by ** default. */ case DB_ENABLE_LOAD_EXTENSION: { #ifndef SQLITE_OMIT_LOAD_EXTENSION int onoff; if( objc!=3 ){ Tcl_WrongNumArgs(interp, 2, objv, "BOOLEAN"); return TCL_ERROR; } if( Tcl_GetBooleanFromObj(interp, objv[2], &onoff) ){ return TCL_ERROR; } sqlite3_enable_load_extension(pDb->db, onoff); break; #else Tcl_AppendResult(interp, "extension loading is turned off at compile-time", 0); return TCL_ERROR; #endif } /* ** $db errorcode ** ** Return the numeric error code that was returned by the most recent ** call to sqlite3_exec(). */ case DB_ERRORCODE: { Tcl_SetObjResult(interp, Tcl_NewIntObj(sqlite3_errcode(pDb->db))); break; } /* ** $db exists $sql ** $db onecolumn $sql ** ** The onecolumn method is the equivalent of: ** lindex [$db eval $sql] 0 */ case DB_EXISTS: case DB_ONECOLUMN: { DbEvalContext sEval; if( objc!=3 ){ Tcl_WrongNumArgs(interp, 2, objv, "SQL"); return TCL_ERROR; } dbEvalInit(&sEval, pDb, objv[2], 0); rc = dbEvalStep(&sEval); if( choice==DB_ONECOLUMN ){ if( rc==TCL_OK ){ Tcl_SetObjResult(interp, dbEvalColumnValue(&sEval, 0)); }else if( rc==TCL_BREAK ){ Tcl_ResetResult(interp); } }else if( rc==TCL_BREAK || rc==TCL_OK ){ Tcl_SetObjResult(interp, Tcl_NewBooleanObj(rc==TCL_OK)); } dbEvalFinalize(&sEval); if( rc==TCL_BREAK ){ rc = TCL_OK; } break; } /* ** $db eval $sql ?array? ?{ ...code... }? ** ** The SQL statement in $sql is evaluated. For each row, the values are ** placed in elements of the array named "array" and ...code... is executed. ** If "array" and "code" are omitted, then no callback is every invoked. ** If "array" is an empty string, then the values are placed in variables ** that have the same name as the fields extracted by the query. */ case DB_EVAL: { if( objc<3 || objc>5 ){ Tcl_WrongNumArgs(interp, 2, objv, "SQL ?ARRAY-NAME? ?SCRIPT?"); return TCL_ERROR; } if( objc==3 ){ DbEvalContext sEval; Tcl_Obj *pRet = Tcl_NewObj(); Tcl_IncrRefCount(pRet); dbEvalInit(&sEval, pDb, objv[2], 0); while( TCL_OK==(rc = dbEvalStep(&sEval)) ){ int i; int nCol; dbEvalRowInfo(&sEval, &nCol, 0); for(i=0; i<nCol; i++){ Tcl_ListObjAppendElement(interp, pRet, dbEvalColumnValue(&sEval, i)); } } dbEvalFinalize(&sEval); if( rc==TCL_BREAK ){ Tcl_SetObjResult(interp, pRet); rc = TCL_OK; } Tcl_DecrRefCount(pRet); }else{ ClientData cd[2]; DbEvalContext *p; Tcl_Obj *pArray = 0; Tcl_Obj *pScript; if( objc==5 && *(char *)Tcl_GetString(objv[3]) ){ pArray = objv[3]; } pScript = objv[objc-1]; Tcl_IncrRefCount(pScript); p = (DbEvalContext *)Tcl_Alloc(sizeof(DbEvalContext)); dbEvalInit(p, pDb, objv[2], pArray); cd[0] = (void *)p; cd[1] = (void *)pScript; rc = DbEvalNextCmd(cd, interp, TCL_OK); } break; } /* ** $db function NAME [-argcount N] SCRIPT ** ** Create a new SQL function called NAME. Whenever that function is ** called, invoke SCRIPT to evaluate the function. */ case DB_FUNCTION: { SqlFunc *pFunc; Tcl_Obj *pScript; char *zName; int nArg = -1; if( objc==6 ){ const char *z = Tcl_GetString(objv[3]); int n = strlen30(z); if( n>2 && strncmp(z, "-argcount",n)==0 ){ if( Tcl_GetIntFromObj(interp, objv[4], &nArg) ) return TCL_ERROR; if( nArg<0 ){ Tcl_AppendResult(interp, "number of arguments must be non-negative", (char*)0); return TCL_ERROR; } } pScript = objv[5]; }else if( objc!=4 ){ Tcl_WrongNumArgs(interp, 2, objv, "NAME [-argcount N] SCRIPT"); return TCL_ERROR; }else{ pScript = objv[3]; } zName = Tcl_GetStringFromObj(objv[2], 0); pFunc = findSqlFunc(pDb, zName); if( pFunc==0 ) return TCL_ERROR; if( pFunc->pScript ){ Tcl_DecrRefCount(pFunc->pScript); } pFunc->pScript = pScript; Tcl_IncrRefCount(pScript); pFunc->useEvalObjv = safeToUseEvalObjv(interp, pScript); rc = sqlite3_create_function(pDb->db, zName, nArg, SQLITE_UTF8, pFunc, tclSqlFunc, 0, 0); if( rc!=SQLITE_OK ){ rc = TCL_ERROR; Tcl_SetResult(interp, (char *)sqlite3_errmsg(pDb->db), TCL_VOLATILE); } break; } /* ** $db incrblob ?-readonly? ?DB? TABLE COLUMN ROWID */ case DB_INCRBLOB: { #ifdef SQLITE_OMIT_INCRBLOB Tcl_AppendResult(interp, "incrblob not available in this build", 0); return TCL_ERROR; #else int isReadonly = 0; const char *zDb = "main"; const char *zTable; const char *zColumn; sqlite_int64 iRow; /* Check for the -readonly option */ if( objc>3 && strcmp(Tcl_GetString(objv[2]), "-readonly")==0 ){ isReadonly = 1; } if( objc!=(5+isReadonly) && objc!=(6+isReadonly) ){ Tcl_WrongNumArgs(interp, 2, objv, "?-readonly? ?DB? TABLE COLUMN ROWID"); return TCL_ERROR; } if( objc==(6+isReadonly) ){ zDb = Tcl_GetString(objv[2]); } zTable = Tcl_GetString(objv[objc-3]); zColumn = Tcl_GetString(objv[objc-2]); rc = Tcl_GetWideIntFromObj(interp, objv[objc-1], &iRow); if( rc==TCL_OK ){ rc = createIncrblobChannel( interp, pDb, zDb, zTable, zColumn, iRow, isReadonly ); } #endif break; } /* ** $db interrupt ** ** Interrupt the execution of the inner-most SQL interpreter. This ** causes the SQL statement to return an error of SQLITE_INTERRUPT. */ case DB_INTERRUPT: { sqlite3_interrupt(pDb->db); break; } /* ** $db nullvalue ?STRING? ** ** Change text used when a NULL comes back from the database. If ?STRING? ** is not present, then the current string used for NULL is returned. ** If STRING is present, then STRING is returned. ** */ case DB_NULLVALUE: { if( objc!=2 && objc!=3 ){ Tcl_WrongNumArgs(interp, 2, objv, "NULLVALUE"); return TCL_ERROR; } if( objc==3 ){ int len; char *zNull = Tcl_GetStringFromObj(objv[2], &len); if( pDb->zNull ){ Tcl_Free(pDb->zNull); } if( zNull && len>0 ){ pDb->zNull = Tcl_Alloc( len + 1 ); memcpy(pDb->zNull, zNull, len); pDb->zNull[len] = '\0'; }else{ pDb->zNull = 0; } } Tcl_SetObjResult(interp, dbTextToObj(pDb->zNull)); break; } /* ** $db last_insert_rowid ** ** Return an integer which is the ROWID for the most recent insert. */ case DB_LAST_INSERT_ROWID: { Tcl_Obj *pResult; Tcl_WideInt rowid; if( objc!=2 ){ Tcl_WrongNumArgs(interp, 2, objv, ""); return TCL_ERROR; } rowid = sqlite3_last_insert_rowid(pDb->db); pResult = Tcl_GetObjResult(interp); Tcl_SetWideIntObj(pResult, rowid); break; } /* ** The DB_ONECOLUMN method is implemented together with DB_EXISTS. */ /* $db progress ?N CALLBACK? ** ** Invoke the given callback every N virtual machine opcodes while executing ** queries. */ case DB_PROGRESS: { if( objc==2 ){ if( pDb->zProgress ){ Tcl_AppendResult(interp, pDb->zProgress, 0); } }else if( objc==4 ){ char *zProgress; int len; int N; if( TCL_OK!=Tcl_GetIntFromObj(interp, objv[2], &N) ){ return TCL_ERROR; }; if( pDb->zProgress ){ Tcl_Free(pDb->zProgress); } zProgress = Tcl_GetStringFromObj(objv[3], &len); if( zProgress && len>0 ){ pDb->zProgress = Tcl_Alloc( len + 1 ); memcpy(pDb->zProgress, zProgress, len+1); }else{ pDb->zProgress = 0; } #ifndef SQLITE_OMIT_PROGRESS_CALLBACK if( pDb->zProgress ){ pDb->interp = interp; sqlite3_progress_handler(pDb->db, N, DbProgressHandler, pDb); }else{ sqlite3_progress_handler(pDb->db, 0, 0, 0); } #endif }else{ Tcl_WrongNumArgs(interp, 2, objv, "N CALLBACK"); return TCL_ERROR; } break; } /* $db profile ?CALLBACK? ** ** Make arrangements to invoke the CALLBACK routine after each SQL statement ** that has run. The text of the SQL and the amount of elapse time are ** appended to CALLBACK before the script is run. */ case DB_PROFILE: { if( objc>3 ){ Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); return TCL_ERROR; }else if( objc==2 ){ if( pDb->zProfile ){ Tcl_AppendResult(interp, pDb->zProfile, 0); } }else{ char *zProfile; int len; if( pDb->zProfile ){ Tcl_Free(pDb->zProfile); } zProfile = Tcl_GetStringFromObj(objv[2], &len); if( zProfile && len>0 ){ pDb->zProfile = Tcl_Alloc( len + 1 ); memcpy(pDb->zProfile, zProfile, len+1); }else{ pDb->zProfile = 0; } #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) if( pDb->zProfile ){ pDb->interp = interp; sqlite3_profile(pDb->db, DbProfileHandler, pDb); }else{ sqlite3_profile(pDb->db, 0, 0); } #endif } break; } /* ** $db rekey KEY ** ** Change the encryption key on the currently open database. */ case DB_REKEY: { int nKey; void *pKey; if( objc!=3 ){ Tcl_WrongNumArgs(interp, 2, objv, "KEY"); return TCL_ERROR; } pKey = Tcl_GetByteArrayFromObj(objv[2], &nKey); #ifdef SQLITE_HAS_CODEC rc = sqlite3_rekey(pDb->db, pKey, nKey); if( rc ){ Tcl_AppendResult(interp, sqlite3ErrStr(rc), 0); rc = TCL_ERROR; } #endif break; } /* $db restore ?DATABASE? FILENAME ** ** Open a database file named FILENAME. Transfer the content ** of FILENAME into the local database DATABASE (default: "main"). */ case DB_RESTORE: { const char *zSrcFile; const char *zDestDb; sqlite3 *pSrc; sqlite3_backup *pBackup; int nTimeout = 0; if( objc==3 ){ zDestDb = "main"; zSrcFile = Tcl_GetString(objv[2]); }else if( objc==4 ){ zDestDb = Tcl_GetString(objv[2]); zSrcFile = Tcl_GetString(objv[3]); }else{ Tcl_WrongNumArgs(interp, 2, objv, "?DATABASE? FILENAME"); return TCL_ERROR; } rc = sqlite3_open_v2(zSrcFile, &pSrc, SQLITE_OPEN_READONLY, 0); if( rc!=SQLITE_OK ){ Tcl_AppendResult(interp, "cannot open source database: ", sqlite3_errmsg(pSrc), (char*)0); sqlite3_close(pSrc); return TCL_ERROR; } pBackup = sqlite3_backup_init(pDb->db, zDestDb, pSrc, "main"); if( pBackup==0 ){ Tcl_AppendResult(interp, "restore failed: ", sqlite3_errmsg(pDb->db), (char*)0); sqlite3_close(pSrc); return TCL_ERROR; } while( (rc = sqlite3_backup_step(pBackup,100))==SQLITE_OK || rc==SQLITE_BUSY ){ if( rc==SQLITE_BUSY ){ if( nTimeout++ >= 3 ) break; sqlite3_sleep(100); } } sqlite3_backup_finish(pBackup); if( rc==SQLITE_DONE ){ rc = TCL_OK; }else if( rc==SQLITE_BUSY || rc==SQLITE_LOCKED ){ Tcl_AppendResult(interp, "restore failed: source database busy", (char*)0); rc = TCL_ERROR; }else{ Tcl_AppendResult(interp, "restore failed: ", sqlite3_errmsg(pDb->db), (char*)0); rc = TCL_ERROR; } sqlite3_close(pSrc); break; } /* ** $db status (step|sort|autoindex) ** ** Display SQLITE_STMTSTATUS_FULLSCAN_STEP or ** SQLITE_STMTSTATUS_SORT for the most recent eval. */ case DB_STATUS: { int v; const char *zOp; if( objc!=3 ){ Tcl_WrongNumArgs(interp, 2, objv, "(step|sort|autoindex)"); return TCL_ERROR; } zOp = Tcl_GetString(objv[2]); if( strcmp(zOp, "step")==0 ){ v = pDb->nStep; }else if( strcmp(zOp, "sort")==0 ){ v = pDb->nSort; }else if( strcmp(zOp, "autoindex")==0 ){ v = pDb->nIndex; }else{ Tcl_AppendResult(interp, "bad argument: should be autoindex, step, or sort", (char*)0); return TCL_ERROR; } Tcl_SetObjResult(interp, Tcl_NewIntObj(v)); break; } /* ** $db timeout MILLESECONDS ** ** Delay for the number of milliseconds specified when a file is locked. */ case DB_TIMEOUT: { int ms; if( objc!=3 ){ Tcl_WrongNumArgs(interp, 2, objv, "MILLISECONDS"); return TCL_ERROR; } if( Tcl_GetIntFromObj(interp, objv[2], &ms) ) return TCL_ERROR; sqlite3_busy_timeout(pDb->db, ms); break; } /* ** $db total_changes ** ** Return the number of rows that were modified, inserted, or deleted ** since the database handle was created. */ case DB_TOTAL_CHANGES: { Tcl_Obj *pResult; if( objc!=2 ){ Tcl_WrongNumArgs(interp, 2, objv, ""); return TCL_ERROR; } pResult = Tcl_GetObjResult(interp); Tcl_SetIntObj(pResult, sqlite3_total_changes(pDb->db)); break; } /* $db trace ?CALLBACK? ** ** Make arrangements to invoke the CALLBACK routine for each SQL statement ** that is executed. The text of the SQL is appended to CALLBACK before ** it is executed. */ case DB_TRACE: { if( objc>3 ){ Tcl_WrongNumArgs(interp, 2, objv, "?CALLBACK?"); return TCL_ERROR; }else if( objc==2 ){ if( pDb->zTrace ){ Tcl_AppendResult(interp, pDb->zTrace, 0); } }else{ char *zTrace; int len; if( pDb->zTrace ){ Tcl_Free(pDb->zTrace); } zTrace = Tcl_GetStringFromObj(objv[2], &len); if( zTrace && len>0 ){ pDb->zTrace = Tcl_Alloc( len + 1 ); memcpy(pDb->zTrace, zTrace, len+1); }else{ pDb->zTrace = 0; } #if !defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_OMIT_FLOATING_POINT) if( pDb->zTrace ){ pDb->interp = interp; sqlite3_trace(pDb->db, DbTraceHandler, pDb); }else{ sqlite3_trace(pDb->db, 0, 0); } #endif } break; } /* $db transaction [-deferred|-immediate|-exclusive] SCRIPT ** ** Start a new transaction (if we are not already in the midst of a ** transaction) and execute the TCL script SCRIPT. After SCRIPT ** completes, either commit the transaction or roll it back if SCRIPT ** throws an exception. Or if no new transation was started, do nothing. ** pass the exception on up the stack. ** ** This command was inspired by Dave Thomas's talk on Ruby at the ** 2005 O'Reilly Open Source Convention (OSCON). */ case DB_TRANSACTION: { Tcl_Obj *pScript; const char *zBegin = "SAVEPOINT _tcl_transaction"; if( objc!=3 && objc!=4 ){ Tcl_WrongNumArgs(interp, 2, objv, "[TYPE] SCRIPT"); return TCL_ERROR; } if( pDb->nTransaction==0 && objc==4 ){ static const char *TTYPE_strs[] = { "deferred", "exclusive", "immediate", 0 }; enum TTYPE_enum { TTYPE_DEFERRED, TTYPE_EXCLUSIVE, TTYPE_IMMEDIATE }; int ttype; if( Tcl_GetIndexFromObj(interp, objv[2], TTYPE_strs, "transaction type", 0, &ttype) ){ return TCL_ERROR; } switch( (enum TTYPE_enum)ttype ){ case TTYPE_DEFERRED: /* no-op */; break; case TTYPE_EXCLUSIVE: zBegin = "BEGIN EXCLUSIVE"; break; case TTYPE_IMMEDIATE: zBegin = "BEGIN IMMEDIATE"; break; } } pScript = objv[objc-1]; /* Run the SQLite BEGIN command to open a transaction or savepoint. */ pDb->disableAuth++; rc = sqlite3_exec(pDb->db, zBegin, 0, 0, 0); pDb->disableAuth--; if( rc!=SQLITE_OK ){ Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0); return TCL_ERROR; } pDb->nTransaction++; /* If using NRE, schedule a callback to invoke the script pScript, then ** a second callback to commit (or rollback) the transaction or savepoint ** opened above. If not using NRE, evaluate the script directly, then ** call function DbTransPostCmd() to commit (or rollback) the transaction ** or savepoint. */ if( DbUseNre() ){ Tcl_NRAddCallback(interp, DbTransPostCmd, cd, 0, 0, 0); Tcl_NREvalObj(interp, pScript, 0); }else{ rc = DbTransPostCmd(&cd, interp, Tcl_EvalObjEx(interp, pScript, 0)); } break; } /* ** $db unlock_notify ?script? */ case DB_UNLOCK_NOTIFY: { #ifndef SQLITE_ENABLE_UNLOCK_NOTIFY Tcl_AppendResult(interp, "unlock_notify not available in this build", 0); rc = TCL_ERROR; #else if( objc!=2 && objc!=3 ){ Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?"); rc = TCL_ERROR; }else{ void (*xNotify)(void **, int) = 0; void *pNotifyArg = 0; if( pDb->pUnlockNotify ){ Tcl_DecrRefCount(pDb->pUnlockNotify); pDb->pUnlockNotify = 0; } if( objc==3 ){ xNotify = DbUnlockNotify; pNotifyArg = (void *)pDb; pDb->pUnlockNotify = objv[2]; Tcl_IncrRefCount(pDb->pUnlockNotify); } if( sqlite3_unlock_notify(pDb->db, xNotify, pNotifyArg) ){ Tcl_AppendResult(interp, sqlite3_errmsg(pDb->db), 0); rc = TCL_ERROR; } } #endif break; } /* ** $db wal_hook ?script? ** $db update_hook ?script? ** $db rollback_hook ?script? */ case DB_WAL_HOOK: case DB_UPDATE_HOOK: case DB_ROLLBACK_HOOK: { /* set ppHook to point at pUpdateHook or pRollbackHook, depending on ** whether [$db update_hook] or [$db rollback_hook] was invoked. */ Tcl_Obj **ppHook; if( choice==DB_UPDATE_HOOK ){ ppHook = &pDb->pUpdateHook; }else if( choice==DB_WAL_HOOK ){ ppHook = &pDb->pWalHook; }else{ ppHook = &pDb->pRollbackHook; } if( objc!=2 && objc!=3 ){ Tcl_WrongNumArgs(interp, 2, objv, "?SCRIPT?"); return TCL_ERROR; } if( *ppHook ){ Tcl_SetObjResult(interp, *ppHook); if( objc==3 ){ Tcl_DecrRefCount(*ppHook); *ppHook = 0; } } if( objc==3 ){ assert( !(*ppHook) ); if( Tcl_GetCharLength(objv[2])>0 ){ *ppHook = objv[2]; Tcl_IncrRefCount(*ppHook); } } sqlite3_update_hook(pDb->db, (pDb->pUpdateHook?DbUpdateHandler:0), pDb); sqlite3_rollback_hook(pDb->db,(pDb->pRollbackHook?DbRollbackHandler:0),pDb); sqlite3_wal_hook(pDb->db,(pDb->pWalHook?DbWalHandler:0),pDb); break; } /* $db version ** ** Return the version string for this database. */ case DB_VERSION: { Tcl_SetResult(interp, (char *)sqlite3_libversion(), TCL_STATIC); break; } } /* End of the SWITCH statement */ return rc; } #if SQLITE_TCL_NRE /* ** Adaptor that provides an objCmd interface to the NRE-enabled ** interface implementation. */ static int DbObjCmdAdaptor( void *cd, Tcl_Interp *interp, int objc, Tcl_Obj *const*objv ){ return Tcl_NRCallObjProc(interp, DbObjCmd, cd, objc, objv); } #endif /* SQLITE_TCL_NRE */ /* ** sqlite3 DBNAME FILENAME ?-vfs VFSNAME? ?-key KEY? ?-readonly BOOLEAN? ** ?-create BOOLEAN? ?-nomutex BOOLEAN? ** ** This is the main Tcl command. When the "sqlite" Tcl command is ** invoked, this routine runs to process that command. ** ** The first argument, DBNAME, is an arbitrary name for a new ** database connection. This command creates a new command named ** DBNAME that is used to control that connection. The database ** connection is deleted when the DBNAME command is deleted. ** ** The second argument is the name of the database file. ** */ static int DbMain(void *cd, Tcl_Interp *interp, int objc,Tcl_Obj *const*objv){ SqliteDb *p; void *pKey = 0; int nKey = 0; const char *zArg; char *zErrMsg; int i; const char *zFile; const char *zVfs = 0; int flags; Tcl_DString translatedFilename; /* In normal use, each TCL interpreter runs in a single thread. So ** by default, we can turn of mutexing on SQLite database connections. ** However, for testing purposes it is useful to have mutexes turned ** on. So, by default, mutexes default off. But if compiled with ** SQLITE_TCL_DEFAULT_FULLMUTEX then mutexes default on. */ #ifdef SQLITE_TCL_DEFAULT_FULLMUTEX flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX; #else flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX; #endif if( objc==2 ){ zArg = Tcl_GetStringFromObj(objv[1], 0); if( strcmp(zArg,"-version")==0 ){ Tcl_AppendResult(interp,sqlite3_version,0); return TCL_OK; } if( strcmp(zArg,"-has-codec")==0 ){ #ifdef SQLITE_HAS_CODEC Tcl_AppendResult(interp,"1",0); #else Tcl_AppendResult(interp,"0",0); #endif return TCL_OK; } } for(i=3; i+1<objc; i+=2){ zArg = Tcl_GetString(objv[i]); if( strcmp(zArg,"-key")==0 ){ pKey = Tcl_GetByteArrayFromObj(objv[i+1], &nKey); }else if( strcmp(zArg, "-vfs")==0 ){ zVfs = Tcl_GetString(objv[i+1]); }else if( strcmp(zArg, "-readonly")==0 ){ int b; if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR; if( b ){ flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE); flags |= SQLITE_OPEN_READONLY; }else{ flags &= ~SQLITE_OPEN_READONLY; flags |= SQLITE_OPEN_READWRITE; } }else if( strcmp(zArg, "-create")==0 ){ int b; if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR; if( b && (flags & SQLITE_OPEN_READONLY)==0 ){ flags |= SQLITE_OPEN_CREATE; }else{ flags &= ~SQLITE_OPEN_CREATE; } }else if( strcmp(zArg, "-nomutex")==0 ){ int b; if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR; if( b ){ flags |= SQLITE_OPEN_NOMUTEX; flags &= ~SQLITE_OPEN_FULLMUTEX; }else{ flags &= ~SQLITE_OPEN_NOMUTEX; } }else if( strcmp(zArg, "-fullmutex")==0 ){ int b; if( Tcl_GetBooleanFromObj(interp, objv[i+1], &b) ) return TCL_ERROR; if( b ){ flags |= SQLITE_OPEN_FULLMUTEX; flags &= ~SQLITE_OPEN_NOMUTEX; }else{ flags &= ~SQLITE_OPEN_FULLMUTEX; } }else{ Tcl_AppendResult(interp, "unknown option: ", zArg, (char*)0); return TCL_ERROR; } } if( objc<3 || (objc&1)!=1 ){ Tcl_WrongNumArgs(interp, 1, objv, "HANDLE FILENAME ?-vfs VFSNAME? ?-readonly BOOLEAN? ?-create BOOLEAN?" " ?-nomutex BOOLEAN? ?-fullmutex BOOLEAN?" #ifdef SQLITE_HAS_CODEC " ?-key CODECKEY?" #endif ); return TCL_ERROR; } zErrMsg = 0; p = (SqliteDb*)Tcl_Alloc( sizeof(*p) ); if( p==0 ){ Tcl_SetResult(interp, "malloc failed", TCL_STATIC); return TCL_ERROR; } memset(p, 0, sizeof(*p)); zFile = Tcl_GetStringFromObj(objv[2], 0); zFile = Tcl_TranslateFileName(interp, zFile, &translatedFilename); sqlite3_open_v2(zFile, &p->db, flags, zVfs); Tcl_DStringFree(&translatedFilename); if( SQLITE_OK!=sqlite3_errcode(p->db) ){ zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(p->db)); sqlite3_close(p->db); p->db = 0; } #ifdef SQLITE_HAS_CODEC if( p->db ){ sqlite3_key(p->db, pKey, nKey); } #endif if( p->db==0 ){ Tcl_SetResult(interp, zErrMsg, TCL_VOLATILE); Tcl_Free((char*)p); sqlite3_free(zErrMsg); return TCL_ERROR; } p->maxStmt = NUM_PREPARED_STMTS; p->interp = interp; zArg = Tcl_GetStringFromObj(objv[1], 0); if( DbUseNre() ){ Tcl_NRCreateCommand(interp, zArg, DbObjCmdAdaptor, DbObjCmd, (char*)p, DbDeleteCmd); }else{ Tcl_CreateObjCommand(interp, zArg, DbObjCmd, (char*)p, DbDeleteCmd); } return TCL_OK; } /* ** Provide a dummy Tcl_InitStubs if we are using this as a static ** library. */ #ifndef USE_TCL_STUBS # undef Tcl_InitStubs # define Tcl_InitStubs(a,b,c) #endif /* ** Make sure we have a PACKAGE_VERSION macro defined. This will be ** defined automatically by the TEA makefile. But other makefiles ** do not define it. */ #ifndef PACKAGE_VERSION # define PACKAGE_VERSION SQLITE_VERSION #endif /* ** Initialize this module. ** ** This Tcl module contains only a single new Tcl command named "sqlite". ** (Hence there is no namespace. There is no point in using a namespace ** if the extension only supplies one new name!) The "sqlite" command is ** used to open a new SQLite database. See the DbMain() routine above ** for additional information. ** ** The EXTERN macros are required by TCL in order to work on windows. */ EXTERN int Sqlite3_Init(Tcl_Interp *interp){ Tcl_InitStubs(interp, "8.4", 0); Tcl_CreateObjCommand(interp, "sqlite3", (Tcl_ObjCmdProc*)DbMain, 0, 0); Tcl_PkgProvide(interp, "sqlite3", PACKAGE_VERSION); #ifndef SQLITE_3_SUFFIX_ONLY /* The "sqlite" alias is undocumented. It is here only to support ** legacy scripts. All new scripts should use only the "sqlite3" ** command. */ Tcl_CreateObjCommand(interp, "sqlite", (Tcl_ObjCmdProc*)DbMain, 0, 0); #endif return TCL_OK; } EXTERN int Tclsqlite3_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); } EXTERN int Sqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; } EXTERN int Tclsqlite3_SafeInit(Tcl_Interp *interp){ return TCL_OK; } EXTERN int Sqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } EXTERN int Tclsqlite3_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } EXTERN int Sqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; } EXTERN int Tclsqlite3_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;} #ifndef SQLITE_3_SUFFIX_ONLY int Sqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); } int Tclsqlite_Init(Tcl_Interp *interp){ return Sqlite3_Init(interp); } int Sqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; } int Tclsqlite_SafeInit(Tcl_Interp *interp){ return TCL_OK; } int Sqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } int Tclsqlite_Unload(Tcl_Interp *interp, int flags){ return TCL_OK; } int Sqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK; } int Tclsqlite_SafeUnload(Tcl_Interp *interp, int flags){ return TCL_OK;} #endif #ifdef TCLSH /***************************************************************************** ** All of the code that follows is used to build standalone TCL interpreters ** that are statically linked with SQLite. Enable these by compiling ** with -DTCLSH=n where n can be 1 or 2. An n of 1 generates a standard ** tclsh but with SQLite built in. An n of 2 generates the SQLite space ** analysis program. */ #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) /* * This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. */ /* * If compiled on a machine that doesn't have a 32-bit integer, * you just set "uint32" to the appropriate datatype for an * unsigned 32-bit integer. For example: * * cc -Duint32='unsigned long' md5.c * */ #ifndef uint32 # define uint32 unsigned int #endif struct MD5Context { int isInit; uint32 buf[4]; uint32 bits[2]; unsigned char in[64]; }; typedef struct MD5Context MD5Context; /* * Note: this code is harmless on little-endian machines. */ static void byteReverse (unsigned char *buf, unsigned longs){ uint32 t; do { t = (uint32)((unsigned)buf[3]<<8 | buf[2]) << 16 | ((unsigned)buf[1]<<8 | buf[0]); *(uint32 *)buf = t; buf += 4; } while (--longs); } /* The four core functions - F1 is optimized somewhat */ /* #define F1(x, y, z) (x & y | ~x & z) */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ #define MD5STEP(f, w, x, y, z, data, s) \ ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x ) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ static void MD5Transform(uint32 buf[4], const uint32 in[16]){ register uint32 a, b, c, d; a = buf[0]; b = buf[1]; c = buf[2]; d = buf[3]; MD5STEP(F1, a, b, c, d, in[ 0]+0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[ 1]+0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[ 2]+0x242070db, 17); MD5STEP(F1, b, c, d, a, in[ 3]+0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[ 4]+0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[ 5]+0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[ 6]+0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[ 7]+0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[ 8]+0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[ 9]+0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10]+0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11]+0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12]+0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13]+0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14]+0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15]+0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[ 1]+0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[ 6]+0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11]+0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[ 0]+0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[ 5]+0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10]+0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15]+0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[ 4]+0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[ 9]+0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14]+0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[ 3]+0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[ 8]+0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13]+0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[ 2]+0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[ 7]+0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12]+0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[ 5]+0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[ 8]+0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11]+0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14]+0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[ 1]+0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[ 4]+0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[ 7]+0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10]+0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13]+0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[ 0]+0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[ 3]+0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[ 6]+0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[ 9]+0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12]+0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15]+0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[ 2]+0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[ 0]+0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[ 7]+0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14]+0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[ 5]+0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12]+0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[ 3]+0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10]+0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[ 1]+0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[ 8]+0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15]+0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[ 6]+0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13]+0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[ 4]+0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11]+0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[ 2]+0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[ 9]+0xeb86d391, 21); buf[0] += a; buf[1] += b; buf[2] += c; buf[3] += d; } /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ static void MD5Init(MD5Context *ctx){ ctx->isInit = 1; ctx->buf[0] = 0x67452301; ctx->buf[1] = 0xefcdab89; ctx->buf[2] = 0x98badcfe; ctx->buf[3] = 0x10325476; ctx->bits[0] = 0; ctx->bits[1] = 0; } /* * Update context to reflect the concatenation of another buffer full * of bytes. */ static void MD5Update(MD5Context *ctx, const unsigned char *buf, unsigned int len){ uint32 t; /* Update bitcount */ t = ctx->bits[0]; if ((ctx->bits[0] = t + ((uint32)len << 3)) < t) ctx->bits[1]++; /* Carry from low to high */ ctx->bits[1] += len >> 29; t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */ /* Handle any leading odd-sized chunks */ if ( t ) { unsigned char *p = (unsigned char *)ctx->in + t; t = 64-t; if (len < t) { memcpy(p, buf, len); return; } memcpy(p, buf, t); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (uint32 *)ctx->in); buf += t; len -= t; } /* Process data in 64-byte chunks */ while (len >= 64) { memcpy(ctx->in, buf, 64); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (uint32 *)ctx->in); buf += 64; len -= 64; } /* Handle any remaining bytes of data. */ memcpy(ctx->in, buf, len); } /* * Final wrapup - pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ static void MD5Final(unsigned char digest[16], MD5Context *ctx){ unsigned count; unsigned char *p; /* Compute number of bytes mod 64 */ count = (ctx->bits[0] >> 3) & 0x3F; /* Set the first char of padding to 0x80. This is safe since there is always at least one byte free */ p = ctx->in + count; *p++ = 0x80; /* Bytes of padding needed to make 64 bytes */ count = 64 - 1 - count; /* Pad out to 56 mod 64 */ if (count < 8) { /* Two lots of padding: Pad the first block to 64 bytes */ memset(p, 0, count); byteReverse(ctx->in, 16); MD5Transform(ctx->buf, (uint32 *)ctx->in); /* Now fill the next block with 56 bytes */ memset(ctx->in, 0, 56); } else { /* Pad block to 56 bytes */ memset(p, 0, count-8); } byteReverse(ctx->in, 14); /* Append length in bits and transform */ ((uint32 *)ctx->in)[ 14 ] = ctx->bits[0]; ((uint32 *)ctx->in)[ 15 ] = ctx->bits[1]; MD5Transform(ctx->buf, (uint32 *)ctx->in); byteReverse((unsigned char *)ctx->buf, 4); memcpy(digest, ctx->buf, 16); memset(ctx, 0, sizeof(ctx)); /* In case it is sensitive */ } /* ** Convert a 128-bit MD5 digest into a 32-digit base-16 number. */ static void MD5DigestToBase16(unsigned char *digest, char *zBuf){ static char const zEncode[] = "0123456789abcdef"; int i, j; for(j=i=0; i<16; i++){ int a = digest[i]; zBuf[j++] = zEncode[(a>>4)&0xf]; zBuf[j++] = zEncode[a & 0xf]; } zBuf[j] = 0; } /* ** Convert a 128-bit MD5 digest into sequency of eight 5-digit integers ** each representing 16 bits of the digest and separated from each ** other by a "-" character. */ static void MD5DigestToBase10x8(unsigned char digest[16], char zDigest[50]){ int i, j; unsigned int x; for(i=j=0; i<16; i+=2){ x = digest[i]*256 + digest[i+1]; if( i>0 ) zDigest[j++] = '-'; sprintf(&zDigest[j], "%05u", x); j += 5; } zDigest[j] = 0; } /* ** A TCL command for md5. The argument is the text to be hashed. The ** Result is the hash in base64. */ static int md5_cmd(void*cd, Tcl_Interp *interp, int argc, const char **argv){ MD5Context ctx; unsigned char digest[16]; char zBuf[50]; void (*converter)(unsigned char*, char*); if( argc!=2 ){ Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0], " TEXT\"", 0); return TCL_ERROR; } MD5Init(&ctx); MD5Update(&ctx, (unsigned char*)argv[1], (unsigned)strlen(argv[1])); MD5Final(digest, &ctx); converter = (void(*)(unsigned char*,char*))cd; converter(digest, zBuf); Tcl_AppendResult(interp, zBuf, (char*)0); return TCL_OK; } /* ** A TCL command to take the md5 hash of a file. The argument is the ** name of the file. */ static int md5file_cmd(void*cd, Tcl_Interp*interp, int argc, const char **argv){ FILE *in; MD5Context ctx; void (*converter)(unsigned char*, char*); unsigned char digest[16]; char zBuf[10240]; if( argc!=2 ){ Tcl_AppendResult(interp,"wrong # args: should be \"", argv[0], " FILENAME\"", 0); return TCL_ERROR; } in = fopen(argv[1],"rb"); if( in==0 ){ Tcl_AppendResult(interp,"unable to open file \"", argv[1], "\" for reading", 0); return TCL_ERROR; } MD5Init(&ctx); for(;;){ int n; n = fread(zBuf, 1, sizeof(zBuf), in); if( n<=0 ) break; MD5Update(&ctx, (unsigned char*)zBuf, (unsigned)n); } fclose(in); MD5Final(digest, &ctx); converter = (void(*)(unsigned char*,char*))cd; converter(digest, zBuf); Tcl_AppendResult(interp, zBuf, (char*)0); return TCL_OK; } /* ** Register the four new TCL commands for generating MD5 checksums ** with the TCL interpreter. */ int Md5_Init(Tcl_Interp *interp){ Tcl_CreateCommand(interp, "md5", (Tcl_CmdProc*)md5_cmd, MD5DigestToBase16, 0); Tcl_CreateCommand(interp, "md5-10x8", (Tcl_CmdProc*)md5_cmd, MD5DigestToBase10x8, 0); Tcl_CreateCommand(interp, "md5file", (Tcl_CmdProc*)md5file_cmd, MD5DigestToBase16, 0); Tcl_CreateCommand(interp, "md5file-10x8", (Tcl_CmdProc*)md5file_cmd, MD5DigestToBase10x8, 0); return TCL_OK; } #endif /* defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) */ #if defined(SQLITE_TEST) /* ** During testing, the special md5sum() aggregate function is available. ** inside SQLite. The following routines implement that function. */ static void md5step(sqlite3_context *context, int argc, sqlite3_value **argv){ MD5Context *p; int i; if( argc<1 ) return; p = sqlite3_aggregate_context(context, sizeof(*p)); if( p==0 ) return; if( !p->isInit ){ MD5Init(p); } for(i=0; i<argc; i++){ const char *zData = (char*)sqlite3_value_text(argv[i]); if( zData ){ MD5Update(p, (unsigned char*)zData, strlen(zData)); } } } static void md5finalize(sqlite3_context *context){ MD5Context *p; unsigned char digest[16]; char zBuf[33]; p = sqlite3_aggregate_context(context, sizeof(*p)); MD5Final(digest,p); MD5DigestToBase16(digest, zBuf); sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); } int Md5_Register(sqlite3 *db){ int rc = sqlite3_create_function(db, "md5sum", -1, SQLITE_UTF8, 0, 0, md5step, md5finalize); sqlite3_overload_function(db, "md5sum", -1); /* To exercise this API */ return rc; } #endif /* defined(SQLITE_TEST) */ /* ** If the macro TCLSH is one, then put in code this for the ** "main" routine that will initialize Tcl and take input from ** standard input, or if a file is named on the command line ** the TCL interpreter reads and evaluates that file. */ #if TCLSH==1 static char zMainloop[] = "set line {}\n" "while {![eof stdin]} {\n" "if {$line!=\"\"} {\n" "puts -nonewline \"> \"\n" "} else {\n" "puts -nonewline \"% \"\n" "}\n" "flush stdout\n" "append line [gets stdin]\n" "if {[info complete $line]} {\n" "if {[catch {uplevel #0 $line} result]} {\n" "puts stderr \"Error: $result\"\n" "} elseif {$result!=\"\"} {\n" "puts $result\n" "}\n" "set line {}\n" "} else {\n" "append line \\n\n" "}\n" "}\n" ; #endif #if TCLSH==2 static char zMainloop[] = #include "spaceanal_tcl.h" ; #endif #ifdef SQLITE_TEST static void init_all(Tcl_Interp *); static int init_all_cmd( ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ Tcl_Interp *slave; if( objc!=2 ){ Tcl_WrongNumArgs(interp, 1, objv, "SLAVE"); return TCL_ERROR; } slave = Tcl_GetSlave(interp, Tcl_GetString(objv[1])); if( !slave ){ return TCL_ERROR; } init_all(slave); return TCL_OK; } /* ** Tclcmd: db_use_legacy_prepare DB BOOLEAN ** ** The first argument to this command must be a database command created by ** [sqlite3]. If the second argument is true, then the handle is configured ** to use the sqlite3_prepare_v2() function to prepare statements. If it ** is false, sqlite3_prepare(). */ static int db_use_legacy_prepare_cmd( ClientData cd, Tcl_Interp *interp, int objc, Tcl_Obj *CONST objv[] ){ Tcl_CmdInfo cmdInfo; SqliteDb *pDb; int bPrepare; if( objc!=3 ){ Tcl_WrongNumArgs(interp, 1, objv, "DB BOOLEAN"); return TCL_ERROR; } if( !Tcl_GetCommandInfo(interp, Tcl_GetString(objv[1]), &cmdInfo) ){ Tcl_AppendResult(interp, "no such db: ", Tcl_GetString(objv[1]), (char*)0); return TCL_ERROR; } pDb = (SqliteDb*)cmdInfo.objClientData; if( Tcl_GetBooleanFromObj(interp, objv[2], &bPrepare) ){ return TCL_ERROR; } pDb->bLegacyPrepare = bPrepare; Tcl_ResetResult(interp); return TCL_OK; } #endif /* ** Configure the interpreter passed as the first argument to have access ** to the commands and linked variables that make up: ** ** * the [sqlite3] extension itself, ** ** * If SQLITE_TCLMD5 or SQLITE_TEST is defined, the Md5 commands, and ** ** * If SQLITE_TEST is set, the various test interfaces used by the Tcl ** test suite. */ static void init_all(Tcl_Interp *interp){ Sqlite3_Init(interp); #if defined(SQLITE_TEST) || defined(SQLITE_TCLMD5) Md5_Init(interp); #endif #ifdef SQLITE_TEST { extern int Sqliteconfig_Init(Tcl_Interp*); extern int Sqlitetest1_Init(Tcl_Interp*); extern int Sqlitetest2_Init(Tcl_Interp*); extern int Sqlitetest3_Init(Tcl_Interp*); extern int Sqlitetest4_Init(Tcl_Interp*); extern int Sqlitetest5_Init(Tcl_Interp*); extern int Sqlitetest6_Init(Tcl_Interp*); extern int Sqlitetest7_Init(Tcl_Interp*); extern int Sqlitetest8_Init(Tcl_Interp*); extern int Sqlitetest9_Init(Tcl_Interp*); extern int Sqlitetestasync_Init(Tcl_Interp*); extern int Sqlitetest_autoext_Init(Tcl_Interp*); extern int Sqlitetest_demovfs_Init(Tcl_Interp *); extern int Sqlitetest_func_Init(Tcl_Interp*); extern int Sqlitetest_hexio_Init(Tcl_Interp*); extern int Sqlitetest_init_Init(Tcl_Interp*); extern int Sqlitetest_malloc_Init(Tcl_Interp*); extern int Sqlitetest_mutex_Init(Tcl_Interp*); extern int Sqlitetestschema_Init(Tcl_Interp*); extern int Sqlitetestsse_Init(Tcl_Interp*); extern int Sqlitetesttclvar_Init(Tcl_Interp*); extern int SqlitetestThread_Init(Tcl_Interp*); extern int SqlitetestOnefile_Init(); extern int SqlitetestOsinst_Init(Tcl_Interp*); extern int Sqlitetestbackup_Init(Tcl_Interp*); extern int Sqlitetestintarray_Init(Tcl_Interp*); extern int Sqlitetestvfs_Init(Tcl_Interp *); extern int SqlitetestStat_Init(Tcl_Interp*); extern int Sqlitetestrtree_Init(Tcl_Interp*); extern int Sqlitequota_Init(Tcl_Interp*); extern int Sqlitemultiplex_Init(Tcl_Interp*); extern int SqliteSuperlock_Init(Tcl_Interp*); extern int SqlitetestSyscall_Init(Tcl_Interp*); extern int Sqlitetestfuzzer_Init(Tcl_Interp*); extern int Sqlitetestwholenumber_Init(Tcl_Interp*); #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) extern int Sqlitetestfts3_Init(Tcl_Interp *interp); #endif #ifdef SQLITE_ENABLE_ZIPVFS extern int Zipvfs_Init(Tcl_Interp*); Zipvfs_Init(interp); #endif Sqliteconfig_Init(interp); Sqlitetest1_Init(interp); Sqlitetest2_Init(interp); Sqlitetest3_Init(interp); Sqlitetest4_Init(interp); Sqlitetest5_Init(interp); Sqlitetest6_Init(interp); Sqlitetest7_Init(interp); Sqlitetest8_Init(interp); Sqlitetest9_Init(interp); Sqlitetestasync_Init(interp); Sqlitetest_autoext_Init(interp); Sqlitetest_demovfs_Init(interp); Sqlitetest_func_Init(interp); Sqlitetest_hexio_Init(interp); Sqlitetest_init_Init(interp); Sqlitetest_malloc_Init(interp); Sqlitetest_mutex_Init(interp); Sqlitetestschema_Init(interp); Sqlitetesttclvar_Init(interp); SqlitetestThread_Init(interp); SqlitetestOnefile_Init(interp); SqlitetestOsinst_Init(interp); Sqlitetestbackup_Init(interp); Sqlitetestintarray_Init(interp); Sqlitetestvfs_Init(interp); SqlitetestStat_Init(interp); Sqlitetestrtree_Init(interp); Sqlitequota_Init(interp); Sqlitemultiplex_Init(interp); SqliteSuperlock_Init(interp); SqlitetestSyscall_Init(interp); Sqlitetestfuzzer_Init(interp); Sqlitetestwholenumber_Init(interp); #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) Sqlitetestfts3_Init(interp); #endif Tcl_CreateObjCommand( interp, "load_testfixture_extensions", init_all_cmd, 0, 0 ); Tcl_CreateObjCommand( interp, "db_use_legacy_prepare", db_use_legacy_prepare_cmd, 0, 0 ); #ifdef SQLITE_SSE Sqlitetestsse_Init(interp); #endif } #endif } #define TCLSH_MAIN main /* Needed to fake out mktclapp */ int TCLSH_MAIN(int argc, char **argv){ Tcl_Interp *interp; /* Call sqlite3_shutdown() once before doing anything else. This is to ** test that sqlite3_shutdown() can be safely called by a process before ** sqlite3_initialize() is. */ sqlite3_shutdown(); #if TCLSH==2 sqlite3_config(SQLITE_CONFIG_SINGLETHREAD); #endif Tcl_FindExecutable(argv[0]); interp = Tcl_CreateInterp(); init_all(interp); if( argc>=2 ){ int i; char zArgc[32]; sqlite3_snprintf(sizeof(zArgc), zArgc, "%d", argc-(3-TCLSH)); Tcl_SetVar(interp,"argc", zArgc, TCL_GLOBAL_ONLY); Tcl_SetVar(interp,"argv0",argv[1],TCL_GLOBAL_ONLY); Tcl_SetVar(interp,"argv", "", TCL_GLOBAL_ONLY); for(i=3-TCLSH; i<argc; i++){ Tcl_SetVar(interp, "argv", argv[i], TCL_GLOBAL_ONLY | TCL_LIST_ELEMENT | TCL_APPEND_VALUE); } if( TCLSH==1 && Tcl_EvalFile(interp, argv[1])!=TCL_OK ){ const char *zInfo = Tcl_GetVar(interp, "errorInfo", TCL_GLOBAL_ONLY); if( zInfo==0 ) zInfo = Tcl_GetStringResult(interp); fprintf(stderr,"%s: %s\n", *argv, zInfo); return 1; } } if( TCLSH==2 || argc<=1 ){ Tcl_GlobalEval(interp, zMainloop); } return 0; } #endif /* TCLSH */
birdsarah/appjs-browserhistory
node_modules/sqlite3/deps/sqlite3/tea/generic/tclsqlite3.c
C
mit
118,397
/* Copyright (c) 2009 Google Inc. * * 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.google.appengine.demos.mediastore; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.jdo.annotations.IdGeneratorStrategy; import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.PersistenceCapable; import javax.jdo.annotations.Persistent; import javax.jdo.annotations.PrimaryKey; import com.google.appengine.api.blobstore.BlobKey; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.users.User; @PersistenceCapable(identityType = IdentityType.APPLICATION) public class MediaObject { @PrimaryKey @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY) private Key key; @Persistent private User owner; @Persistent private BlobKey blob; @Persistent private Date creation; @Persistent private String contentType; @Persistent private String filename; @Persistent private long size; @Persistent private String title; @Persistent private String description; @Persistent private boolean isPublic; private static final List<String> IMAGE_TYPES = Arrays.asList("image/png", "image/jpeg", "image/tiff", "image/gif", "image/bmp"); public MediaObject(User owner, BlobKey blob, Date creationTime, String contentType, String filename, long size, String title, String description, boolean isPublic) { this.blob = blob; this.owner = owner; this.creation = creationTime; this.contentType = contentType; this.filename = filename; this.size = size; this.title = title; this.description = description; this.isPublic = isPublic; } public Key getKey() { return key; } public User getOwner() { return owner; } public Date getCreationTime() { return creation; } public boolean isPublic() { return isPublic; } public String getDescription() { return description; } public String getTitle() { return title; } public String getFilename() { return filename; } public long getSize() { return size; } public String getContentType() { if (contentType == null) { return "text/plain"; } return contentType; } public String getURLPath() { String key = blob.getKeyString(); return "/resource?key=" + key; } public String getDisplayURL() { String key = blob.getKeyString(); return "/display?key=" + key; } public boolean isImage() { return IMAGE_TYPES.contains(getContentType()); } }
dougkoellmer/swarm
tools/appengine-java-sdk/demos/mediastore/src/com/google/appengine/demos/mediastore/MediaObject.java
Java
mit
3,081
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>basic_raw_socket::async_receive (1 of 2 overloads)</title> <link rel="stylesheet" href="../../../../boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.75.2"> <link rel="home" href="../../../../index.html" title="Asio"> <link rel="up" href="../async_receive.html" title="basic_raw_socket::async_receive"> <link rel="prev" href="../async_receive.html" title="basic_raw_socket::async_receive"> <link rel="next" href="overload2.html" title="basic_raw_socket::async_receive (2 of 2 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../../asio.png"></td></tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../async_receive.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../async_receive.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="asio.reference.basic_raw_socket.async_receive.overload1"></a><a class="link" href="overload1.html" title="basic_raw_socket::async_receive (1 of 2 overloads)">basic_raw_socket::async_receive (1 of 2 overloads)</a> </h5></div></div></div> <p> Start an asynchronous receive on a connected socket. </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="../../MutableBufferSequence.html" title="Mutable buffer sequence requirements">MutableBufferSequence</a><span class="special">,</span> <span class="keyword">typename</span> <a class="link" href="../../ReadHandler.html" title="Read handler requirements">ReadHandler</a><span class="special">&gt;</span> <a class="link" href="../../asynchronous_operations.html#asio.reference.asynchronous_operations.return_type_of_an_initiating_function"><span class="emphasis"><em>void-or-deduced</em></span></a> <span class="identifier">async_receive</span><span class="special">(</span> <span class="keyword">const</span> <span class="identifier">MutableBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">,</span> <span class="identifier">ReadHandler</span> <span class="identifier">handler</span><span class="special">);</span> </pre> <p> This function is used to asynchronously receive data from the raw socket. The function call always returns immediately. </p> <h6> <a name="asio.reference.basic_raw_socket.async_receive.overload1.h0"></a> <span><a name="asio.reference.basic_raw_socket.async_receive.overload1.parameters"></a></span><a class="link" href="overload1.html#asio.reference.basic_raw_socket.async_receive.overload1.parameters">Parameters</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl> <dt><span class="term">buffers</span></dt> <dd><p> One or more buffers into which the data will be received. Although the buffers object may be copied as necessary, ownership of the underlying memory blocks is retained by the caller, which must guarantee that they remain valid until the handler is called. </p></dd> <dt><span class="term">handler</span></dt> <dd> <p> The handler to be called when the receive operation completes. Copies will be made of the handler as required. The function signature of the handler must be: </p> <pre class="programlisting"><span class="keyword">void</span> <span class="identifier">handler</span><span class="special">(</span> <span class="keyword">const</span> <span class="identifier">asio</span><span class="special">::</span><span class="identifier">error_code</span><span class="special">&amp;</span> <span class="identifier">error</span><span class="special">,</span> <span class="comment">// Result of operation.</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">bytes_transferred</span> <span class="comment">// Number of bytes received.</span> <span class="special">);</span> </pre> <p> Regardless of whether the asynchronous operation completes immediately or not, the handler will not be invoked from within this function. Invocation of the handler will be performed in a manner equivalent to using <code class="computeroutput"><span class="identifier">asio</span><span class="special">::</span><span class="identifier">io_service</span><span class="special">::</span><span class="identifier">post</span><span class="special">()</span></code>. </p> </dd> </dl> </div> <h6> <a name="asio.reference.basic_raw_socket.async_receive.overload1.h1"></a> <span><a name="asio.reference.basic_raw_socket.async_receive.overload1.remarks"></a></span><a class="link" href="overload1.html#asio.reference.basic_raw_socket.async_receive.overload1.remarks">Remarks</a> </h6> <p> The async_receive operation can only be used with a connected socket. Use the async_receive_from function to receive data on an unconnected raw socket. </p> <h6> <a name="asio.reference.basic_raw_socket.async_receive.overload1.h2"></a> <span><a name="asio.reference.basic_raw_socket.async_receive.overload1.example"></a></span><a class="link" href="overload1.html#asio.reference.basic_raw_socket.async_receive.overload1.example">Example</a> </h6> <p> To receive into a single data buffer use the <a class="link" href="../../buffer.html" title="buffer"><code class="computeroutput"><span class="identifier">buffer</span></code></a> function as follows: </p> <pre class="programlisting"><span class="identifier">socket</span><span class="special">.</span><span class="identifier">async_receive</span><span class="special">(</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">buffer</span><span class="special">(</span><span class="identifier">data</span><span class="special">,</span> <span class="identifier">size</span><span class="special">),</span> <span class="identifier">handler</span><span class="special">);</span> </pre> <p> See the <a class="link" href="../../buffer.html" title="buffer"><code class="computeroutput"><span class="identifier">buffer</span></code></a> documentation for information on receiving into multiple buffers in one go, and how to use it with arrays, boost::array or std::vector. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2015 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../async_receive.html"><img src="../../../../prev.png" alt="Prev"></a><a accesskey="u" href="../async_receive.html"><img src="../../../../up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../next.png" alt="Next"></a> </div> </body> </html>
otgaard/zap
third_party/asio/doc/asio/reference/basic_raw_socket/async_receive/overload1.html
HTML
mit
8,064
from django.test import TestCase from mock import patch import six import silk from silk.profiling.dynamic import _get_module, _get_parent_module, profile_function_or_method from .util import mock_data_collector class TestGetModule(TestCase): """test for _get_module""" def test_singular(self): module = _get_module('silk') self.assertEqual(module.__class__.__name__, 'module') self.assertEqual('silk', module.__name__) self.assertTrue(hasattr(module, 'models')) def test_dot(self): module = _get_module('silk.models') self.assertEqual(module.__class__.__name__, 'module') self.assertEqual('silk.models', module.__name__) self.assertTrue(hasattr(module, 'SQLQuery')) class TestGetParentModule(TestCase): """test for silk.tools._get_parent_module""" def test_singular(self): parent = _get_parent_module(silk) self.assertIsInstance(parent, dict) def test_dot(self): import silk.utils parent = _get_parent_module(silk.utils) self.assertEqual(parent, silk) class MyClass(object): def foo(self): pass def foo(): pass def source_file_name(): file_name = __file__ if file_name[-1] == 'c': file_name = file_name[:-1] return file_name class TestProfileFunction(TestCase): def test_method_as_str(self): # noinspection PyShadowingNames def foo(_): pass # noinspection PyUnresolvedReferences with patch.object(MyClass, 'foo', foo): profile_function_or_method('tests.test_dynamic_profiling', 'MyClass.foo', 'test') dc = mock_data_collector() with patch('silk.profiling.profiler.DataCollector', return_value=dc) as mock_DataCollector: MyClass().foo() self.assertEqual(mock_DataCollector.return_value.register_profile.call_count, 1) call_args = mock_DataCollector.return_value.register_profile.call_args[0][0] self.assertDictContainsSubset({ 'func_name': foo.__name__, 'dynamic': True, 'file_path': source_file_name(), 'name': 'test', 'line_num': six.get_function_code(foo).co_firstlineno }, call_args) def test_func_as_str(self): name = foo.__name__ line_num = six.get_function_code(foo).co_firstlineno profile_function_or_method('tests.test_dynamic_profiling', 'foo', 'test') dc = mock_data_collector() with patch('silk.profiling.profiler.DataCollector', return_value=dc) as mock_DataCollector: foo() self.assertEqual(mock_DataCollector.return_value.register_profile.call_count, 1) call_args = mock_DataCollector.return_value.register_profile.call_args[0][0] self.assertDictContainsSubset({ 'func_name': name, 'dynamic': True, 'file_path': source_file_name(), 'name': 'test', 'line_num': line_num }, call_args)
ruhan/django-silk-mongoengine
project/tests/test_dynamic_profiling.py
Python
mit
3,131
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Minim : : Reciprocal : : patch</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <link href="stylesheet.css" rel="stylesheet" type="text/css"> </head> <body> <center> <table class="mainTable"> <tr> <td class="header"> <span class="indexheader">Minim</span><br/> <span class="indexnavigation"> <a href="index.html">core</a> | <a href="index_ugens.html">ugens</a> | <a href="index_analysis.html">analysis</a> </span> </td> <td class="border-left">&nbsp;</td> </tr> <tr> <td class="classNavigation"> <p class="mainTextName"><A href="ugen_class_ugen.html">UGen</A></p> <p class="methodName">patch</p> </td> <td class="mainText border-left"> <p class="memberSectionHeader">Description</p> Send the output of this UGen to another UGen, UGenInput, or AudioOutput. For instance, if an Oscil is patched to an AudioOutput, you will hear the sound it generates. If a FilePlayer is patched to a Delay, then the delay effect will be applied to the sound generated by the FilePlayer. <p class="memberSectionHeader">Signature</p> <pre>UGen patch(UGen connectToUGen) UGen patch(UGen.UGenInput connectToInput) void patch(AudioOutput audioOutput) </pre> <p class="memberSectionHeader">Parameters</p> <span class="parameterName">connectToUGen</span>&nbsp;&mdash;&nbsp;<span class="parameterDescription">The UGen to patch to.</span><br/> <span class="parameterName">connectToInput</span>&nbsp;&mdash;&nbsp;<span class="parameterDescription">The UGenInput to patch to.</span><br/> <span class="parameterName">audioOutput</span>&nbsp;&mdash;&nbsp;<span class="parameterDescription">The AudioOutput you want to connect this UGen to.</span><br/> <p class="memberSectionHeader">Returns</p> <p>When patching to a UGen or UGenInput, the UGen being patched to is returned so that you can chain patch calls. For example: <pre> sine.patch( gain ).patch( out ); </pre></p> <p class="memberSectionHeader">Related</p> <p class="memberSectionHeader">Example</p> <pre>/** * This sketch demonstrates how to create a simple synthesis chain that * involves controlling the value of a UGenInput with the output of * a UGen. In this case, we patch an Oscil generating a sine wave into * the amplitude input of an Oscil generating a square wave. The result * is known as amplitude modulation. * &lt;p> * For more information about Minim and additional features, * visit http://code.compartmental.net/minim/ */ import ddf.minim.*; import ddf.minim.ugens.*; Minim minim; AudioOutput out; Oscil wave; Oscil mod; void setup() { size(512, 200, P3D); minim = new Minim(this); // use the getLineOut method of the Minim object to get an AudioOutput object out = minim.getLineOut(); // create a triangle wave Oscil, set to 440 Hz, at 1.0 amplitude // in this case, the amplitude we construct the Oscil with // doesn't matter because we will be patching something to // its amplitude input. wave = new Oscil( 440, 1.0f, Waves.TRIANGLE ); // create a sine wave Oscil for modulating the amplitude of wave mod = new Oscil( 2, 0.4f, Waves.SINE ); // connect up the modulator mod.patch( wave.amplitude ); // patch wave to the output wave.patch( out ); } void draw() { background(0); stroke(255); // draw the waveforms for(int i = 0; i &lt; out.bufferSize() - 1; i++) { line( i, 50 + out.left.get(i)*50, i+1, 50 + out.left.get(i+1)*50 ); line( i, 150 + out.right.get(i)*50, i+1, 150 + out.right.get(i+1)*50 ); } } </pre> <p class="memberSectionHeader">Usage</p> Web & Application </td> </tr> </table> </center> </body> </html>
dibarbet/MusicComposer
libraries/minim/documentation/reciprocal_method_patch.html
HTML
mit
3,992
import ElCheckbox from './src/checkbox'; /* istanbul ignore next */ ElCheckbox.install = function(Vue) { Vue.component(ElCheckbox.name, ElCheckbox); }; export default ElCheckbox;
furybean/element
packages/checkbox/index.js
JavaScript
mit
184
// (C) Copyright Gennadiy Rozental 2005-2007. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision: 41369 $ // // Description : Facilities to perform interaction-based testing // *************************************************************************** #ifndef BOOST_TEST_INTERACTION_BASED_HPP_112105GER #define BOOST_TEST_INTERACTION_BASED_HPP_112105GER // Boost.Test #include <boost/test/detail/config.hpp> #include <boost/test/detail/global_typedef.hpp> #include <boost/test/utils/wrap_stringstream.hpp> #include <boost/test/detail/suppress_warnings.hpp> // Boost #include <boost/lexical_cast.hpp> //____________________________________________________________________________// // ************************************************************************** // // ************** BOOST_ITEST_EPOINT ************** // // ************************************************************************** // #define BOOST_ITEST_EPOINT( description ) \ ::boost::itest::manager::instance().exception_point( BOOST_TEST_L(__FILE__), __LINE__, description ) /**/ // ************************************************************************** // // ************** BOOST_ITEST_DPOINT ************** // // ************************************************************************** // #define BOOST_ITEST_DPOINT() \ ::boost::itest::manager::instance().decision_point( BOOST_TEST_L(__FILE__), __LINE__ ) /**/ // ************************************************************************** // // ************** BOOST_ITEST_SCOPE ************** // // ************************************************************************** // #define BOOST_ITEST_SCOPE( scope_name ) \ ::boost::itest::scope_guard itest_scope_guard ## __LINE__( BOOST_TEST_L(__FILE__), __LINE__, BOOST_STRINGIZE(scope_name) ) /**/ // ************************************************************************** // // ************** BOOST_ITEST_NEW ************** // // ************************************************************************** // #define BOOST_ITEST_NEW( type_name ) \ new ( ::boost::itest::location( BOOST_TEST_L(__FILE__), __LINE__ ) ) type_name /**/ // ************************************************************************** // // ************** BOOST_ITEST_DATA_FLOW ************** // // ************************************************************************** // #define BOOST_ITEST_DATA_FLOW( v ) \ ::boost::itest::manager::instance().generic_data_flow( v ) /**/ // ************************************************************************** // // ************** BOOST_ITEST_RETURN ************** // // ************************************************************************** // #define BOOST_ITEST_RETURN( type, default_value ) \ ::boost::itest::manager::instance().generic_return<type>( default_value ) /**/ // ************************************************************************** // // ************** BOOST_ITEST_MOCK_FUNC ************** // // ************************************************************************** // #define BOOST_ITEST_MOCK_FUNC( function_name ) \ BOOST_ITEST_SCOPE( function_name ); \ BOOST_ITEST_EPOINT( 0 ); \ return ::boost::itest::mock_object<>::prototype(); \ /**/ namespace boost { namespace itest { // interaction-based testing using unit_test::const_string; // ************************************************************************** // // ************** manager ************** // // ************************************************************************** // class BOOST_TEST_DECL manager { public: // instance access static manager& instance() { return *instance_ptr(); } // Mock objects interface hooks virtual void exception_point( const_string /*file*/, std::size_t /*line_num*/, const_string /*descr*/ ){} virtual bool decision_point( const_string /*file*/, std::size_t /*line_num*/ ) { return true; } virtual unsigned enter_scope( const_string /*file*/, std::size_t /*line_num*/, const_string /*scope_name*/){ return 0; } virtual void leave_scope( unsigned ) {} virtual void allocated( const_string /*file*/, std::size_t /*line_num*/, void* /*p*/, std::size_t /*s*/ ) {} virtual void freed( void* /*p*/ ) {} virtual void data_flow( const_string /*d*/ ) {} virtual std::string return_value( const_string /*default_value */ ) { return ""; } template<typename T> void generic_data_flow( T const& t ) { wrap_stringstream ws; data_flow( (ws << t).str() ); } template<typename T, typename DefaultValueType> T generic_return( DefaultValueType const& dv ) { wrap_stringstream ws; std::string const& res = return_value( (ws << dv).str() ); if( res.empty() ) return dv; return lexical_cast<T>( res ); } protected: manager(); #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564)) public: #endif BOOST_TEST_PROTECTED_VIRTUAL ~manager(); private: struct dummy_constr{}; explicit manager( dummy_constr* ) {} static manager* instance_ptr( bool reset = false, manager* ptr = 0 ); }; // manager // ************************************************************************** // // ************** scope_guard ************** // // ************************************************************************** // class scope_guard { public: // Constructor scope_guard( const_string file, std::size_t line_num, const_string scope_name ) { m_scope_index = manager::instance().enter_scope( file, line_num, scope_name ); } ~scope_guard() { manager::instance().leave_scope( m_scope_index ); } unsigned m_scope_index; }; // ************************************************************************** // // ************** location ************** // // ************************************************************************** // struct location { location( const_string file, std::size_t line ) : m_file_name( file ) , m_line_num( line ) {} const_string m_file_name; std::size_t m_line_num; }; } // namespace itest } // namespace boost // ************************************************************************** // // ************** operator new overload ************** // // ************************************************************************** // #if !defined(BOOST_ITEST_NO_NEW_OVERLOADS) // STL #include <cstdlib> # ifdef BOOST_NO_STDC_NAMESPACE namespace std { using ::malloc; using ::free; } # endif inline void* operator new( std::size_t s, ::boost::itest::location const& l ) { void* res = std::malloc(s ? s : 1); if( res ) ::boost::itest::manager::instance().allocated( l.m_file_name, l.m_line_num, res, s ); else throw std::bad_alloc(); return res; } //____________________________________________________________________________// inline void* operator new[]( std::size_t s, ::boost::itest::location const& l ) { void* res = std::malloc(s ? s : 1); if( res ) ::boost::itest::manager::instance().allocated( l.m_file_name, l.m_line_num, res, s ); else throw std::bad_alloc(); return res; } //____________________________________________________________________________// inline void operator delete( void* p, ::boost::itest::location const& ) { ::boost::itest::manager::instance().freed( p ); std::free( p ); } //____________________________________________________________________________// inline void operator delete[]( void* p, ::boost::itest::location const& ) { ::boost::itest::manager::instance().freed( p ); std::free( p ); } //____________________________________________________________________________// #endif #include <boost/test/detail/enable_warnings.hpp> #endif // BOOST_TEST_INTERACTION_BASED_HPP_112105GER
Ezeer/VegaStrike_win32FR
vegastrike/boost/1_35/boost/test/interaction_based.hpp
C++
mit
8,928
/*global Backbone, _, console */ "use strict"; // The TableView is a BaseView that's self explanatory. // It has subViews which represent rows in the table, as // well as a heading row view singleton. var TableView = Backbone.BaseView.extend({ tagName: 'table', template: _.template('<thead></thead><tbody></tbody>'), subViewConfig: { row : { construct: 'RowView', location: 'tbody' // Rows are appended to tbody selector within the table }, headingRow: { construct: 'HeadingRowView', location: 'thead', singleton: true // We only need one heading row, so we make it a singleton } }, initialize: function () { this.subs.add('headingRow', { cols: ['First Name', 'Last Name', 'Actions'] }); // Add a row sub-view for each model in the collection this.collection.each(function (rowModel) { this.subs.add('row', { model: rowModel }); }, this); }, render: function () { this.$el.html(this.template()); // Render all subviews and append them to their locations // clear the locations of any existing elems before appending this.subs.renderAppend({ clearLocations: true }); return this; }, // viewEvents are setup in the BaseView and work like the standard 'events' object // but for backbone events. So for example, the key 'change model' would listen // to the change event on the model property of the view. The context would be the view viewEvents: { 'submit' : function (arg) { console.log('User clicked submit on a row cell. ' + 'The event bubbled up to the table view with this message: ' + arg); } } }); var HeadingRowView = Backbone.BaseView.extend({ tagName: 'tr', subViewConfig: { headingCol: { construct: 'HeadingCellView' } }, initialize: function (options) { this.cols = options.cols; _.each(this.cols, function (colLabel) { this.subs.add('headingCol', { label: colLabel }); }, this); }, render: function () { this.$el.empty(); // Render the sub-views and append them directly to // this.$el this.subs.renderAppend(this.$el); return this; } }); var HeadingCellView = Backbone.BaseView.extend({ tagName: 'th', initialize: function (options) { this.label = options.label; }, render: function () { this.$el.html(this.label); return this; } }); var RowView = Backbone.BaseView.extend({ tagName: 'tr', subViewConfig: { firstName : { construct: 'CellView', singleton: true, options: { modelField: 'firstName' } }, lastName : { construct : 'CellView', singleton: true, options: { modelField: 'lastName' } }, actions : { construct: 'ActionsView', singleton: true } }, initialize: function () { var opts = { model : this.model }; this.subs.add({ firstName : opts, lastName: opts, actions : opts }); }, render: function () { this.subs.renderAppend(this.$el); return this; } }); var CellView = Backbone.BaseView.extend({ tagName: 'td', initialize: function (options) { this.modelField = options.modelField; }, render: function () { this.$el.html(this.model.get(this.modelField)); return this; } }); var ActionsView = Backbone.BaseView.extend({ tagName: 'td', template: _.template('<button class="btn submit">Submit</button>'), render: function () { this.$el.html(this.template()); return this; }, events: { 'click .submit' : function () { this.triggerBubble('submit', ['Hello, this person\'s name is ' + this.model.get('firstName') + ' ' + this.model.get('lastName')]); } } });
antialias/backbone-base-and-form-view
examples/example-table.js
JavaScript
mit
4,177
<form class='navbar-form navbar-right' action='/user/login' method='post' enctype="multipart/form-data"> <div class='form-group'> <input name='username' type='text' class='form-control' placeholder='Username'> <input name='password' type='password' class='form-control' placeholder='Password'> <span class="btn btn-default btn-file"> Upload <input type="file" name="avatar"> </span> </div> <button type='submit' class='btn btn-success'>GO!</button> </form>
khoanguyen96/stock-ticker
application/views/templates/_login_control.php
PHP
mit
516
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Security\Core\Exception; /** * TokenNotFoundException is thrown if a Token cannot be found. * * @author Johannes M. Schmitt <[email protected]> * @author Alexander <[email protected]> */ class TokenNotFoundException extends AuthenticationException { /** * {@inheritdoc} */ public function getMessageKey() { return 'No token could be found.'; } }
Francky69/kilatrou
vendor/symfony/symfony/src/Symfony/Component/Security/Core/Exception/TokenNotFoundException.php
PHP
mit
686
$(function() { $(document).on('submit', '#create-permission-form', function() { var sArray = $(this).serializeArray(); $.ajax({ "type": "POST", "url": window.location.href.toString(), "data": sArray, "dataType": "json" }).done(function(result) { if(result.permissionCreated === false) { if(typeof result.message !== 'undefined') { showStatusMessage(result.message, result.messageType); } else if(typeof result.errorMessages !== 'undefined') { showRegisterFormAjaxErrors(result.errorMessages); } } else { window.location = result.redirectUrl; } }); return false; }).on('submit', '#edit-permission-form', function() { var sArray = $(this).serializeArray(); $.ajax({ "type": "PUT", "url": window.location.href.toString(), "data": sArray, "dataType": "json" }).done(function(result) { if(typeof result.message !== 'undefined') { showStatusMessage(result.message, result.messageType); } else if(typeof result.errorMessages !== 'undefined') { showRegisterFormAjaxErrors(result.errorMessages); } }); return false; }).on('click', '#delete-item', function() { $('#confirm-modal').modal(); }).on('click', '.delete-permission .confirm-action', function() { $.each($('.table tbody tr td input:checkbox:checked'), function( key, value ) { $.ajax( { "url": window.location.href.toString()+"/../permission/"+$(this).data('permission-id'), "type": "DELETE" }).done(function(result) { showStatusMessage(result.message, result.messageType); ajaxContent($(this).attr('href'), ".ajax-content", false); }); }); $('#confirm-modal').modal('hide'); }) });
PavelPolyakov/laravel-demo
vendor/mrjuliuss/syntara/public/assets/js/dashboard/permission.js
JavaScript
mit
2,256
--- name: Smart & Final address_1: 5700 E Olympic Blvd address_2: '' city: Los Angeles state: CA zip: '90022' phone: (323) 888-4204 latitude: '34.013946' longitude: '-118.14825' category: Supermarket website: 'http://www.smartandfinal.com/' active: '' daycode1: Mon day1_open: '700' day1_close: '2100' daycode2: Tue day2_open: '700' day2_close: '2100' daycode3: Wed day3_open: '700' day3_close: '2100' daycode4: Thu day4_open: '700' day4_close: '2100' daycode5: Fri day5_open: '700' day5_close: '2100' daycode6: Sat day6_open: '700' day6_close: '2100' daycode7: Sun day7_open: '700' day7_close: '2100' title: 'Smart & Final, Food Oasis Los Angeles' uri: /supermarket/smart-final-5700-e-olympic-blvd/ formatted_daycode1: Monday formatted_day1_open: 7am formatted_day1_close: 9pm formatted_daycode2: Tuesday formatted_day2_open: 7am formatted_day2_close: 9pm formatted_daycode3: Wednesday formatted_day3_open: 7am formatted_day3_close: 9pm formatted_daycode4: Thursday formatted_day4_open: 7am formatted_day4_close: 9pm formatted_daycode5: Friday formatted_day5_open: 7am formatted_day5_close: 9pm formatted_daycode6: Saturday formatted_day6_open: 7am formatted_day6_close: 9pm formatted_daycode7: Sunday formatted_day7_open: 7am formatted_day7_close: 9pm ---
kathwang21/site
_supermarket/smart-final-5700-e-olympic-blvd.md
Markdown
mit
1,261
--- title: TestedSetups 2014 01 authors: amuller, bcrochet, cgirda, dron, edu, flaper87, gfidente, ihrachys, jary, jlibosva, jruzicka, krwhitney, mangelajo, marun, mbourvin, mpavlase, mrhodes, ndipanov, nmagnezi, oblaut, ohochman, panda, pixelbeat, rbowen, rlandy, thaha, vaneldik, whayutin, yrabl, zaitcev wiki_title: TestedSetups 2014 01 wiki_revision_count: 132 wiki_last_updated: 2014-02-21 --- # TestedSetups 2014 01 Tested Setups for [RDO_test_day_January_2014](RDO_test_day_January_2014). Tests should be executed against the Icehouse RDO **not** Havana, some steps from the official Quickstart guide **do not** apply to Icehouse; make sure to follow the steps described in the [RDO_test_day_January_2014#How_To_Test](RDO_test_day_January_2014#How_To_Test) page instead. ## Example Entry Here's how you might fill out an entry once you've tested it. Mark a given test "Good" or "Fail", as appropriate, and link to any tickets that you've opened as a result, and to any place where you've written up your test notes. Mark as Workaround if you have a failure but can get past it. Link to your writeup of the workaround. | Config Name | Release | BaseOS | Status | HOWTO | Who | Date | BZ/LP | Notes Page | |----------------------------------------------------------------|------------------|-----------|----------------------------------------------|-----------------------------------------------------|--------|------------|--------------------------------------------------------------------|------------| | All-in-One w/ Quantum OVS (no tunnels, fake bridge) Networking | Grizzly 2013.1.3 | RHEL 6.4 | <span style="background:#00ff00">Good</span> | [Neutron-Quickstart](Neutron-Quickstart) | pmyers | 2013-09-08 | None | None | | | | Fedora 19 | <span style="background:#ff0000">FAIL</span> | [Neutron-Quickstart](Neutron-Quickstart) | rbowen | 2013-10-09 | ~~[1017421](https://bugzilla.redhat.com/show_bug.cgi?id=1017421)~~ | None | ## Packstack Based Installation (Neutron Networking) Please make sure to use the steps described in the RDO_test_day_January_2014#How_To_Test page when installing the base RDO system. Do not go trough the Quickstart steps unmodified which will instead give you an RDO Havana deployment. | Config Name | Release | BaseOS | Status | HOWTO | Who | Date | BZ/LP | Notes Page | |-----------------------------------------------------------------------|---------|------------|----------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------|-------------------|---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------| | All-in-One | | RHEL 6.5 | <span style="background:#00ff00">Good</span> (With Bugs) | | nmagnezi/ukalifon | 01/07-08/2014 | [1047156](https://bugzilla.redhat.com/show_bug.cgi?id=1047156) [1049235](https://bugzilla.redhat.com/show_bug.cgi?id=1049235) [1049537](https://bugzilla.redhat.com/show_bug.cgi?id=1049537) [1049915](https://bugzilla.redhat.com/show_bug.cgi?id=1049915) [1049982](https://bugzilla.redhat.com/show_bug.cgi?id=1049982) | None | | | | RHEL 6.5 | <span style="background:#00ff00">Good</span> | | jruzicka | 01/07/2014 | None | None | | | | CentOS 6.5 | <span style="background:#ff0000">FAIL</span> | | thaha | 2014-01-07 | |[1028690](https://bugzilla.redhat.com/show_bug.cgi?id=1028690) | | [Jenkins Log](https://prod-rdojenkins.rhcloud.com/job/packstack-rdo-icehouse-neutron-centos-production/lastBuild/) | | | | Fedora 20 | <span style="background:#ff0000">FAIL</span> | | thaha | 2014-01-07 | | [1049114](https://bugzilla.redhat.com/show_bug.cgi?id=1049114) [981116](https://bugzilla.redhat.com/show_bug.cgi?id=981116) [1028690](https://bugzilla.redhat.com/show_bug.cgi?id=1028690) | | [Jenkins log](https://prod-rdojenkins.rhcloud.com/job/packstack-rdo-icehouse-multinode-neutron-f20-production/lastBuild/) | | | | Fedora 20 | <span style="background:#ff0000">FAIL</span> | | zaitcev | 2014-01-07 | | | instance launches but no ping? | | | | Fedora 20 | <span style="background:#ff0000">FAIL</span> | | ndipanov | 2014-01-08 | |[1049922](https://bugzilla.redhat.com/show_bug.cgi?id=1049922) | | iscsiadm-initiator-utils bug - can't boot instance from volume | | | | RHEL 6.5 | <span style="background:#00ff00">Good</span> | | mrhodes | 01/08/2014 | None | [Workaround for rubygems package dependency](https://etherpad.openstack.org/p/rdo_test_day_jan_2014) | | Distributed w/ Neutron OVS (no tunnels, real provider net) Networking | | RHEL 6.5 | <span style="background:#00ff00">Good</span> (With Bugs) | | nmagnezi | 01/07-08/2014 | [1047156](https://bugzilla.redhat.com/show_bug.cgi?id=1047156) [1049235](https://bugzilla.redhat.com/show_bug.cgi?id=1049235) [1049537](https://bugzilla.redhat.com/show_bug.cgi?id=1049537) [1049915](https://bugzilla.redhat.com/show_bug.cgi?id=1049915) [1049982](https://bugzilla.redhat.com/show_bug.cgi?id=1049982) | None | | All-in-One w/ Neutron OVS (no tunnels, real provider net) Networking | | CentOS 6.5 | ?? | [Neutron-Quickstart w/ External Accessibility](http://allthingsopen.com/2013/08/23/openstack-packstack-installation-with-external-connectivity) | marun | 2014-01-08 | None | None | | | | Fedora 20 | ?? | [Neutron-Quickstart w/ External Accessibility](http://allthingsopen.com/2013/08/23/openstack-packstack-installation-with-external-connectivity) | ihrachys | 01/08/2014 | [972918](https://bugzilla.redhat.com/show_bug.cgi?id=972918) | None | | | | RHEL 6.5 | ?? | [Neutron-Quickstart w/ External Accessibility](http://allthingsopen.com/2013/08/23/openstack-packstack-installation-with-external-connectivity) | ihrachys | 01/08/2014 | [1050025](https://bugzilla.redhat.com/show_bug.cgi?id=1050025) | None | | Distributed w/ Neutron ML2 Networking | | RHEL 6.5 | ?? | [Modular Layer 2 (ML2) Plugin](Modular Layer 2 (ML2) Plugin) | panda | 01/07-08/2014 | None | testsuite name="smoke" tests="156" errors="15" failures="3" skip="18" | | Distributed w/ Neutron OVS (GRE) Networking | | CentOS 6.5 | ?? | [Using_GRE_Tenant_Networks](Using_GRE_Tenant_Networks) | weshay | 01/07-08/2014 | None | debugging <testsuite name="smoketests" tests="181" errors="18" failures="0" skip="14"> | | Distributed w/ Neutron OVS (GRE) Networking | | RHEL 6.5 | <span style="background:#00ff00">Good</span> | [Using_GRE_Tenant_Networks](Using_GRE_Tenant_Networks) | oblaut | 2014-01-07 | [1049597](https://bugzilla.redhat.com/show_bug.cgi?id=1049597) | None | | Multi-Node w/ Neutron OVS (GRE) Networking | | CENTOS 6.5 | <span style="background:#00ff00">Good with bugs</span> | [Using_GRE_Tenant_Networks](Using_GRE_Tenant_Networks) | cgirda | 2014-02-20 | None | None | | | | Fedora 20 | <span style="background:#00ff00">Good</span> | [Using_GRE_Tenant_Networks](Using_GRE_Tenant_Networks) | rlandy | 01/07/2014 | [1049985](https://bugzilla.redhat.com/show_bug.cgi?id=1049985) | Required workaround not listed on Workarounds_2014_01 page | | | | RHEL 6.5 | ?? | [Using_GRE_Tenant_Networks](Using_GRE_Tenant_Networks) | jlibosva | 01/07/2014 | None | None | | Distributed w/ Neutron OVS (VXLAN) Networking | | RHEL 6.5 | ?? | [Using VXLAN Tenant Networks](Using VXLAN Tenant Networks) | amuller | 01/07/2014 | None | None | | | | Fedora 20 | ?? | | | | None | None | | Neutron VPNaaS Networking | | RHEL 6.5 | ?? | | ?? | ?? | None | None | | | | Fedora 20 | ?? | | ?? | ?? | None | None | | | | RHEL 6.5 | ?? | | ?? | ?? | None | None | | Neutron LBaaS Networking | | RHEL 6.5 | Yfried | | ?? | ?? | None | None | | | | Fedora 20 | ?? | | ?? | ?? | None | None | ## Packstack Based Installation (Storage Components) Please see [Docs/Storage](Docs/Storage) for configuration guides as well as suggestions on what could be tested for both Cinder and Glance and make sure to use the steps described in the [RDO_test_day_January_2014#How_To_Test](RDO_test_day_January_2014#How_To_Test) page when installing the base RDO system. **Do not** go trough the Quickstart steps unmodified which will instead give you an RDO Havana deployment. | Config Name | Backend | BaseOS | Status | HOWTO | Who | Date | BZ/LP | Notes Page | |---------------------------------------------------------------|----------------------------------------------------------------------|-------------|--------------------------------------------------|-------|----------|---------------|-------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------| | [Cinder] All-in-One: different Cinder drivers only | See [Docs/Storage](Docs/Storage) for guides and testables | | | | CentOS 6.5 | ?? | | ?? | ?? | None | None | | | | Fedora 20 | ?? | | ?? | ?? | None | None | | | LVM | RHEL 6.5 | <span style="background:#00ff00">Good</span> | | mbourvin | 01/07/2014 | None | None | | | gluster | RHEL 6.5 | ?? | | ?? | ?? | None | None | | | ThinLVM | RHEL 6.5 | <span style="background:##ff0000">Fail</span> | | ewarszaw | ?? | None | None | | | nfs | RHEL 6.5 | ?? | | ?? | ?? | None | None | | | | RHEL 7 Beta | ?? | | ?? | ?? | None | None | | [Cinder] Semi/Fully Distributed: GlusterFS, EMC, LVM, ThinLVM | See [Docs/Storage](Docs/Storage) for guides and testables | | | | CentOS 6.5 | ?? | | ?? | ?? | None | None | | | EMC iSCSI | RHEL 6.5 | <span style="background:#ffff00">Med</span> | | giulivo | 01/07/2014 | [1049382](https://bugzilla.redhat.com/show_bug.cgi?id=1049382) [1049511](https://bugzilla.redhat.com/show_bug.cgi?id=1049511) | [1049872](https://bugzilla.redhat.com/show_bug.cgi?id=1049872) [997011](https://bugzilla.redhat.com/show_bug.cgi?id=997011) | | | ThinLVM | RHEL 6.5 | <span style="background:#ff0000">Fail</span> | | giulivo | 01/08/2014 | [1049944](https://bugzilla.redhat.com/show_bug.cgi?id=1049944) [1049947](https://bugzilla.redhat.com/show_bug.cgi?id=1049947) | | | | | Fedora 20 | ?? | | ?? | ?? | None | None | | | | RHEL 6.5 | ?? | | ?? | ?? | None | None | | | | RHEL 7 Beta | ?? | | ?? | ?? | None | None | | [Glance] All-in-One: different Glance drivers only | See [Docs/Storage](Docs/Storage) for guides and testables | | | | CentOS 6.5 | ?? | | ?? | ?? | None | None | | | local | Fedora 20 | <span style="background:#00ff00">WIP Good</span> | | flaper87 | 01/07/2014 | None | None | | | local Thin LVM | RHEL 6.5 | <span style="background:#00ff00">WIP Good</span> | | edu | 01/07/2014 | None | None | | | local | RHEL 6.5 | <span style="background:#00ff00">Good</span> | | mbourvin | 01/07/2014 | None | None | | | | RHEL 7 Beta | ?? | | ?? | ?? | None | None | | [Glance] Semi/Fully Distributed: GlusterFS, Swift | See [Docs/Storage](Docs/Storage) for guides and testables | | | | CentOS 6.5 | ?? | | ?? | ?? | None | None | | | | Fedora 20 | ?? | | ?? | ?? | None | None | | | Swift | RHEL 6.5 | <span style="background:#00ff00">Good</span> | | mpavlase | 01-02/07/2014 | None | None | | | | RHEL 7 Beta | ?? | | ?? | ?? | None | None | ## Packstack Based Installation (Misc Components) Various components which don't fit the large test efforts above. | Item/Area Name | Release | BaseOS | Status | HOWTO | Who | Date | BZ/LP | Notes Page | |----------------------------------------------------|--------------|----------|----------------------------------------------|-------|----------|-----------|----------------------------------------------------------------|-------------------------------------------------| | Ceilometer: All-in-One w/ Neutron Networking, Heat | RDO icehouse | RHEL 6.5 | <span style="background:#00ff00">GOOD</span> | | kwhitney | 2014-0107 | [1049493](https://bugzilla.redhat.com/show_bug.cgi?id=1049493) | Used script "cst.bash" (Ceilometer Sanity Test) | ## Advanced Installs (Foreman Based) -- Work in Progress Please see [Deploying RDO Using Foreman](Deploying RDO Using Foreman) for directions on setting up compute and controller nodes using foreman (only RHEL (derivatives) for now) | Config Name | Release | BaseOS | Status | HOWTO | Who | Date | BZ/LP | Notes Page | |------------------------------------------|--------------|------------|----------------------------------------------|---------------------------------------------------------------------------------------------------------------------|-------------------|---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------| | 2 Node install with Nova Networking | RDO Icehouse | RHEL 6.5 | <span style="background:#00ff00">Good</span> | [ 2 Node install with Nova Networking](Deploying_RDO_Using_Foreman #2_Node_install_with_Nova_Networking) | ohochman | 01/07-08/2013 | [1047353](https://bugzilla.redhat.com/show_bug.cgi?id=1047353) [1048922](https://bugzilla.redhat.com/show_bug.cgi?id=1048922) | | Used the: latest & greatest: - openstack-foreman-installer noarch 1.0.1-2.el6 + puppet-3.4.2-1.el6.noarch.rpm | | | | CentOS 6.5 | ?? | [ 2 Node install with Nova Networking](Deploying_RDO_Using_Foreman#2_Node_install_with_Nova_Networking) | ?? | ?? | None | None | | 3 Node install with Neutron | RDO Icehouse | RHEL 6.5 | <span style="background:#00ff00">Good</span> | [ 3 Node install with Neutron](Deploying_RDO_Using_Foreman#Neutron_with_Networker_Node) | ohochman | 01/07-08/2013 | [1047353](https://bugzilla.redhat.com/show_bug.cgi?id=1047353) [1048922](https://bugzilla.redhat.com/show_bug.cgi?id=1048922) [1049895](https://bugzilla.redhat.com/show_bug.cgi?id=1049895) | | None | | | | CentOS 6.5 | ?? | [ 3 Node install with Neutron](Deploying_RDO_Using_Foreman#Neutron_with_Networker_Node) | majopela | 01/08/2013 | None | None | | 4 node (Compute x2) install with Neutron | RDO Icehouse | RHEL 6.5 | <span style="background:#ffff00">Med</span> | [ 4 Node install (Compute x2) with Neutron](Deploying_RDO_Using_Foreman#Neutron_with_Networker_Node) | bcrochet ohochman | 01/07/2014 | None | None | | Multi-host w/ Load Balanced Services | RDO Icehouse | RHEL 6.5 | None | [ Load Balanced API](Load_Balance_OpenStack_API) | ?? | ?? | None | None | | | | CentOS 6.5 | ?? | [ Load Balanced API](Load_Balance_OpenStack_API) | ?? | ?? | None | None | | HA MySql | RDO Icehouse | RHEL 6.5 | ?? | [ HA MySql](Deploying_RDO_Using_Foreman#HA_Database_Cluster) | ?? | ?? | None | None | | | | CentOS 6.5 | ?? | [ HA MySql](Deploying_RDO_Using_Foreman#HA_Database_Cluster) | ?? | ?? | None | None | ## Other | Config Name | Release | BaseOS | Status | HOWTO | Who | Date | BZ/LP | Notes Page | |-------------------------------------------------------------|---------|--------|----------------------------------------------|--------------------------------------------------------------------------------------------------|---------|--------------|-------|----------------------------------------------------------| | Savanna, hadoop cluster provisioning | | | ?? | [Savanna installation and setup](https://savanna.readthedocs.org/en/latest/) | ?? | ?? | None | None | | Securing RDO Core Services (API Endpoints, Message Brokers) | | | ?? | [Securing_Services](Securing_Services) | ?? | ?? | None | None | | Tuskar and TripleO | | | <span style="background:#ff0000">FAIL</span> | [Deploying_RDO_Using_Tuskar_And_TripleO](Deploying_RDO_Using_Tuskar_And_TripleO) | jhenner | 7-8. 1. 2014 | None | <https://etherpad.openstack.org/p/rdo_test_day_jan_2014> |
vaneldik/website
source/uncategorized/testedsetups-2014-01.html.md
Markdown
mit
44,621
// // RKObjectMappingResult.h // RestKit // // Created by Blake Watters on 5/7/11. // Copyright (c) 2009-2012 RestKit. All rights reserved. // // 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. // #import <Foundation/Foundation.h> @interface RKObjectMappingResult : NSObject { id _keyPathToMappedObjects; } - (id)initWithDictionary:(id)dictionary; + (RKObjectMappingResult*)mappingResultWithDictionary:(NSDictionary*)keyPathToMappedObjects; /** Return the mapping result as a dictionary */ - (NSDictionary*)asDictionary; - (id)asObject; - (NSArray*)asCollection; - (NSError*)asError; @end
bendyworks/TravisCI.app
Pods/RestKit/Code/ObjectMapping/RKObjectMappingResult.h
C
mit
1,114
// // HttpListenerPrefixCollection.cs // Copied from System.Net.HttpListenerPrefixCollection.cs // // Author: // Gonzalo Paniagua Javier ([email protected]) // // Copyright (c) 2005 Novell, Inc. (http://www.novell.com) // Copyright (c) 2012-2013 sta.blockhead // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; namespace WebSocketSharp.Net { /// <summary> /// Provides the collection used to store the URI prefixes for the <see cref="HttpListener"/>. /// </summary> public class HttpListenerPrefixCollection : ICollection<string>, IEnumerable<string>, IEnumerable { #region Private Fields private HttpListener _listener; private List<string> _prefixes; #endregion #region Private Constructors private HttpListenerPrefixCollection () { _prefixes = new List<string> (); } #endregion #region Internal Constructors internal HttpListenerPrefixCollection (HttpListener listener) : this () { _listener = listener; } #endregion #region Public Properties /// <summary> /// Gets the number of prefixes contained in the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <value> /// A <see cref="int"/> that contains the number of prefixes. /// </value> public int Count { get { return _prefixes.Count; } } /// <summary> /// Gets a value indicating whether access to the <see cref="HttpListenerPrefixCollection"/> /// is read-only. /// </summary> /// <value> /// Always returns <c>false</c>. /// </value> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether access to the <see cref="HttpListenerPrefixCollection"/> /// is synchronized. /// </summary> /// <value> /// Always returns <c>false</c>. /// </value> public bool IsSynchronized { get { return false; } } #endregion #region Public Methods /// <summary> /// Adds the specified <paramref name="uriPrefix"/> to the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <param name="uriPrefix"> /// A <see cref="string"/> that contains a URI prefix to add. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="uriPrefix"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="uriPrefix"/> is invalid. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/> /// is closed. /// </exception> public void Add (string uriPrefix) { _listener.CheckDisposed (); ListenerPrefix.CheckUriPrefix (uriPrefix); if (_prefixes.Contains (uriPrefix)) return; _prefixes.Add (uriPrefix); if (_listener.IsListening) EndPointManager.AddPrefix (uriPrefix, _listener); } /// <summary> /// Removes all URI prefixes from the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/> /// is closed. /// </exception> public void Clear () { _listener.CheckDisposed (); _prefixes.Clear (); if (_listener.IsListening) EndPointManager.RemoveListener (_listener); } /// <summary> /// Returns a value indicating whether the <see cref="HttpListenerPrefixCollection"/> contains /// the specified <paramref name="uriPrefix"/>. /// </summary> /// <returns> /// <c>true</c> if the <see cref="HttpListenerPrefixCollection"/> contains <paramref name="uriPrefix"/>; /// otherwise, <c>false</c>. /// </returns> /// <param name="uriPrefix"> /// A <see cref="string"/> that contains a URI prefix to test. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="uriPrefix"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/> /// is closed. /// </exception> public bool Contains (string uriPrefix) { _listener.CheckDisposed (); if (uriPrefix == null) throw new ArgumentNullException ("uriPrefix"); return _prefixes.Contains (uriPrefix); } /// <summary> /// Copies the contents of the <see cref="HttpListenerPrefixCollection"/> to /// the specified <see cref="Array"/>. /// </summary> /// <param name="array"> /// An <see cref="Array"/> that receives the URI prefix strings /// in the <see cref="HttpListenerPrefixCollection"/>. /// </param> /// <param name="offset"> /// An <see cref="int"/> that contains the zero-based index in <paramref name="array"/> /// at which copying begins. /// </param> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/> /// is closed. /// </exception> public void CopyTo (Array array, int offset) { _listener.CheckDisposed (); ((ICollection) _prefixes).CopyTo (array, offset); } /// <summary> /// Copies the contents of the <see cref="HttpListenerPrefixCollection"/> to /// the specified array of <see cref="string"/>. /// </summary> /// <param name="array"> /// An array of <see cref="string"/> that receives the URI prefix strings /// in the <see cref="HttpListenerPrefixCollection"/>. /// </param> /// <param name="offset"> /// An <see cref="int"/> that contains the zero-based index in <paramref name="array"/> /// at which copying begins. /// </param> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/> /// is closed. /// </exception> public void CopyTo (string [] array, int offset) { _listener.CheckDisposed (); _prefixes.CopyTo (array, offset); } /// <summary> /// Gets an object that can be used to iterate through the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <returns> /// An object that implements the IEnumerator&lt;string&gt; interface and provides access to /// the URI prefix strings in the <see cref="HttpListenerPrefixCollection"/>. /// </returns> public IEnumerator<string> GetEnumerator () { return _prefixes.GetEnumerator (); } /// <summary> /// Removes the specified <paramref name="uriPrefix"/> from the list of prefixes /// in the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <returns> /// <c>true</c> if <paramref name="uriPrefix"/> is successfully found and removed; /// otherwise, <c>false</c>. /// </returns> /// <param name="uriPrefix"> /// A <see cref="string"/> that contains a URI prefix to remove. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="uriPrefix"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="HttpListener"/> associated with this <see cref="HttpListenerPrefixCollection"/> /// is closed. /// </exception> public bool Remove (string uriPrefix) { _listener.CheckDisposed (); if (uriPrefix == null) throw new ArgumentNullException ("uriPrefix"); var result = _prefixes.Remove (uriPrefix); if (result && _listener.IsListening) EndPointManager.RemovePrefix (uriPrefix, _listener); return result; } #endregion #region Explicit Interface Implementation /// <summary> /// Gets an object that can be used to iterate through the <see cref="HttpListenerPrefixCollection"/>. /// </summary> /// <returns> /// An object that implements the <see cref="IEnumerator"/> interface and provides access to /// the URI prefix strings in the <see cref="HttpListenerPrefixCollection"/>. /// </returns> IEnumerator IEnumerable.GetEnumerator () { return _prefixes.GetEnumerator (); } #endregion } }
uken/websocket-sharp
websocket-sharp/Net/HttpListenerPrefixCollection.cs
C#
mit
9,048
package com.daviancorp.android.ui.detail; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.media.Image; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.support.v4.content.Loader; import android.support.v4.widget.CursorAdapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.daviancorp.android.data.classes.HuntingReward; import com.daviancorp.android.data.database.HuntingRewardCursor; import com.daviancorp.android.loader.HuntingRewardListCursorLoader; import com.daviancorp.android.mh4udatabase.R; import com.daviancorp.android.ui.ClickListeners.MonsterClickListener; import java.io.IOException; public class ItemMonsterFragment extends ListFragment implements LoaderCallbacks<Cursor> { private static final String ARG_ITEM_ID = "ITEM_ID"; public static ItemMonsterFragment newInstance(long itemId) { Bundle args = new Bundle(); args.putLong(ARG_ITEM_ID, itemId); ItemMonsterFragment f = new ItemMonsterFragment(); f.setArguments(args); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Initialize the loader to load the list of runs getLoaderManager().initLoader(R.id.item_monster_fragment, getArguments(), this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_generic_list, null); return v; } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // You only ever load the runs, so assume this is the case long itemId = args.getLong(ARG_ITEM_ID, -1); return new HuntingRewardListCursorLoader(getActivity(), HuntingRewardListCursorLoader.FROM_ITEM, itemId, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // Create an adapter to point at this cursor ItemHuntingRewardListCursorAdapter adapter = new ItemHuntingRewardListCursorAdapter( getActivity(), (HuntingRewardCursor) cursor); setListAdapter(adapter); } @Override public void onLoaderReset(Loader<Cursor> loader) { // Stop using the cursor (via the adapter) setListAdapter(null); } private static class ItemHuntingRewardListCursorAdapter extends CursorAdapter { private HuntingRewardCursor mHuntingRewardCursor; public ItemHuntingRewardListCursorAdapter(Context context, HuntingRewardCursor cursor) { super(context, cursor, 0); mHuntingRewardCursor = cursor; } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { // Use a layout inflater to get a row view LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); return inflater.inflate(R.layout.fragment_item_monster_listitem, parent, false); } @Override public void bindView(View view, Context context, Cursor cursor) { // Get the item for the current row HuntingReward huntingReward = mHuntingRewardCursor.getHuntingReward(); // Set up the text view RelativeLayout itemLayout = (RelativeLayout) view.findViewById(R.id.listitem); TextView rankTextView = (TextView) view.findViewById(R.id.rank); TextView monsterTextView = (TextView) view.findViewById(R.id.monster); TextView methodTextView = (TextView) view.findViewById(R.id.method); TextView amountTextView = (TextView) view.findViewById(R.id.amount); TextView percentageTextView = (TextView) view .findViewById(R.id.percentage); ImageView monsterImageView = (ImageView) view.findViewById(R.id.monster_image); String cellRankText = huntingReward.getRank(); String cellMonsterText = huntingReward.getMonster().getName(); String cellMethodText = huntingReward.getCondition(); int cellAmountText = huntingReward.getStackSize(); int cellPercentageText = huntingReward.getPercentage(); rankTextView.setText(cellRankText); monsterTextView.setText(cellMonsterText); methodTextView.setText(cellMethodText); amountTextView.setText("" + cellAmountText); String percent = "" + cellPercentageText + "%"; percentageTextView.setText(percent); itemLayout.setTag(huntingReward.getMonster().getId()); itemLayout.setOnClickListener(new MonsterClickListener(context, huntingReward.getMonster().getId())); Drawable i = null; String cellImage = "icons_monster/" + huntingReward.getMonster().getFileLocation(); try { i = Drawable.createFromStream( context.getAssets().open(cellImage), null); } catch (IOException e) { e.printStackTrace(); } monsterImageView.setImageDrawable(i); } } }
flamearrow/MonsterHunter4UDatabase
app/src/main/java/com/daviancorp/android/ui/detail/ItemMonsterFragment.java
Java
mit
5,173
/*expected initial->s1_1->s1_2->s1_3->s1_4; s1_1->s1_4; s1_2->s1_4->final; */ a &&= b ?? c; /*DOT digraph { node[shape=box,style="rounded,filled",fillcolor=white]; initial[label="",shape=circle,style=filled,fillcolor=black,width=0.25,height=0.25]; final[label="",shape=doublecircle,style=filled,fillcolor=black,width=0.25,height=0.25]; s1_1[label="Program:enter\nExpressionStatement:enter\nAssignmentExpression:enter\nIdentifier (a)"]; s1_2[label="LogicalExpression:enter\nIdentifier (b)"]; s1_3[label="Identifier (c)\nLogicalExpression:exit"]; s1_4[label="AssignmentExpression:exit\nExpressionStatement:exit\nProgram:exit"]; initial->s1_1->s1_2->s1_3->s1_4; s1_1->s1_4; s1_2->s1_4->final; } */
DavidAnson/eslint
tests/fixtures/code-path-analysis/assignment--logical-and-3.js
JavaScript
mit
736
# Contributing :raised_hands::tada: First off, thanks for taking the time to contribute! :tada::raised_hands: The following is a set of guidelines for contributing to react-datetime. The purpose of these guidelines is to maintain a high quality of code *and* traceability. Please respect these guidelines. ## General This repository use tests and a linter as automatic tools to maintain the quality of the code. These two tasks are run locally on your machine before every commit (as a pre-commit git hook), if any test fail or the linter gives an error the commit will not be created. They are also run on a Travis CI machine when you create a pull request, and the PR will not be merged unless Travis says all tests and the linting pass. ## Git Commit Messages * Use the present tense ("Add feature" not "Added feature") * Use the imperative mood ("Move cursor to..." not "Moves cursor to...") * Think of it as you are *commanding* what your commit is doing * Git itself uses the imperative whenever it creates a commit on your behalf, so it makes sense for you to use it too * Use the body to explain *what* and *why* * If the commit is non-trivial, please provide more detailed information in the commit body message * *How* you made the change is visible in the code and is therefore rarely necessary to include in the commit body message, but *why* you made the change is often harder to guess and is therefore useful to include in the commit body message [Here's a nice blog post on how to write great git messages.](http://chris.beams.io/posts/git-commit/) ## Pull Requests * Follow the current code style * Write tests for your changes * Document your changes in the README if it's needed * End files with a newline * There's no need to create a new build for each pull request, we (the maintainers) do this when we release a new version ## Issues * Please be descriptive when you fill in the issue template, this will greatly help us maintainers in helping you which will lead to your issue being resolved faster * Feature requests are very welcomed, but not every feature that is requested can be guaranteed to be implemented
arqex/react-datetime
.github/CONTRIBUTING.md
Markdown
mit
2,177
(function(){ angular.module('angularytics').factory('AngularyticsGoogleHandler', function() { var service = {}; service.trackPageView = function(url) { _gaq.push(['_set', 'page', url]); _gaq.push(['_trackPageview', url]); }; service.trackEvent = function(category, action, opt_label, opt_value, opt_noninteraction) { _gaq.push(['_trackEvent', category, action, opt_label, opt_value, opt_noninteraction]); }; service.trackTiming = function(category, variable, value, opt_label) { _gaq.push(['_trackTiming', category, variable, value, opt_label]); }; return service; }).factory('AngularyticsGoogleUniversalHandler', function () { var service = {}; service.trackPageView = function (url) { ga('set', 'page', url); ga('send', 'pageview', url); }; service.trackEvent = function (category, action, opt_label, opt_value, opt_noninteraction) { ga('send', 'event', category, action, opt_label, opt_value, {'nonInteraction': opt_noninteraction}); }; service.trackTiming = function (category, variable, value, opt_label) { ga('send', 'timing', category, variable, value, opt_label); }; return service; }); })();
chutterbox/chutter
vendor/angularytics/src/googleHandler.js
JavaScript
mit
1,345
$('.ui.checkbox') .checkbox() ; $(".ui.right.pointing").dropdown();
ovenslove/ExpressBlog
blog/public/js/trash.js
JavaScript
mit
71
IBodyIndexFrame::get\_FrameDescription Method ============================================= Gets the description of the body index frame. <span id="syntaxSection"></span> Syntax ====== <table> <colgroup> <col width="100%" /> </colgroup> <thead> <tr class="header"> <th align="left">C++</th> </tr> </thead> <tbody> <tr class="odd"> <td align="left"><pre><code>public: HRESULT get_FrameDescription( IFrameDescription **frameDescription )</code></pre></td> </tr> </tbody> </table> <span id="ID4EG"></span> #### Parameters *frameDescription* Type: IFrameDescription [out] The description of the body index infrared frame. <span id="ID4EP"></span> #### Return value Type: HRESULT Returns S\_OK if successful; otherwise, returns a failure code. <span id="requirements"></span> Requirements ============ **Header:** kinect.h **Library:** kinect20.lib <!--Please do not edit the data in the comment block below.--> <!-- TOCTitle : get_FrameDescription Method RLTitle : IBodyIndexFrame::get_FrameDescription Method KeywordK : get_FrameDescription method KeywordK : IBodyIndexFrame::get_FrameDescription method KeywordF : IBodyIndexFrame::get_FrameDescription KeywordF : get_FrameDescription KeywordF : Microsoft.Kinect.kinect.IBodyIndexFrame.get_FrameDescription(IFrameDescription@) KeywordA : M:Microsoft.Kinect.kinect.IBodyIndexFrame.get_FrameDescription(IFrameDescription@) AssetID : M:Microsoft.Kinect.kinect.IBodyIndexFrame.get_FrameDescription(IFrameDescription@) Locale : en-us CommunityContent : 1 APIType : Managed APILocation : APIName : Microsoft.Kinect.kinect.IBodyIndexFrame::get_FrameDescription TargetOS : Windows TopicType : kbSyntax DevLang : C++ DocSet : K4Wv2 ProjType : K4Wv2Proj Technology : Kinect for Windows Product : Kinect for Windows SDK v2 productversion : 20 -->
UnaNancyOwen/Docs
Kinect4Windows2.0/k4w2/Reference/C++_Reference/Interfaces/IBodyIndexFrame_Interface/Methods/get_FrameDescription_Method.md
Markdown
mit
1,844
module Fastlane module Actions class FrameitAction < Action def self.run(config) return if Helper.test? require 'frameit' begin FastlaneCore::UpdateChecker.start_looking_for_update('frameit') unless Helper.is_test? color = Frameit::Color::BLACK color = Frameit::Color::SILVER if config[:white] || config[:silver] UI.message("Framing screenshots at path #{config[:path]}") Dir.chdir(config[:path]) do ENV["FRAMEIT_FORCE_DEVICE_TYPE"] = config[:force_device_type] if config[:force_device_type] Frameit::Runner.new.run('.', color) ENV.delete("FRAMEIT_FORCE_DEVICE_TYPE") if config[:force_device_type] end ensure FastlaneCore::UpdateChecker.show_update_status('frameit', Frameit::VERSION) end end def self.description "Adds device frames around the screenshots using frameit" end def self.available_options [ FastlaneCore::ConfigItem.new(key: :white, env_name: "FRAMEIT_WHITE_FRAME", description: "Use white device frames", optional: true, is_string: false), FastlaneCore::ConfigItem.new(key: :silver, description: "Use white device frames. Alias for :white", optional: true, is_string: false), FastlaneCore::ConfigItem.new(key: :path, env_name: "FRAMEIT_SCREENSHOTS_PATH", description: "The path to the directory containing the screenshots", default_value: Actions.lane_context[SharedValues::SNAPSHOT_SCREENSHOTS_PATH] || FastlaneFolder.path), FastlaneCore::ConfigItem.new(key: :force_device_type, env_name: "FRAMEIT_FORCE_DEVICE_TYPE", description: "Forces a given device type, useful for Mac screenshots, as their sizes vary", optional: true, verify_block: proc do |value| available = ['iPhone_6_Plus', 'iPhone_5s', 'iPhone_4', 'iPad_mini', 'Mac'] unless available.include? value raise "Invalid device type '#{value}'. Available values: #{available}".red end end) ] end def self.author "KrauseFx" end def self.is_supported?(platform) [:ios, :mac].include? platform end end end end
cbowns/fastlane
fastlane/lib/fastlane/actions/frameit.rb
Ruby
mit
2,945
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ (function() { ccui.Scale9Sprite.CanvasRenderCmd = function (renderable) { cc.Node.CanvasRenderCmd.call(this, renderable); this._cachedParent = null; this._cacheDirty = false; this._state = ccui.Scale9Sprite.state.NORMAL; var node = this._node; var locCacheCanvas = this._cacheCanvas = cc.newElement('canvas'); locCacheCanvas.width = 1; locCacheCanvas.height = 1; this._cacheContext = new cc.CanvasContextWrapper(locCacheCanvas.getContext("2d")); var locTexture = this._cacheTexture = new cc.Texture2D(); locTexture.initWithElement(locCacheCanvas); locTexture.handleLoadedTexture(); this._cacheSprite = new cc.Sprite(locTexture); this._cacheSprite.setAnchorPoint(0,0); node.addChild(this._cacheSprite); }; var proto = ccui.Scale9Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype); proto.constructor = ccui.Scale9Sprite.CanvasRenderCmd; proto.visit = function(parentCmd){ var node = this._node; if(!node._visible) return; if (node._positionsAreDirty) { node._updatePositions(); node._positionsAreDirty = false; node._scale9Dirty = true; } node._scale9Dirty = false; this._cacheScale9Sprite(); cc.Node.CanvasRenderCmd.prototype.visit.call(this, parentCmd); }; proto.transform = function(parentCmd){ var node = this._node; cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd); if (node._positionsAreDirty) { node._updatePositions(); node._positionsAreDirty = false; node._scale9Dirty = true; } this._cacheScale9Sprite(); var children = node._children; for(var i=0; i<children.length; i++){ children[i].transform(this); } }; proto._updateDisplayColor = function(parentColor){ cc.Node.CanvasRenderCmd.prototype._updateDisplayColor.call(this, parentColor); var scale9Image = this._node._scale9Image; if(scale9Image){ var scaleChildren = scale9Image.getChildren(); for (var i = 0; i < scaleChildren.length; i++) { var selChild = scaleChildren[i]; if (selChild){ selChild._renderCmd._updateDisplayColor(parentColor); selChild._renderCmd._updateColor(); } } this._cacheScale9Sprite(); } }; proto._cacheScale9Sprite = function(){ var node = this._node; if(!node._scale9Image) return; var locScaleFactor = cc.contentScaleFactor(); var size = node._contentSize; var sizeInPixels = cc.size(size.width * locScaleFactor, size.height * locScaleFactor); var locCanvas = this._cacheCanvas, wrapper = this._cacheContext, locContext = wrapper.getContext(); var contentSizeChanged = false; if(locCanvas.width !== sizeInPixels.width || locCanvas.height !== sizeInPixels.height){ locCanvas.width = sizeInPixels.width; locCanvas.height = sizeInPixels.height; contentSizeChanged = true; } //begin cache cc.renderer._turnToCacheMode(node.__instanceId); node._scale9Image.visit(); //draw to cache canvas var selTexture = node._scale9Image.getTexture(); if(selTexture && this._state === ccui.Scale9Sprite.state.GRAY) selTexture._switchToGray(true); locContext.setTransform(1, 0, 0, 1, 0, 0); locContext.clearRect(0, 0, sizeInPixels.width, sizeInPixels.height); cc.renderer._renderingToCacheCanvas(wrapper, node.__instanceId, locScaleFactor, locScaleFactor); if(selTexture && this._state === ccui.Scale9Sprite.state.GRAY) selTexture._switchToGray(false); if(contentSizeChanged) this._cacheSprite.setTextureRect(cc.rect(0,0, size.width, size.height)); if(!this._cacheSprite.getParent()) node.addChild(this._cacheSprite, -1); }; proto.setState = function(state){ var locScale9Image = this._node._scale9Image; if(!locScale9Image) return; this._state = state; this._cacheScale9Sprite(); }; })();
chukong/sdkbox-samples
frameworks/cocos2d-html5/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js
JavaScript
mit
5,812
# Project "Demo" [![Build Status](https://travis-ci.org/UNIZAR-30246-WebEngineering/UrlShortener2015.svg)](https://travis-ci.org/UNIZAR-30246-WebEngineering/UrlShortener2015) This project is the template for the creation of projects. This project also will contain solutions for blocking issues. The __Demo__ extends the __Common__ project. The code of the project __Demo__ is in the package `urlshortener2014.demo`. It defines the class `UrlShortenerControllerWithLogs` that extends the `UrlShortenerController` provided by the __Core__ with log support for debugging. `Application` and `config` classes configure the __Demo__ application to use `UrlShortenerControllerWithLogs` as controller instead of `UrlShortenerController`. The application can be run as follows: ``` $ gradle run ``` Gradle will compile project __Common__ and then create a `jar` file of it. Next will compile project __Demo__ and run it. Now you have a shortener service running at port 8080 that logs in the console all the requests that you perform.
nebur395/UrlShortener
demo/README.md
Markdown
mit
1,035
'use strict'; var React = require('react'); var Modifiable = React.createFactory(require('./Modifiable.js')); var moment = require('moment'); /* interface AntProps{ ant: { create_at : string, id: int, installed_at: int, isUpdating: boolean, latest_input: string, latest_output: string, name: string, sim: string, client_status: string, outputs: [], updated_at: string, lastMeasurementDate: string, isSelected: bool }, isSelected: boolean, isUpdating: boolean, currentPlaceId: int, onChangeSensor: function(), onSelectedAnts: function() } interface AntState{ isListOpen: boolean } */ var Ant = React.createClass({ displayName: 'Ant', getInitialState: function(){ return { isOpen: false }; }, toggleList: function(){ this.setState(Object.assign(this.state, { isListOpen: !this.state.isListOpen })); }, render: function() { var props = this.props; // console.log('ANT props', props); // console.log('ANT state', state); var classes = [ 'ant', props.ant.client_status ? props.ant.client_status.toLowerCase() : '', props.isSelected ? 'selected' : '', props.ant.isUpdating ? 'updating' : '' ]; var outputs = props.ant.outputs; var wifiStatus = outputs.get('wifi') ? outputs.get('wifi').status : ''; var bluetoothStatus = outputs.get('bluetooth') ? outputs.get('bluetooth').status : ''; var wifiClasses = ['wifi', wifiStatus]; var bluetoothClasses = ['bluetooth', bluetoothStatus]; return React.DOM.div({className: classes.join(' ')}, React.DOM.input({ className: 'ant-selector', onClick: function(){ props.onSelectedAnts(props.ant.id); }, type: 'checkbox', checked: props.isSelected }), React.DOM.ul({}, React.DOM.li({className: 'light'}, React.DOM.div({}, React.DOM.div({}, 'Name'), new Modifiable({ className: 'sensorName', isUpdating: false, text: props.ant.name, dbLink: { sim: props.ant.sim, field: 'name' }, onChange: props.onChangeSensor }) ), React.DOM.div({}, React.DOM.div({}, 'Id'), React.DOM.div({}, props.ant.sim) // currently, the sim in Db is considered as the id in general ) ), React.DOM.li({className: 'client dark'}, props.ant.client_status ), React.DOM.li({className: 'sense light'}, React.DOM.div({}, React.DOM.div({}, 'Sensors'), React.DOM.div({className: 'sensors'}, React.DOM.div({className: wifiClasses.join(' ')}, React.DOM.i({className: 'flaticon-wifi74'}), React.DOM.div({}, wifiStatus) ), React.DOM.div({className: bluetoothClasses.join(' ')}, React.DOM.i({className: 'flaticon-logotype56'}), React.DOM.div({}, bluetoothStatus) ) ), React.DOM.div({className: 'settings'}, React.DOM.div({}, 'Settings: '), React.DOM.div({}, props.ant.period ? props.ant.period : 'ND'), React.DOM.div({}, props.ant.start_hour ? props.ant.start_hour : 'ND'), React.DOM.div({}, props.ant.stop_hour ? props.ant.stop_hour : 'ND') ) ) ), React.DOM.li({className: 'command dark'}, React.DOM.div({}, React.DOM.div({}, 'Last Command'), React.DOM.div({}, props.ant.latest_input), React.DOM.div({}, props.ant.latest_output) ) ), React.DOM.li({className: 'low-importance light'}, React.DOM.div({}, React.DOM.div({}, 'Last Data'), React.DOM.div({}, props.ant.lastMeasurementDate === '' ? 'No measurement' : moment(props.ant.lastMeasurementDate).fromNow() ) ), React.DOM.div({}, React.DOM.div({}, 'Updated'), React.DOM.div({}, moment(props.ant.updated_at).fromNow()) ) ) ), React.DOM.div({ className: 'uninstall clickable', onClick: function(){ console.log('Uninstalling'); var dbData = { 'field': 'installed_at', 'sim': props.ant.sim, 'value': null }; if (props.isSelected) props.onSelectedAnts(props.ant.id); props.onChangeSensor([dbData]); } }, 'Uninstall' ) ); } }); module.exports = Ant;
6element/pheromon
api/clients/Admin/src/Components/Ant.js
JavaScript
mit
5,981
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Macro BOOST_LOG_GLOBAL_LOGGER_DEFAULT</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="index.html" title="Chapter&#160;1.&#160;Boost.Log v2"> <link rel="up" href="logging_sources.html#header.boost.log.sources.global_logger_storage_hpp" title="Header &lt;boost/log/sources/global_logger_storage.hpp&gt;"> <link rel="prev" href="BOOST_LOG_GLOBAL_LOGGER_INIT.html" title="Macro BOOST_LOG_GLOBAL_LOGGER_INIT"> <link rel="next" href="BOOST_LOG_GLOBAL_LOGGER_CTOR_ARGS.html" title="Macro BOOST_LOG_GLOBAL_LOGGER_CTOR_ARGS"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr><td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td></tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="BOOST_LOG_GLOBAL_LOGGER_INIT.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="logging_sources.html#header.boost.log.sources.global_logger_storage_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="BOOST_LOG_GLOBAL_LOGGER_CTOR_ARGS.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="BOOST_LOG_GLOBAL_LOGGER_DEFAULT"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Macro BOOST_LOG_GLOBAL_LOGGER_DEFAULT</span></h2> <p>BOOST_LOG_GLOBAL_LOGGER_DEFAULT &#8212; The macro defines a global logger initializer that will default-construct the logger. </p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="logging_sources.html#header.boost.log.sources.global_logger_storage_hpp" title="Header &lt;boost/log/sources/global_logger_storage.hpp&gt;">boost/log/sources/global_logger_storage.hpp</a>&gt; </span>BOOST_LOG_GLOBAL_LOGGER_DEFAULT(tag_name, logger)</pre></div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2007-2016 Andrey Semashev<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>). </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="BOOST_LOG_GLOBAL_LOGGER_INIT.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="logging_sources.html#header.boost.log.sources.global_logger_storage_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="BOOST_LOG_GLOBAL_LOGGER_CTOR_ARGS.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
yinchunlong/abelkhan-1
ext/c++/thirdpart/c++/boost/libs/log/doc/html/BOOST_LOG_GLOBAL_LOGGER_DEFAULT.html
HTML
mit
3,457
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path # Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. Rails.application.config.assets.precompile += %w( react-server.js components.js init.js page_specific.js )
aamin005/Firdowsspace
config/initializers/assets.rb
Ruby
mit
529
/* * This file is part of the SDWebImage package. * (c) Olivier Poitrey <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #import "SDWebImageCompat.h" #import "SDImageCoder.h" /** This is the protocol for SDAnimatedImage class only but not for SDAnimatedImageCoder. If you want to provide a custom animated image class with full advanced function, you can conform to this instead of the base protocol. */ @protocol SDAnimatedImage <SDAnimatedImageProvider> @required /** Initializes and returns the image object with the specified data, scale factor and possible animation decoding options. @note We use this to create animated image instance for normal animation decoding. @param data The data object containing the image data. @param scale The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the `size` property. @param options A dictionary containing any animation decoding options. @return An initialized object */ - (nullable instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale options:(nullable SDImageCoderOptions *)options; /** Initializes the image with an animated coder. You can use the coder to decode the image frame later. @note We use this with animated coder which conforms to `SDProgressiveImageCoder` for progressive animation decoding. @param animatedCoder An animated coder which conform `SDAnimatedImageCoder` protocol @param scale The scale factor to assume when interpreting the image data. Applying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the `size` property. @return An initialized object */ - (nullable instancetype)initWithAnimatedCoder:(nonnull id<SDAnimatedImageCoder>)animatedCoder scale:(CGFloat)scale; @optional // These methods are used for optional advanced feature, like image frame preloading. /** Pre-load all animated image frame into memory. Then later frame image request can directly return the frame for index without decoding. This method may be called on background thread. @note If one image instance is shared by lots of imageViews, the CPU performance for large animated image will drop down because the request frame index will be random (not in order) and the decoder should take extra effort to keep it re-entrant. You can use this to reduce CPU usage if need. Attention this will consume more memory usage. */ - (void)preloadAllFrames; /** Unload all animated image frame from memory if are already pre-loaded. Then later frame image request need decoding. You can use this to free up the memory usage if need. */ - (void)unloadAllFrames; /** Returns a Boolean value indicating whether all animated image frames are already pre-loaded into memory. */ @property (nonatomic, assign, readonly, getter=isAllFramesLoaded) BOOL allFramesLoaded; @end @interface SDAnimatedImage : UIImage <SDAnimatedImage> // This class override these methods from UIImage(NSImage), and it supports NSSecureCoding. // You should use these methods to create a new animated image. Use other methods just call super instead. + (nullable instancetype)imageNamed:(nonnull NSString *)name; // Cache in memory, no Asset Catalog support #if __has_include(<UIKit/UITraitCollection.h>) + (nullable instancetype)imageNamed:(nonnull NSString *)name inBundle:(nullable NSBundle *)bundle compatibleWithTraitCollection:(nullable UITraitCollection *)traitCollection; // Cache in memory, no Asset Catalog support #else + (nullable instancetype)imageNamed:(nonnull NSString *)name inBundle:(nullable NSBundle *)bundle; // Cache in memory, no Asset Catalog support #endif + (nullable instancetype)imageWithContentsOfFile:(nonnull NSString *)path; + (nullable instancetype)imageWithData:(nonnull NSData *)data; + (nullable instancetype)imageWithData:(nonnull NSData *)data scale:(CGFloat)scale; - (nullable instancetype)initWithContentsOfFile:(nonnull NSString *)path; - (nullable instancetype)initWithData:(nonnull NSData *)data; - (nullable instancetype)initWithData:(nonnull NSData *)data scale:(CGFloat)scale; /** Current animated image format. */ @property (nonatomic, assign, readonly) SDImageFormat animatedImageFormat; /** Current animated image data, you can use this instead of CGImage to create another instance. If the current image is not animated image, this value is nil. */ @property (nonatomic, copy, readonly, nullable) NSData *animatedImageData; /** The scale factor of the image. @note For UIKit, this just call super instead. @note For AppKit, `NSImage` can contains multiple image representations with different scales. However, this class does not do that from the design. We processs the scale like UIKit. This wil actually be calculated from image size and pixel size. */ @property (nonatomic, readonly) CGFloat scale; // By default, animated image frames are returned by decoding just in time without keeping into memory. But you can choose to preload them into memory as well, See the decsription in `SDAnimatedImage` protocol. // After preloaded, there is no huge difference on performance between this and UIImage's `animatedImageWithImages:duration:`. But UIImage's animation have some issues such like blanking and pausing during segue when using in `UIImageView`. It's recommend to use only if need. - (void)preloadAllFrames; - (void)unloadAllFrames; @property (nonatomic, assign, readonly, getter=isAllFramesLoaded) BOOL allFramesLoaded; @end
czl0325/ZLCollectionView
demo/Pods/SDWebImage/SDWebImage/SDAnimatedImage.h
C
mit
5,804
<!doctype html> <html> <head> <title>Psychology Experiment - Error</title> <link rel=stylesheet href="/static/css/bootstrap.min.css" type="text/css"> <link rel=stylesheet href="/static/css/style.css" type="text/css"> </head> <body> <div id="container-error"> <div id="error"> <h1>Sorry, there was an error</h1> <hr> <div class="alert alert-danger"> {% if errornum == 1008 %} <p>Sorry, our records indicate that you have attempted to complete this HIT, but quit before finishing.</p> <p>Because this is a Psychology experiment, you can only complete this HIT once.</p> <p>Please return the HIT so someone else can perform the experiment.</p> {% elif errornum == 1010 %} <p>Sorry, our records indicate that you have already completed (or attempted to complete) this HIT.</p> <p>Because this is a Psychology experiment, you can only complete this HIT once.</p> <p>Please release the HIT so someone else can perform the experiment.</p> {% else %} <p>Sorry, there was an unexpected error in our processing of your HIT.<p> {% endif %} <p> If you would like to receive partial compensation or feel you have reached this page in error, please email <a href="mailto:[email protected]">[email protected]</a> and send the following information: </p> <p> Error: #{{ errornum }}<br> {% if hitId %} HITID: #{{ hitId }}<br> {% endif %} {% if assignId %}AssignmentId: #{{ assignId }}<br> {% endif %} {% if workerId %} WorkerId: #{{ workerId }}<br> {% endif %} </p> </div> <hr> <h3>Our sincere apologies!</h3> </div> </div> </body> </html>
kasmith/cbmm-project-christmas
psiturk-rg-reach/templates/error.html
HTML
mit
2,257
define([ 'amber/devel', './deploy' // --- packages used only during development begin here --- // --- packages used only during development end here --- ], function (amber) { return amber; });
sebastianconcept/amber-minimal-ide
devel.js
JavaScript
mit
213
drawer { display: block; position: fixed; top:44px; width: 270px; height: 100%; z-index: 100; } drawer.animate { -webkit-transition: 0.4s all ease-in-out; transition: 0.4s all ease-in-out; } .animate { -webkit-transition: 0.4s all ease-in-out; transition: 0.4s all ease-in-out; } .drawerToggle { right:25px; } drawer.left { -webkit-transform: translate3d(-100%, 0, 0); transform: translate3d(-100%, 0, 0); box-shadow: 1px 0px 10px rgba(0,0,0,0.3); } drawer.right { right: 0; top: 0; -webkit-transform: translate3d(100%, 0, 0); transform: translate3d(100%, 0, 0); box-shadow: -1px 0px 10px rgba(0,0,0,0.3); }
guaerguagua/ionic-sworkit-sidemenu
css/drawer.css
CSS
mit
650
function spread(fn, length) { switch(length) { case 0: return function() {return fn();}; case 1: return function(a) {return fn(a[0]);}; case 2: return function(a) {return fn(a[0], a[1]);}; case 3: return function(a) {return fn(a[0], a[1], a[2]);}; case 4: return function(a) {return fn(a[0], a[1], a[2], a[3]);}; default: return function(a) {return fn.apply(null, a);}; } } function apply(fn, c, a) { let aLength = a ? a.length : 0; if (c == null) { switch (aLength) { case 0: return fn(); case 1: return fn(a[0]); case 2: return fn(a[0], a[1]); case 3: return fn(a[0], a[1], a[2]); case 4: return fn(a[0], a[1], a[2], a[3]); default: return fn.apply(null, a); } } else { switch (aLength) { case 0: return fn.call(c); default: return fn.apply(c, a); } } } module.exports = {spread, apply};
kelsadita/kefir
src/utils/functions.js
JavaScript
mit
892
import * as c from "../data/c.json"; import * as d from "../data/d.json"; import { bb, aa } from "../data/e.json"; import f, { named } from "../data/f.json"; import g, { named as gnamed } from "../data/g.json"; it("should be possible to import json data", function() { expect(c[2]).toBe(3); expect(Object.keys(d)).toEqual(["default"]); expect(aa).toBe(1); expect(bb).toBe(2); expect(named).toBe("named"); expect({ f }).toEqual({ f: { __esModule: true, default: "default", named: "named" } }); expect(g.named).toBe(gnamed); });
EliteScientist/webpack
test/cases/json/import-by-name/index.js
JavaScript
mit
549
using FarseerPhysics.Dynamics; using FarseerPhysics.Dynamics.Joints; using Microsoft.Xna.Framework; namespace Nez.Farseer { internal abstract class FSJointDef { public Body bodyA; public Body bodyB; public bool collideConnected; abstract public Joint createJoint(); } internal class FSDistanceJointDef : FSJointDef { public Vector2 ownerBodyAnchor; public Vector2 otherBodyAnchor; public float frequency; public float dampingRatio; public override Joint createJoint() { var joint = new DistanceJoint( bodyA, bodyB, ownerBodyAnchor * FSConvert.displayToSim, otherBodyAnchor * FSConvert.displayToSim ); joint.collideConnected = collideConnected; joint.frequency = frequency; joint.dampingRatio = dampingRatio; return joint; } } internal class FSFrictionJointDef : FSJointDef { public Vector2 anchor; public float maxForce; public float maxTorque; public override Joint createJoint() { var joint = new FrictionJoint( bodyA, bodyB, anchor ); joint.collideConnected = collideConnected; joint.maxForce = maxForce; joint.maxTorque = maxTorque; return joint; } } internal class FSWeldJointDef : FSJointDef { public Vector2 ownerBodyAnchor; public Vector2 otherBodyAnchor; public float dampingRatio; public float frequencyHz; public override Joint createJoint() { var joint = new WeldJoint( bodyA, bodyB, ownerBodyAnchor * FSConvert.displayToSim, otherBodyAnchor * FSConvert.displayToSim ); joint.collideConnected = collideConnected; joint.dampingRatio = dampingRatio; joint.frequencyHz = frequencyHz; return joint; } } internal class FSAngleJointDef : FSJointDef { public float maxImpulse = float.MaxValue; public float biasFactor = 0.2f; public float softness; public override Joint createJoint() { var joint = new AngleJoint( bodyA, bodyB ); joint.collideConnected = collideConnected; joint.maxImpulse = maxImpulse; joint.biasFactor = biasFactor; joint.softness = softness; return joint; } } internal class FSRevoluteJointDef : FSJointDef { public Vector2 ownerBodyAnchor; public Vector2 otherBodyAnchor; public bool limitEnabled; public float lowerLimit; public float upperLimit; public bool motorEnabled; public float motorSpeed; public float maxMotorTorque; public float motorImpulse; public override Joint createJoint() { var joint = new RevoluteJoint( bodyA, bodyB, ownerBodyAnchor * FSConvert.displayToSim, otherBodyAnchor * FSConvert.displayToSim ); joint.collideConnected = collideConnected; joint.limitEnabled = limitEnabled; joint.lowerLimit = lowerLimit; joint.upperLimit = upperLimit; joint.motorEnabled = motorEnabled; joint.motorSpeed = motorSpeed; joint.maxMotorTorque = maxMotorTorque; joint.motorImpulse = motorImpulse; return joint; } } internal class FSPrismaticJointDef : FSJointDef { public Vector2 ownerBodyAnchor; public Vector2 otherBodyAnchor; public Vector2 axis = Vector2.UnitY; public bool limitEnabled; public float lowerLimit; public float upperLimit; public bool motorEnabled; public float motorSpeed = 0.7f; public float maxMotorForce = 2; public float motorImpulse; public override Joint createJoint() { var joint = new PrismaticJoint( bodyA, bodyB, ownerBodyAnchor * FSConvert.displayToSim, otherBodyAnchor * FSConvert.displayToSim ); joint.collideConnected = collideConnected; joint.axis = axis; joint.limitEnabled = limitEnabled; joint.lowerLimit = lowerLimit; joint.upperLimit = upperLimit; joint.motorEnabled = motorEnabled; joint.motorSpeed = motorSpeed; joint.maxMotorForce = maxMotorForce; joint.motorImpulse = motorImpulse; return joint; } } internal class FSRopeJointDef : FSJointDef { public Vector2 ownerBodyAnchor; public Vector2 otherBodyAnchor; public float maxLength; public override Joint createJoint() { var joint = new RopeJoint( bodyA, bodyB, ownerBodyAnchor * FSConvert.displayToSim, otherBodyAnchor * FSConvert.displayToSim ); joint.collideConnected = collideConnected; joint.maxLength = maxLength * FSConvert.displayToSim; return joint; } } internal class FSMotorJointDef : FSJointDef { public Vector2 linearOffset; public float maxForce = 1; public float maxTorque = 1; public float angularOffset; public override Joint createJoint() { var joint = new MotorJoint( bodyA, bodyB ); joint.collideConnected = collideConnected; joint.linearOffset = linearOffset * FSConvert.displayToSim; joint.maxForce = maxForce; joint.maxTorque = maxTorque; joint.angularOffset = angularOffset; return joint; } } internal class FSWheelJointDef : FSJointDef { public Vector2 anchor; public Vector2 axis = Vector2.UnitY; public bool motorEnabled; public float motorSpeed; public float maxMotorTorque; public float frequency = 2; public float dampingRatio = 0.7f; public override Joint createJoint() { var joint = new WheelJoint( bodyA, bodyB, anchor * FSConvert.displayToSim, axis ); joint.collideConnected = collideConnected; joint.axis = axis; joint.motorEnabled = motorEnabled; joint.motorSpeed = motorSpeed; joint.maxMotorTorque = maxMotorTorque; joint.frequency = frequency; joint.dampingRatio = dampingRatio; return joint; } } internal class FSPulleyJointDef : FSJointDef { public Vector2 ownerBodyAnchor; public Vector2 otherBodyAnchor; public Vector2 ownerBodyGroundAnchor; public Vector2 otherBodyGroundAnchor; public float ratio; public override Joint createJoint() { var joint = new PulleyJoint( bodyA, bodyB, ownerBodyAnchor * FSConvert.displayToSim, otherBodyGroundAnchor * FSConvert.displayToSim, ownerBodyGroundAnchor * FSConvert.displayToSim, otherBodyGroundAnchor * FSConvert.displayToSim, ratio ); joint.collideConnected = collideConnected; return joint; } } internal class FSGearJointDef : FSJointDef { public Joint ownerJoint; public Joint otherJoint; public float ratio = 1; public override Joint createJoint() { var joint = new GearJoint( bodyA, bodyB, ownerJoint, otherJoint, ratio ); joint.collideConnected = collideConnected; return joint; } } internal class FSMouseJointDef : FSJointDef { public Vector2 worldAnchor; public float maxForce; public float frequency = 5; public float dampingRatio = 0.7f; public override Joint createJoint() { var joint = new FixedMouseJoint( bodyA, worldAnchor * FSConvert.displayToSim ); joint.collideConnected = collideConnected; // conditionally set the maxForce if( maxForce > 0 ) joint.maxForce = maxForce; joint.frequency = frequency; joint.dampingRatio = dampingRatio; return joint; } } }
Blucky87/Nez
Nez.FarseerPhysics/Nez/HighLevel/InternalObjectDefs/FSJointDef.cs
C#
mit
6,807
const express = require("express") const router = express() const { createWebAPIRequest } = require("../util/util") router.get("/", (req, res) => { const cookie = req.get('Cookie') ? req.get('Cookie') : '' const id = req.query.id const data = { artistId: id, "total": true, "offset": req.query.offset, "limit": req.query.limit, "csrf_token": "" } createWebAPIRequest( 'music.163.com', `/weapi/artist/mvs`, 'POST', data, cookie, music_req => res.send(music_req), err => res.status(502).send('fetch error') ) }) module.exports = router
xfya/gitdemo
vue/vue-163-music-master/server/router/artists_mv.js
JavaScript
mit
588
require File.expand_path('../../fixtures/encoded_strings', __FILE__) describe :array_inspect, :shared => true do it "returns a string" do [1, 2, 3].send(@method).should be_kind_of(String) end it "returns '[]' for an empty Array" do [].send(@method).should == "[]" end it "calls inspect on its elements and joins the results with commas" do items = Array.new(3) do |i| obj = mock(i.to_s) obj.should_receive(:inspect).and_return(i.to_s) obj end items.send(@method).should == "[0, 1, 2]" end it "represents a recursive element with '[...]'" do ArraySpecs.recursive_array.send(@method).should == "[1, \"two\", 3.0, [...], [...], [...], [...], [...]]" ArraySpecs.head_recursive_array.send(@method).should == "[[...], [...], [...], [...], [...], 1, \"two\", 3.0]" ArraySpecs.empty_recursive_array.send(@method).should == "[[...]]" end it "taints the result if the Array is non-empty and tainted" do [1, 2].taint.send(@method).tainted?.should be_true end it "does not taint the result if the Array is tainted but empty" do [].taint.send(@method).tainted?.should be_false end it "taints the result if an element is tainted" do ["str".taint].send(@method).tainted?.should be_true end ruby_version_is "1.9" do it "untrusts the result if the Array is untrusted" do [1, 2].untrust.send(@method).untrusted?.should be_true end it "does not untrust the result if the Array is untrusted but empty" do [].untrust.send(@method).untrusted?.should be_false end it "untrusts the result if an element is untrusted" do ["str".untrust].send(@method).untrusted?.should be_true end end ruby_version_is "1.9" do it "returns a US-ASCII string for an empty Array" do [].send(@method).encoding.should == Encoding::US_ASCII end it "copies the ASCII-compatible encoding of the result of inspecting the first element" do euc_jp = mock("euc_jp") euc_jp.should_receive(:inspect).and_return("euc_jp".encode!(Encoding::EUC_JP)) utf_8 = mock("utf_8") utf_8.should_receive(:inspect).and_return("utf_8".encode!(Encoding::UTF_8)) result = [euc_jp, utf_8].send(@method) result.encoding.should == Encoding::EUC_JP result.should == "[euc_jp, utf_8]".encode(Encoding::EUC_JP) end ruby_version_is "2.0" do it "raises if inspected result is not default external encoding" do utf_16be = mock("utf_16be") utf_16be.should_receive(:inspect).and_return("utf_16be".encode!(Encoding::UTF_16BE)) lambda { [utf_16be].send(@method) }.should raise_error(Encoding::CompatibilityError) end end it "raises if inspecting two elements produces incompatible encodings" do utf_8 = mock("utf_8") utf_8.should_receive(:inspect).and_return("utf_8".encode!(Encoding::UTF_8)) utf_16be = mock("utf_16be") utf_16be.should_receive(:inspect).and_return("utf_16be".encode!(Encoding::UTF_16BE)) lambda { [utf_8, utf_16be].send(@method) }.should raise_error(Encoding::CompatibilityError) end end end
mrkn/rubyspec
core/array/shared/inspect.rb
Ruby
mit
3,128
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information using DotNetNuke.Abstractions.Portals; using DotNetNuke.Abstractions.Prompt; using DotNetNuke.Abstractions.Users; using DotNetNuke.Entities.Modules.Definitions; using DotNetNuke.Prompt; using DotNetNuke.Security.Permissions; using System; using System.Collections.Generic; using System.Linq; namespace DotNetNuke.Entities.Modules.Prompt { /// <summary> /// This is a (Prompt) Console Command. You should not reference this class directly. It is to be used solely through Prompt. /// </summary> [ConsoleCommand("list-modules", Constants.CommandCategoryKeys.Modules, "Prompt_ListModules_Description")] public class ListModules : ConsoleCommand { /// <inheritdoc/> public override string LocalResourceFile => Constants.DefaultPromptResourceFile; [ConsoleCommandParameter("pageid", "Prompt_ListModules_FlagPageId")] public int? PageId { get; set; } = -1; [ConsoleCommandParameter("page", "Prompt_ListModules_FlagPage", "1")] public int Page { get; set; } = 1; [ConsoleCommandParameter("max", "Prompt_ListModules_FlagMax", "10")] public int Max { get; set; } = 10; [ConsoleCommandParameter("name", "Prompt_ListModules_FlagModuleName")] public string ModuleName { get; set; } [ConsoleCommandParameter("title", "Prompt_ListModules_FlagModuleTitle")] public string ModuleTitle { get; set; } [ConsoleCommandParameter("deleted", "Prompt_ListModules_FlagDeleted")] public bool? Deleted { get; set; } /// <inheritdoc/> public override void Initialize(string[] args, IPortalSettings portalSettings, IUserInfo userInfo, int activeTabId) { base.Initialize(args, portalSettings, userInfo, activeTabId); this.ParseParameters(this); } /// <inheritdoc/> public override IConsoleResultModel Run() { var max = this.Max <= 0 ? 10 : (this.Max > 500 ? 500 : this.Max); int total; var portalDesktopModules = DesktopModuleController.GetPortalDesktopModules(this.PortalId); var pageIndex = (this.Page > 0 ? this.Page - 1 : 0); pageIndex = pageIndex < 0 ? 0 : pageIndex; var pageSize = this.Max; pageSize = pageSize > 0 && pageSize <= 100 ? pageSize : 10; this.ModuleName = this.ModuleName?.Replace("*", ""); this.ModuleTitle = this.ModuleTitle?.Replace("*", ""); var modules = ModuleController.Instance.GetModules(this.PortalSettings.PortalId) .Cast<ModuleInfo>().Where(ModulePermissionController.CanViewModule); if (!string.IsNullOrEmpty(this.ModuleName)) modules = modules.Where(module => module.DesktopModule.ModuleName.IndexOf(this.ModuleName, StringComparison.OrdinalIgnoreCase) >= 0); if (!string.IsNullOrEmpty(this.ModuleTitle)) modules = modules.Where(module => module.ModuleTitle.IndexOf(this.ModuleTitle, StringComparison.OrdinalIgnoreCase) >= 0); // Return only deleted modules with matching criteria. if (this.PageId.HasValue && this.PageId.Value > 0) { modules = modules.Where(x => x.TabID == this.PageId.Value); } if (this.Deleted.HasValue) { modules = modules.Where(module => module.IsDeleted == this.Deleted); } // Get distincts. modules = modules.GroupBy(x => x.ModuleID).Select(group => group.First()).OrderBy(x => x.ModuleID); var moduleInfos = modules as IList<ModuleInfo> ?? modules.ToList(); total = moduleInfos.Count; modules = moduleInfos.Skip(pageIndex * pageSize).Take(pageSize) .Where(m => { var moduleDefinition = ModuleDefinitionController.GetModuleDefinitionByID(m.ModuleDefID); return portalDesktopModules.Any(kvp => kvp.Value.DesktopModuleID == moduleDefinition?.DesktopModuleID); }); var results = modules.Select(x => PromptModuleInfo.FromDnnModuleInfo(x, this.Deleted)); var totalPages = total / max + (total % max == 0 ? 0 : 1); var pageNo = this.Page > 0 ? this.Page : 1; return new ConsoleResultModel { Data = results, PagingInfo = new PagingInfo { PageNo = pageNo, TotalPages = totalPages, TotalRecords = total, PageSize = max, }, Records = results.Count(), Output = results.Count() == 0 ? this.LocalizeString("Prompt_NoModules") : "", }; } } }
dnnsoftware/Dnn.Platform
DNN Platform/Library/Entities/Modules/Prompt/ListModules.cs
C#
mit
5,038
/*! * jQuery JavaScript Library v1.8.1 -effects,-dimensions * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Sun Sep 23 2012 11:00:04 GMT-0700 (PDT) */ (function( window, undefined ) { var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, navigator = window.navigator, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // Save a reference to some core methods core_push = Array.prototype.push, core_slice = Array.prototype.slice, core_indexOf = Array.prototype.indexOf, core_toString = Object.prototype.toString, core_hasOwn = Object.prototype.hasOwnProperty, core_trim = String.prototype.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 detecting and trimming whitespace core_rnotwhite = /\S/, core_rspace = /\s+/, // 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) 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*\.|)\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 and self cleanup method DOMContentLoaded = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false ); jQuery.ready(); } else if ( document.readyState === "complete" ) { // we're here because readyState === "complete" in oldIE // which is good enough for us to call the dom ready! document.detachEvent( "onreadystatechange", DOMContentLoaded ); jQuery.ready(); } }, // [[Class]] -> type pairs class2type = {}; jQuery.fn = jQuery.prototype = { constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem, ret, doc; // Handle $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle $(DOMElement) if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; 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; doc = ( context && context.nodeType ? context.ownerDocument || context : document ); // scripts is true for back-compat selector = jQuery.parseHTML( match[1], doc, true ); if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { this.attr.call( selector, context, true ); } return jQuery.merge( this, selector ); // 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: $(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 current version of jQuery being used jquery: "1.8.1 -effects,-dimensions", // 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, name, selector ) { // 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; if ( name === "find" ) { ret.selector = this.selector + ( this.selector ? " " : "" ) + selector; } else if ( name ) { ret.selector = this.selector + "." + name + "(" + selector + ")"; } // 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; }, eq: function( i ) { i = +i; return i === -1 ? this.slice( i ) : this.slice( i, i + 1 ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ), "slice", core_slice.call(arguments).join(",") ); }, 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 options, name, src, copy, copyIsArray, 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, 1 ); } // 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 ) { return obj == null ? String( obj ) : class2type[ core_toString.call(obj) ] || "object"; }, 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 // scripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, scripts ) { var parsed; if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { scripts = context; context = 0; } context = context || document; // Single tag if ( (parsed = rsingleTag.exec( data )) ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] ); return jQuery.merge( [], (parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes ); }, parseJSON: function( data ) { if ( !data || typeof data !== "string") { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( 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 && core_rnotwhite.test( 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.toUpperCase() === name.toUpperCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var name, i = 0, length = obj.length, isObj = length === undefined || jQuery.isFunction( obj ); if ( args ) { if ( isObj ) { for ( name in obj ) { if ( callback.apply( obj[ name ], args ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.apply( obj[ i++ ], args ) === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isObj ) { for ( name in obj ) { if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) { break; } } } else { for ( ; i < length; ) { if ( callback.call( obj[ i ], i, obj[ i++ ] ) === 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.toString().replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var type, ret = results || []; if ( arr != null ) { // The window, strings (and functions) also have 'length' // Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930 type = jQuery.type( arr ); if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) { core_push.call( ret, arr ); } else { jQuery.merge( 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, key, ret = [], i = 0, length = elems.length, // jquery objects are treated as arrays isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ; // 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 ( key in elems ) { value = callback( elems[ key ], key, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return ret.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 tmp, args, proxy; 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, 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 || proxy.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, pass ) { var exec, bulk = key == null, i = 0, length = elems.length; // Sets many values if ( key && typeof key === "object" ) { for ( i in key ) { jQuery.access( elems, fn, i, key[i], 1, emptyGet, value ); } chainable = 1; // Sets one value } else if ( value !== undefined ) { // Optionally, function values get executed if exec is true exec = pass === undefined && jQuery.isFunction( value ); if ( bulk ) { // Bulk operations only iterate when executing function values if ( exec ) { exec = fn; fn = function( elem, key, value ) { return exec.call( jQuery( elem ), value ); }; // Otherwise they run against the entire set } else { fn.call( elems, value ); fn = null; } } if ( fn ) { for (; i < length; i++ ) { fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass ); } } chainable = 1; } 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, 1 ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", jQuery.ready, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", DOMContentLoaded ); // A fallback to window.onload, that will always work window.attachEvent( "onload", jQuery.ready ); // 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 ); } // 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".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); // 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.split( core_rspace ), 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 // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // 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" && ( !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; }, // Control if a given callback is in the list has: function( fn ) { return jQuery.inArray( fn, list ) > -1; }, // 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 = fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ]( jQuery.isFunction( fn ) ? function() { var returned = 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 === deferred ? newDefer : this, [ returned ] ); } } : newDefer[ action ] ); }); 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 typeof obj === "object" ? 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 ] = list.fire deferred[ tuple[0] ] = list.fire; 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, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div"); // Preliminary tests div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; // Can't get basic test support if ( !all || !all.length || !a ) { return {}; } // First batch of supports tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; support = { // 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, // Make sure that if no value is specified for a checkbox // that it defaults to "on". // (WebKit defaults to "" instead) checkOn: ( input.value === "on" ), // 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, // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // 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 submitBubbles: true, changeBubbles: true, focusinBubbles: false, 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; // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete div.test; } catch( e ) { support.deleteExpando = false; } if ( !div.addEventListener && div.attachEvent && div.fireEvent ) { div.attachEvent( "onclick", clickFn = function() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) support.noCloneEvent = false; }); div.cloneNode( true ).fireEvent("onclick"); div.detachEvent( "onclick", clickFn ); } // Check if a radio maintains its value // after being appended to the DOM input = document.createElement("input"); input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; input.setAttribute( "checked", "checked" ); // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "name", "t" ); div.appendChild( input ); fragment = document.createDocumentFragment(); fragment.appendChild( div.lastChild ); // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; fragment.removeChild( input ); fragment.appendChild( div ); // Technique from Juriy Zaytsev // http://perfectionkills.com/detecting-event-support-without-browser-sniffing/ // We only care about the case where non-standard event systems // are used, namely in IE. Short-circuiting here helps us to // avoid an eval call (in setAttribute) which can cause CSP // to go haywire. See: https://developer.mozilla.org/en/Security/CSP if ( div.attachEvent ) { for ( i in { submit: true, change: true, focusin: true }) { eventName = "on" + i; isSupported = ( eventName in div ); if ( !isSupported ) { div.setAttribute( eventName, "return;" ); isSupported = ( typeof div[ eventName ] === "function" ); } support[ i + "Bubbles" ] = isSupported; } } // Run tests that need a body at doc ready jQuery(function() { var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;", 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 = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px"; body.insertBefore( container, body.firstChild ); // Construct the test element div = document.createElement("div"); container.appendChild( div ); // 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). // (only IE 8 fails this test) 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"; // Check if empty table cells still have offsetWidth/Height // (IE <= 8 fail this test) 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 ); // NOTE: To any future maintainer, we've 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. For more // info see bug #3333 // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = document.createElement("div"); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; div.appendChild( marginDiv ); support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== "undefined" ) { // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout // (IE < 8 does this) div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Check if elements with layout shrink-wrap their children // (IE 6 does this) div.style.display = "block"; div.style.overflow = "visible"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); container.style.zoom = 1; } // Null elements to avoid leaks in IE body.removeChild( container ); container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE fragment.removeChild( div ); all = a = select = opt = input = fragment = div = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; jQuery.extend({ cache: {}, deletedIds: [], // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( jQuery.fn.jquery + 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, 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 = jQuery.deletedIds.pop() || ++jQuery.uuid; } 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; }, removeData: function( elem, name, pvt /* Internal Use Only */ ) { if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, i, l, 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(" "); } } } 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; } }, // For internal use only. _data: function( elem, name, data ) { return jQuery.data( elem, name, data, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { 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 parts, part, attr, name, l, 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" ) ) { attr = elem.attributes; for ( l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.substring(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 ); }); } parts = key.split( ".", 2 ); parts[1] = parts[1] ? "." + parts[1] : ""; part = parts[1] + "!"; return jQuery.access( this, function( value ) { if ( value === undefined ) { data = this.triggerHandler( "getData" + part, [ parts[0] ] ); // Try to fetch any internally stored data first if ( data === undefined && elem ) { data = jQuery.data( elem, key ); data = dataAttr( elem, key, data ); } return data === undefined && parts[1] ? this.data( parts[0] ) : data; } parts[1] = value; this.each(function() { var self = jQuery( this ); self.triggerHandler( "setData" + part, parts ); jQuery.data( this, key, value ); self.triggerHandler( "changeData" + part, parts ); }); }, null, value, arguments.length > 1, null, false ); }, 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--; } 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", true ); jQuery.removeData( elem, key, true ); }) }); } }); 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, fixSpecified, rclass = /[\t\r\n]/g, rreturn = /\r/g, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea|)$/i, rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute; 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 classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { var removes, className, elem, c, cl, i, l; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call(this, j, this.className) ); }); } if ( (value && typeof value === "string") || value === undefined ) { removes = ( value || "" ).split( core_rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 && elem.className ) { className = (" " + elem.className + " ").replace( rclass, " " ); // loop over each item in the removal list for ( c = 0, cl = removes.length; c < cl; c++ ) { // Remove until there is nothing to remove, while ( className.indexOf(" " + removes[ c ] + " ") > -1 ) { className = className.replace( " " + removes[ c ] + " " , " " ); } } elem.className = value ? jQuery.trim( className ) : ""; } } } 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.split( core_rspace ); while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } } else if ( type === "undefined" || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // toggle whole className 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 ) > -1 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, 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, i, max, option, index = elem.selectedIndex, values = [], options = elem.options, one = elem.type === "select-one"; // Nothing was selected if ( index < 0 ) { return null; } // Loop through all the selected options i = one ? index : 0; max = one ? index + 1 : options.length; for ( ; i < max; i++ ) { option = options[ i ]; // Don't return options that are disabled or in a disabled optgroup if ( option.selected && (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 ); } } // Fixes Bug #2551 -- select.val() broken in IE after form.reset() if ( one && !values.length && options.length ) { return jQuery( options[ index ] ).val(); } 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; } } }, // Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9 attrFn: {}, attr: function( elem, name, value, pass ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) { return jQuery( elem )[ name ]( value ); } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { 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 ); return; } else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, "" + value ); return value; } } else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return ret === null ? undefined : ret; } }, removeAttr: function( elem, value ) { var propName, attrNames, name, isBool, i = 0; if ( value && elem.nodeType === 1 ) { attrNames = value.split( core_rspace ); for ( ; i < attrNames.length; i++ ) { name = attrNames[ i ]; if ( name ) { propName = jQuery.propFix[ name ] || name; isBool = rboolean.test( name ); // See #9699 for explanation of this approach (setting first, then removal) // Do not do this for boolean attributes (see #10870) if ( !isBool ) { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); // Set corresponding property to false for boolean attributes if ( isBool && propName in elem ) { elem[ propName ] = false; } } } } }, attrHooks: { type: { set: function( elem, value ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } else 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 it's default in case type is set after value // This is for element creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } }, // Use the value property for back compat // Use the nodeHook for button elements in IE6/7 (#1954) value: { get: function( elem, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.get( elem, name ); } return name in elem ? elem.value : null; }, set: function( elem, value, name ) { if ( nodeHook && jQuery.nodeName( elem, "button" ) ) { return nodeHook.set( elem, value, name ); } // Does not return so that setAttribute is also used elem.value = 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 ) { // Align boolean attributes with corresponding properties // Fall back to attribute presence where some booleans are not supported var attrNode, property = jQuery.prop( elem, name ); return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { var propName; if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { // value is true since we know at this point it's type boolean and not false // Set boolean attributes to the same name and set the DOM property propName = jQuery.propFix[ name ] || name; if ( propName in elem ) { // Only set the IDL specifically if it already exists on the element elem[ propName ] = true; } elem.setAttribute( name, name.toLowerCase() ); } return name; } }; // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { fixSpecified = { name: true, id: true, coords: true }; // 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; ret = elem.getAttributeNode( name ); return ret && ( fixSpecified[ name ] ? 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 ) { ret = document.createAttribute( name ); elem.setAttributeNode( ret ); } return ( ret.value = value + "" ); } }; // 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; } } }); }); // 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 ) { if ( value === "" ) { value = "false"; } nodeHook.set( elem, value, name ); } }; } // Some attributes require a special call on IE 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; } }); }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Normalize to lowercase since IE uppercases css property names return elem.style.cssText.toLowerCase() || 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 = /^(?:textarea|input|select)$/i, rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/, rhoverHack = /(?:^|\s)hover(\.\S+|)\b/, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, hoverHack = function( events ) { return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" ); }; /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { add: function( elem, types, handler, data, selector ) { var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special; // Don't attach events to noData or text/comment nodes (allow plain objects tho) if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) { 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 events = elemData.events; if ( !events ) { elemData.events = events = {}; } eventHandle = elemData.handle; if ( !eventHandle ) { elemData.handle = eventHandle = 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 !== "undefined" && (!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 = jQuery.trim( hoverHack(types) ).split( " " ); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = tns[1]; namespaces = ( tns[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: tns[1], data: data, handler: handler, guid: handler.guid, selector: selector, namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first handlers = events[ type ]; if ( !handlers ) { 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; }, global: {}, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, 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 = jQuery.trim( hoverHack( types || "" ) ).split(" "); for ( t = 0; t < types.length; t++ ) { tns = rtypenamespace.exec( types[t] ) || []; type = origType = tns[1]; namespaces = tns[2]; // 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; eventType = events[ type ] || []; origCount = eventType.length; namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null; // Remove matching events for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !namespaces || namespaces.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { eventType.splice( j--, 1 ); if ( handleObj.selector ) { eventType.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 ( eventType.length === 0 && origCount !== eventType.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", true ); } }, // Events that are safe to short-circuit if no handlers are attached. // Native DOM events should not be added, they may have inline handlers. customEvent: { "getData": true, "setData": true, "changeData": true }, trigger: function( event, data, elem, onlyHandlers ) { // Don't do events on text and comment nodes if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) { return; } // Event object or event type var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event, namespaces = []; // 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 ) { // Exclusive events trigger only for the exact event (no namespaces) type = type.slice(0, -1); exclusive = true; } if ( type.indexOf( "." ) >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) { // No jQuery handlers for this event type, and it can't have inline handlers return; } // Caller can pass in an Event, Object, or just an event type string event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal new jQuery.Event( type, event ) : // Just the event type (string) new jQuery.Event( type ); event.type = type; event.isTrigger = true; event.exclusive = exclusive; event.namespace = namespaces.join( "." ); event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null; ontype = type.indexOf( ":" ) < 0 ? "on" + type : ""; // Handle a global trigger if ( !elem ) { // TODO: Stop taunting the data cache; remove global events and always attach to document cache = jQuery.cache; for ( i in cache ) { if ( cache[ i ].events && cache[ i ].events[ type ] ) { jQuery.event.trigger( event, data, cache[ i ].handle.elem, true ); } } return; } // 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 ? jQuery.makeArray( data ) : []; data.unshift( event ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( 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) eventPath = [[ elem, special.bindType || type ]]; if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode; for ( old = elem; cur; cur = cur.parentNode ) { eventPath.push([ cur, bubbleType ]); old = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( old === (elem.ownerDocument || document) ) { eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]); } } // Fire handlers on the event path for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) { cur = eventPath[i][0]; event.type = eventPath[i][1]; handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Note that this is a bare JS function and not a jQuery handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && 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) // IE<9 dies on focus/blur to hidden element (#1486) if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method old = elem[ ontype ]; if ( old ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( old ) { elem[ ontype ] = old; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event || window.event ); var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []), delegateCount = handlers.delegateCount, args = [].slice.call( arguments ), run_all = !event.exclusive && !event.namespace, special = jQuery.event.special[ event.type ] || {}, handlerQueue = []; // 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 that should run if there are delegated events // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && !(event.button && event.type === "click") ) { for ( cur = event.target; cur != this; cur = cur.parentNode || this ) { // Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { selMatch = {}; matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; sel = handleObj.selector; if ( selMatch[ sel ] === undefined ) { selMatch[ sel ] = jQuery( sel, this ).index( cur ) >= 0; } if ( selMatch[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, matches: matches }); } } } } // Add the remaining (directly-bound) handlers if ( handlers.length > delegateCount ) { handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) }); } // Run delegates first; they may want to stop propagation beneath us for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) { matched = handlerQueue[ i ]; event.currentTarget = matched.elem; for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) { handleObj = matched.matches[ j ]; // Triggered event must either 1) be non-exclusive and have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) { event.data = handleObj.data; event.handleObj = handleObj; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { event.result = ret; if ( 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; }, // Includes some event props shared by KeyEvent and MouseEvent // *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 *** props: "attrChange attrName relatedNode srcElement 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 eventDoc, doc, body, 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; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, originalEvent = event, fixHook = jQuery.event.fixHooks[ event.type ] || {}, copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = jQuery.Event( originalEvent ); for ( i = copy.length; i; ) { prop = copy[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary (#1925, IE 6/7/8 & Safari2) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Target should not be a text node (#504, Safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8) event.metaKey = !!event.metaKey; return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { delegateType: "focusin" }, blur: { delegateType: "focusout" }, beforeunload: { setup: function( data, namespaces, eventHandle ) { // We only want to do this special case on windows if ( jQuery.isWindow( this ) ) { this.onbeforeunload = eventHandle; } }, teardown: function( namespaces, eventHandle ) { if ( this.onbeforeunload === eventHandle ) { this.onbeforeunload = null; } } } }, 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(); } } }; // Some plugins are using, but it's undocumented/deprecated and will be removed. // The 1.7 special event interface should provide all the hooks needed now. jQuery.event.handle = jQuery.event.dispatch; 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 ] === "undefined" ) { 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; }; function returnFalse() { return false; } function returnTrue() { return 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 = { preventDefault: function() { this.isDefaultPrevented = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if preventDefault exists run it on the original event if ( e.preventDefault ) { e.preventDefault(); // otherwise set the returnValue property of the original event to false (IE) } else { e.returnValue = false; } }, stopPropagation: function() { this.isPropagationStopped = returnTrue; var e = this.originalEvent; if ( !e ) { return; } // if stopPropagation exists run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // otherwise set the cancelBubble property of the original event to true (IE) e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); }, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse }; // 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, selector = handleObj.selector; // 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, "_submit_attached" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "_submit_attached", 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, "_change_attached" ) ) { 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, "_change_attached", 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 origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // && selector != null // ( 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 ); }, live: function( types, data, fn ) { jQuery( this.context ).on( types, this.selector, data, fn ); return this; }, die: function( types, fn ) { jQuery( this.context ).off( types, this.selector || "**", fn ); return this; }, 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 ) { if ( this[0] ) { return jQuery.event.trigger( type, data, this[0], true ); } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, guid = fn.guid || jQuery.guid++, i = 0, toggler = function( event ) { // Figure out which function to execute var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i; jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 ); // Make sure that clicks stop event.preventDefault(); // and execute the function return args[ lastToggle ].apply( this, arguments ) || false; }; // link all the functions, so any of them can unbind this click handler toggler.guid = guid; while ( i < args.length ) { args[ i++ ].guid = guid; } return this.click( toggler ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); 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 ) { if ( fn == null ) { fn = data; data = null; } return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; if ( rkeyEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks; } if ( rmouseEvent.test( name ) ) { jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks; } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true, strundefined = "undefined", expando = ( "sizcache" + Math.random() ).replace( ".", "" ), Token = String, document = window.document, docElem = document.documentElement, dirruns = 0, done = 0, pop = [].pop, push = [].push, slice = [].slice, // Use a stripped-down indexOf if a native one is unavailable indexOf = [].indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Augment a function for special use by Sizzle markFunction = function( fn, value ) { fn[ expando ] = value == null || value; return fn; }, createCache = function() { var cache = {}, keys = []; return markFunction(function( key, value ) { // Only keep the most recent entries if ( keys.push( key ) > Expr.cacheLength ) { delete cache[ keys.shift() ]; } return (cache[ key ] = value); }, cache ); }, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // Regex // 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 not in parens/brackets, // then attribute selectors and non-pseudos (denoted by :), // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)", // For matchExpr.POS and matchExpr.needsContext pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", // 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 ), // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/, rnot = /^:not/, rsibling = /[\x20\t\r\n\f]*[+~]/, rendsWithNot = /:not\($/, rheader = /h\d/i, rinputs = /input|select|textarea|button/i, rbackslash = /\\(?!\\)/g, 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 ), "POS": new RegExp( pos, "i" ), "CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() "needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" ) }, // Support // Used for testing something on an element assert = function( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } }, // Check if getElementsByTagName("*") returns only elements assertTagNameNoComments = assert(function( div ) { div.appendChild( document.createComment("") ); return !div.getElementsByTagName("*").length; }), // Check if getAttribute returns normalized href attributes assertHrefNotNormalized = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }), // Check if attributes should be retrieved by attribute nodes assertAttributes = 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 assertUsableClassName = 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 assertUsableName = 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 = document.getElementsByName && // buggy browsers will return fewer than the correct 2 document.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 document.getElementsByName( expando + 0 ).length; assertGetIdNotName = !document.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // If slice is not available, provide a backup try { slice.call( docElem.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; for ( ; (elem = this[i]); i++ ) { results.push( elem ); } return results; }; } function Sizzle( selector, context, results, seed ) { results = results || []; context = context || document; var match, elem, xml, m, nodeType = context.nodeType; if ( !selector || typeof selector !== "string" ) { return results; } if ( nodeType !== 1 && nodeType !== 9 ) { return []; } xml = isXML( context ); if ( !xml && !seed ) { 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]) && assertUsableClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed, xml ); } Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { return Sizzle( expr, null, null, [ elem ] ).length > 0; }; // 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 ( 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 } else { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } return ret; }; 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; }; // Element contains another contains = Sizzle.contains = docElem.contains ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) ); } : docElem.compareDocumentPosition ? function( a, b ) { return b && !!( a.compareDocumentPosition( b ) & 16 ); } : function( a, b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } return false; }; Sizzle.attr = function( elem, name ) { var val, xml = isXML( elem ); if ( !xml ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( xml || assertAttributes ) { return elem.getAttribute( name ); } val = elem.getAttributeNode( name ); return val ? typeof elem[ name ] === "boolean" ? elem[ name ] ? name : null : val.specified ? val.value : null : null; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, // IE6/7 return a modified href attrHandle: assertHrefNotNormalized ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }, find: { "ID": assertGetIdNotName ? function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { 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] : []; } } : function( id, context, xml ) { if ( typeof context.getElementById !== strundefined && !xml ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }, "TAG": assertTagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { var elem, tmp = [], i = 0; for ( ; (elem = results[i]); i++ ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }, "NAME": assertUsableName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }, "CLASS": assertUsableClassName && function( className, context, xml ) { if ( typeof context.getElementsByClassName !== strundefined && !xml ) { return context.getElementsByClassName( className ); } } }, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( rbackslash, "" ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 3 xn-component of xn+y argument ([+-]?\d*n|) 4 sign of xn-component 5 x of xn-component 6 sign of y-component 7 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1] === "nth" ) { // nth-child requires argument if ( !match[2] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) ); match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" ); // other types prohibit arguments } else if ( match[2] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var unquoted, excess; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } if ( match[3] ) { match[2] = match[3]; } else if ( (unquoted = match[4]) ) { // Only check arguments that contain a pseudo if ( 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 unquoted = unquoted.slice( 0, excess ); match[0] = match[0].slice( 0, excess ); } match[2] = unquoted; } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "ID": assertGetIdNotName ? function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { return elem.getAttribute("id") === id; }; } : function( id ) { id = id.replace( rbackslash, "" ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === id; }; }, "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( rbackslash, "" ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ expando ][ className ]; if ( !pattern ) { pattern = classCache( className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)") ); } return function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }; }, "ATTR": function( name, operator, check ) { return function( elem, context ) { 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.substr( result.length - check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, argument, first, last ) { if ( type === "nth" ) { return function( elem ) { var node, diff, parent = elem.parentNode; if ( first === 1 && last === 0 ) { return true; } if ( parent ) { diff = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { diff++; if ( elem === node ) { break; } } } } // Incorporate the offset (or cast to NaN), then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); }; } return function( elem ) { var node = elem; switch ( type ) { case "only": case "first": while ( (node = node.previousSibling) ) { if ( node.nodeType === 1 ) { return false; } } if ( type === "first" ) { return true; } node = elem; /* falls through */ case "last": while ( (node = node.nextSibling) ) { if ( node.nodeType === 1 ) { return false; } } return true; } }; }, "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: { "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; }; }), "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; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, "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 "?") var nodeType; elem = elem.firstChild; while ( elem ) { if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) { return false; } elem = elem.nextSibling; } return true; }, "header": function( elem ) { return rheader.test( elem.nodeName ); }, "text": function( elem ) { var type, 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" && (type = elem.type) === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type ); }, // Input types "radio": createInputPseudo("radio"), "checkbox": createInputPseudo("checkbox"), "file": createInputPseudo("file"), "password": createInputPseudo("password"), "image": createInputPseudo("image"), "submit": createButtonPseudo("submit"), "reset": createButtonPseudo("reset"), "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "focus": function( elem ) { var doc = elem.ownerDocument; return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href); }, "active": function( elem ) { return elem === elem.ownerDocument.activeElement; }, // Positional types "first": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = 0; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = 1; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; function siblingCheck( a, b, ret ) { if ( a === b ) { return ret; } var cur = a.nextSibling; while ( cur ) { if ( cur === b ) { return -1; } cur = cur.nextSibling; } return 1; } sortOrder = docElem.compareDocumentPosition ? function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return ( !a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4 ) ? -1 : 1; } : function( a, b ) { // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // Fallback to using sourceIndex (in IE) if it's available on both nodes } else if ( a.sourceIndex && b.sourceIndex ) { return a.sourceIndex - b.sourceIndex; } var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // If the nodes are siblings (or identical) we can do a quick check if ( aup === bup ) { return siblingCheck( a, b ); // If no parents were found then the nodes are disconnected } else if ( !aup ) { return -1; } else if ( !bup ) { return 1; } // Otherwise they're somewhere else in the tree so we need // to build up a full list of the parentNodes for comparison while ( cur ) { ap.unshift( cur ); cur = cur.parentNode; } cur = bup; while ( cur ) { bp.unshift( cur ); cur = cur.parentNode; } al = ap.length; bl = bp.length; // Start walking down the tree looking for a discrepancy for ( var i = 0; i < al && i < bl; i++ ) { if ( ap[i] !== bp[i] ) { return siblingCheck( ap[i], bp[i] ); } } // We ended someplace up the tree so do a sibling check return i === al ? siblingCheck( a, bp[i], -1 ) : siblingCheck( ap[i], b, 1 ); }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). [0, 0].sort( sortOrder ); baseHasDuplicate = !hasDuplicate; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, i = 1; hasDuplicate = baseHasDuplicate; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { results.splice( i--, 1 ); } } } return results; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ expando ][ 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 ) { soFar = soFar.slice( match[0].length ); } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); // Cast descendant combinators to space matched.type = match[0].replace( rtrim, " " ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || // The last two arguments here are (context, xml) for backCompat (match = preFilters[ type ]( match, document, true ))) ) { tokens.push( matched = new Token( match.shift() ) ); soFar = soFar.slice( matched.length ); matched.type = type; matched.matches = match; } } 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 addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && combinator.dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( !xml ) { var cache, dirkey = dirruns + " " + doneName + " ", cachedkey = dirkey + cachedruns; while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( (cache = elem[ expando ]) === cachedkey ) { return elem.sizset; } else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) { if ( elem.sizset ) { return elem; } } else { elem[ expando ] = cachedkey; if ( matcher( elem, context, xml ) ) { elem.sizset = true; return elem; } elem.sizset = false; } } } } else { while ( (elem = elem[ dir ]) ) { if ( checkNonElements || elem.nodeType === 1 ) { if ( matcher( elem, context, xml ) ) { return elem; } } } } }; } 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 ) { // Positional selectors apply to seed elements, so it is invalid to follow them with relative ones if ( seed && postFinder ) { return; } var i, elem, postFilterIn, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [], seed ), // 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 ) { postFilterIn = condense( matcherOut, postMap ); postFilter( postFilterIn, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = postFilterIn.length; while ( i-- ) { if ( (elem = postFilterIn[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } // Keep seed and results synchronized if ( seed ) { // Ignore postFinder because it can't coexist with seed i = preFilter && matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { seed[ preMap[i] ] = !(results[ preMap[i] ] = elem); } } } 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 { // The concatenated values are (context, xml) for backCompat 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 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && tokens.join("") ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, 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 ), // Nested matchers should use non-integer dirruns dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E); if ( outermost ) { outermostContext = context !== document && context; cachedruns = superMatcher.el; } // Add elements passing elementMatchers directly to results for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { for ( j = 0; (matcher = elementMatchers[j]); j++ ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++superMatcher.el; } } // 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 ) { for ( j = 0; (matcher = setMatchers[j]); 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; }; superMatcher.el = 0; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ expando ][ 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, seed ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results, seed ); } return results; } function select( selector, context, results, seed, xml ) { var i, tokens, token, type, find, match = tokenize( selector ), j = match.length; 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 && !xml && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().length ); } // Fetch a seed set for right-to-left matching for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; 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( rbackslash, "" ), rsibling.test( tokens[0].type ) && context.parentNode || context, xml )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && tokens.join(""); 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, xml, results, rsibling.test( selector ) ); return results; } if ( document.querySelectorAll ) { (function() { var disconnectedMatch, oldSelect = select, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // qSa(:focus) reports false when true (Chrome 21), // A support test would require too much code (would include document ready) rbuggyQSA = [":focus"], // matchesSelector(:focus) reports false when true (Chrome 21), // matchesSelector(:active) reports false when true (IE9/Opera 11.5) // A support test would require too much code (would include document ready) // just skip matchesSelector for :active rbuggyMatches = [ ":active", ":focus" ], matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector; // 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 (do not put tests after this one) if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE9 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<p test=''></p>"; if ( div.querySelectorAll("[test^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here (do not put tests after this one) div.innerHTML = "<input type='hidden'/>"; if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push(":enabled", ":disabled"); } }); // rbuggyQSA always contains :focus, so no need for a length check rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") ); select = function( selector, context, results, seed, xml ) { // Only use querySelectorAll when not filtering, // when this is not xml, // and when no QSA bugs apply if ( !seed && !xml && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { var groups, i, old = true, nid = expando, newContext = context, newSelector = context.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 ( context.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 + groups[i].join(""); } 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"); } } } } return oldSelect( selector, context, results, seed, xml ); }; if ( matches ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead try { matches.call( div, "[test!='']:sizzle" ); rbuggyMatches.push( "!=", pseudos ); } catch ( e ) {} }); // rbuggyMatches always contains :active and :focus, so no need for a length check rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") ); Sizzle.matchesSelector = function( elem, expr ) { // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyMatches always contains :active, so no need for an existence check if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && (!rbuggyQSA || !rbuggyQSA.test( expr )) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || 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, null, null, [ elem ] ).length > 0; }; } })(); } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Back-compat function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // 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, l, length, n, r, ret, self = this; if ( typeof selector !== "string" ) { return jQuery( selector ).filter(function() { for ( i = 0, l = self.length; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }); } ret = this.pushStack( "", "find", selector ); for ( i = 0, l = this.length; i < l; i++ ) { length = ret.length; jQuery.find( selector, this[i], ret ); if ( i > 0 ) { // Make sure that the results are unique for ( n = length; n < ret.length; n++ ) { for ( r = 0; r < length; r++ ) { if ( ret[r] === ret[n] ) { ret.splice(n--, 1); break; } } } } } 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), "not", selector); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true), "filter", selector ); }, 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; } } ret = ret.length > 1 ? jQuery.unique( ret ) : ret; return this.pushStack( ret, "closest", selectors ); }, // 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.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( isDisconnected( set[0] ) || isDisconnected( all[0] ) ? all : jQuery.unique( all ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; // A painfully simple check to see if an element is disconnected // from a document (should be improved, where feasible). function isDisconnected( node ) { return !node || !node.parentNode || node.parentNode.nodeType === 11; } 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, name, core_slice.call( arguments ).join(",") ); }; }); 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, i ) { 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, i ) { 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, 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, rnocache = /<(?:script|object|embed|option|style)/i, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rcheckableType = /^(?:checkbox|radio)$/, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /\/(java|ecma)script/i, rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g, wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], area: [ 1, "<map>", "</map>" ], _default: [ 0, "", "" ] }, 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; // 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. if ( !jQuery.support.htmlSerialize ) { wrapMap._default = [ 1, "X<div>", "</div>" ]; } 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.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( set, this ), "before", this.selector ); } }, after: function() { if ( !isDisconnected( this[0] ) ) { return this.domManip(arguments, false, function( elem ) { this.parentNode.insertBefore( elem, this.nextSibling ); }); } if ( arguments.length ) { var set = jQuery.clean( arguments ); return this.pushStack( jQuery.merge( this, set ), "after", this.selector ); } }, // 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 ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( elem.getElementsByTagName("*") ); jQuery.cleanData( [ elem ] ); } if ( elem.parentNode ) { 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( elem.getElementsByTagName("*") ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } } 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( elem.getElementsByTagName( "*" ) ); 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 ) { if ( !isDisconnected( this[0] ) ) { // 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 ( jQuery.isFunction( value ) ) { return this.each(function(i) { var self = jQuery(this), old = self.html(); self.replaceWith( value.call( this, i, old ) ); }); } if ( typeof value !== "string" ) { value = jQuery( value ).detach(); } return this.each(function() { var next = this.nextSibling, parent = this.parentNode; jQuery( this ).remove(); if ( next ) { jQuery(next).before( value ); } else { jQuery(parent).append( value ); } }); } return this.length ? this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) : this; }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = [].concat.apply( [], args ); var results, first, fragment, iNoClone, i = 0, value = args[0], scripts = [], l = this.length; // We can't cloneNode fragments that contain checked, in WebKit if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) { return this.each(function() { jQuery(this).domManip( args, table, callback ); }); } if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); args[0] = value.call( this, i, table ? self.html() : undefined ); self.domManip( args, table, callback ); }); } if ( this[0] ) { results = jQuery.buildFragment( args, this, scripts ); fragment = results.fragment; first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). // Fragments from the fragment cache must always be cloned and never used in place. for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) { callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], i === iNoClone ? fragment : jQuery.clone( fragment, true, true ) ); } } // Fix #11809: Avoid leaking memory fragment = first = null; if ( scripts.length ) { jQuery.each( scripts, function( i, elem ) { if ( elem.src ) { if ( jQuery.ajax ) { jQuery.ajax({ url: elem.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.error("no ajax"); } } else { jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } }); } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } 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 cloneFixAttributes( src, dest ) { var nodeName; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } // clearAttributes removes the attributes, which we don't want, // but also removes the attachEvent events, which we *do* want if ( dest.clearAttributes ) { dest.clearAttributes(); } // mergeAttributes, in contrast, only merges back on the // original attributes, not the events if ( dest.mergeAttributes ) { dest.mergeAttributes( src ); } nodeName = dest.nodeName.toLowerCase(); if ( nodeName === "object" ) { // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. 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" && 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.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; // IE blanks contents when cloning scripts } else if ( nodeName === "script" && dest.text !== src.text ) { dest.text = src.text; } // Event data gets referenced instead of copied if the expando // gets copied too dest.removeAttribute( jQuery.expando ); } jQuery.buildFragment = function( args, context, scripts ) { var fragment, cacheable, cachehit, first = args[ 0 ]; // Set context from what may come in as undefined or a jQuery collection or a node // Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 & // also doubles as fix for #8950 where plain objects caused createDocumentFragment exception context = context || document; context = !context.nodeType && context[0] || context; context = context.ownerDocument || context; // Only cache "small" (1/2 KB) HTML strings that are associated with the main document // Cloning options loses the selected state, so don't cache them // IE 6 doesn't like it when you put <object> or <embed> elements in a fragment // Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache // Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501 if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test( first ) && (jQuery.support.checkClone || !rchecked.test( first )) && (jQuery.support.html5Clone || !rnoshimcache.test( first )) ) { // Mark cacheable and look for a hit cacheable = true; fragment = jQuery.fragments[ first ]; cachehit = fragment !== undefined; } if ( !fragment ) { fragment = context.createDocumentFragment(); jQuery.clean( args, context, fragment, scripts ); // Update the cache, but only store false // unless this is a second parsing of the same content if ( cacheable ) { jQuery.fragments[ first ] = cachehit && fragment; } } return { fragment: fragment, cacheable: cacheable }; }; jQuery.fragments = {}; 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 ), l = insert.length, parent = this.length === 1 && this[0].parentNode; if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) { insert[ original ]( this[0] ); return this; } else { for ( ; i < l; i++ ) { elems = ( i > 0 ? this.clone(true) : this ).get(); jQuery( insert[i] )[ original ]( elems ); ret = ret.concat( elems ); } return this.pushStack( ret, name, insert.selector ); } }; }); function getAll( elem ) { if ( typeof elem.getElementsByTagName !== "undefined" ) { return elem.getElementsByTagName( "*" ); } else if ( typeof elem.querySelectorAll !== "undefined" ) { return elem.querySelectorAll( "*" ); } else { return []; } } // Used in clean, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var srcElements, destElements, i, clone; 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) ) { // IE copies events bound via attachEvent when using cloneNode. // Calling detachEvent on the clone will also remove the events // from the original. In order to get around this, we use some // proprietary methods to clear the events. Thanks to MooTools // guys for this hotness. cloneFixAttributes( elem, clone ); // Using Sizzle here is crazy slow, so we use getElementsByTagName instead srcElements = getAll( elem ); destElements = getAll( clone ); // Weird iteration because IE will replace the length property // with an element if you are cloning the body and one of the // elements on the page has a name or id of "length" for ( i = 0; srcElements[i]; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { cloneFixAttributes( srcElements[i], destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { cloneCopyEvent( elem, clone ); if ( deepDataAndEvents ) { srcElements = getAll( elem ); destElements = getAll( clone ); for ( i = 0; srcElements[i]; ++i ) { cloneCopyEvent( srcElements[i], destElements[i] ); } } } srcElements = destElements = null; // Return the cloned set return clone; }, clean: function( elems, context, fragment, scripts ) { var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment, ret = []; // Ensure that context is a document if ( !context || typeof context.createDocumentFragment === "undefined" ) { context = document; } // Use the already-created safe fragment if context permits for ( i = 0; (elem = elems[i]) != null; i++ ) { if ( typeof elem === "number" ) { elem += ""; } if ( !elem ) { continue; } // Convert html string into DOM nodes if ( typeof elem === "string" ) { if ( !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else { // Ensure a safe container in which to render the html safe = safe || createSafeFragment( context ); div = context.createElement("div"); safe.appendChild( div ); // Fix "XHTML"-style tags in all browsers elem = elem.replace(rxhtmlTag, "<$1></$2>"); // Go to html and back, then peel off extra wrappers tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; depth = wrap[0]; div.innerHTML = wrap[1] + elem + wrap[2]; // Move to the right depth while ( depth-- ) { div = div.lastChild; } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> hasBody = rtbody.test(elem); tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !hasBody ? div.childNodes : []; for ( j = tbody.length - 1; j >= 0 ; --j ) { if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) { tbody[ j ].parentNode.removeChild( tbody[ j ] ); } } } // IE completely kills leading whitespace when innerHTML is used if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild ); } elem = div.childNodes; // Take out of fragment container (we need a fresh div each time) div.parentNode.removeChild( div ); } } if ( elem.nodeType ) { ret.push( elem ); } else { jQuery.merge( ret, elem ); } } // Fix #11356: Clear elements from safeFragment if ( div ) { elem = div = safe = null; } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { for ( i = 0; (elem = ret[i]) != null; i++ ) { if ( jQuery.nodeName( elem, "input" ) ) { fixDefaultChecked( elem ); } else if ( typeof elem.getElementsByTagName !== "undefined" ) { jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked ); } } } // Append elements to a provided document fragment if ( fragment ) { // Special handling of each script element handleScript = function( elem ) { // Check if we consider it executable if ( !elem.type || rscriptType.test( elem.type ) ) { // Detach the script and store it in the scripts array (if provided) or the fragment // Return truthy to indicate that it has been handled return scripts ? scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) : fragment.appendChild( elem ); } }; for ( i = 0; (elem = ret[i]) != null; i++ ) { // Check if we're done after handling an executable script if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) { // Append to fragment and handle embedded scripts fragment.appendChild( elem ); if ( typeof elem.getElementsByTagName !== "undefined" ) { // handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript ); // Splice the scripts into ret after their former ancestor and advance our index beyond them ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) ); i += jsTags.length; } } } } return ret; }, cleanData: function( elems, /* internal */ acceptData ) { var data, id, elem, type, 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 ( elem.removeAttribute ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } jQuery.deletedIds.push( id ); } } } } } }); // Limit scope pollution from any deprecated API (function() { var matched, browser; // Use of jQuery.browser is frowned upon. // More details: http://api.jquery.com/jQuery.browser // jQuery.uaMatch maintained for back-compat jQuery.uaMatch = function( ua ) { ua = ua.toLowerCase(); var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || /(webkit)[ \/]([\w.]+)/.exec( ua ) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || /(msie) ([\w.]+)/.exec( ua ) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || []; return { browser: match[ 1 ] || "", version: match[ 2 ] || "0" }; }; matched = jQuery.uaMatch( navigator.userAgent ); browser = {}; if ( matched.browser ) { browser[ matched.browser ] = true; browser.version = matched.version; } // Chrome is Webkit, but Webkit is also Safari. if ( browser.chrome ) { browser.webkit = true; } else if ( browser.webkit ) { browser.safari = true; } jQuery.browser = browser; jQuery.sub = function() { function jQuerySub( selector, context ) { return new jQuerySub.fn.init( selector, context ); } jQuery.extend( true, jQuerySub, this ); jQuerySub.superclass = this; jQuerySub.fn = jQuerySub.prototype = this(); jQuerySub.fn.constructor = jQuerySub; jQuerySub.sub = this.sub; jQuerySub.fn.init = function init( selector, context ) { if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) { context = jQuerySub( context ); } return jQuery.fn.init.call( this, selector, context, rootjQuerySub ); }; jQuerySub.fn.init.prototype = jQuerySub.fn; var rootjQuerySub = jQuerySub(document); return jQuerySub; }; })(); var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, 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 = {}, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ], eventsToggle = jQuery.fn.toggle; // 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 ) { elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var elem, display, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && elem.style.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 { display = curCSS( elem, "display" ); if ( !values[ index ] && display !== "none" ) { jQuery._data( elem, "olddisplay", 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 ) { 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, fn2 ) { var bool = typeof state === "boolean"; if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) { return eventsToggle.apply( this, arguments ); } 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: { "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"; } // 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, numeric, extra ) { var val, num, 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 ); } //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 ( numeric || extra !== undefined ) { num = parseFloat( val ); return numeric || 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 ) { 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.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: To any future maintainer, we've window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { curCSS = function( elem, name ) { var ret, width, minWidth, maxWidth, computed = window.getComputedStyle( elem, null ), style = elem.style; if ( computed ) { ret = computed[ name ]; 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 ) ) { width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { curCSS = function( elem, name ) { var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[ name ], 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; rsLeft = elem.runtimeStyle && elem.runtimeStyle.left; // Put in the new values to get a computed value out if ( rsLeft ) { elem.runtimeStyle.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { elem.runtimeStyle.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox ) { 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" ) { // we use jQuery.css instead of curCSS here // because of the reliableMarginRight CSS hook! val += jQuery.css( elem, extra + cssExpand[ i ], true ); } // From this point on we use curCSS for maximum performance (relevant in animations) if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } else { // at this point, extra isn't content, so add padding val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0; // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0; } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val = name === "width" ? elem.offsetWidth : elem.offsetHeight, valueIsBorderBox = true, isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "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 ); 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 ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { if ( elemdisplay[ nodeName ] ) { return elemdisplay[ nodeName ]; } var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ), display = elem.css("display"); elem.remove(); // If the simple way fails, // get element's real default display by attaching it to a temp iframe if ( display === "none" || display === "" ) { // Use the already-created iframe if possible iframe = document.body.appendChild( iframe || jQuery.extend( document.createElement("iframe"), { frameBorder: 0, width: 0, height: 0 }) ); // Create a cacheable copy of the iframe document on first call. // IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML // document to it; WebKit & Firefox won't allow reusing the iframe document. if ( !iframeDoc || !iframe.createElement ) { iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document; iframeDoc.write("<!doctype html><html><body>"); iframeDoc.close(); } elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) ); display = curCSS( elem, "display" ); document.body.removeChild( iframe ); } // Store the correct default display elemdisplay[ nodeName ] = display; 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 if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) { return jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }); } else { return getWidthOrHeight( elem, name, extra ); } } }, set: function( elem, value, extra ) { return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box" ) : 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 >= 1 && 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 there is no filter style applied in a css rule, we are done if ( 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 ) { // 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" }, function() { if ( computed ) { return 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 ) { var ret = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( 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, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ], expanded = {}; for ( i = 0; 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, rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rselectTextarea = /^(?:select|textarea)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ return this.elements ? jQuery.makeArray( this.elements ) : this; }) .filter(function(){ return this.name && !this.disabled && ( this.checked || rselectTextarea.test( this.nodeName ) || rinput.test( this.type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val, i ){ 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 { // If array item is non-scalar (array or object), encode its // numeric index to resolve deserialization ambiguity issues. // Note that rack (as of 1.0.0) can't currently deserialize // nested arrays properly, and attempting to do so may cause // a server error. Possible fixes are to modify rack's // deserialization algorithm or to provide an option or flag // to force array serialization to be shallow. 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 ); } } var // Document location ajaxLocation, // Document location segments ajaxLocParts, rhash = /#.*$/, 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 = /^\/\//, rquery = /\?/, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rts = /([?&])_=[^&]*/, 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 = ["*/"] + ["*"]; // #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, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ), i = 0, length = dataTypes.length; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression for ( ; i < length; i++ ) { dataType = dataTypes[ i ]; // We control if we're asked to add before // any existing element placeBefore = /^\+/.test( dataType ); if ( placeBefore ) { dataType = dataType.substr( 1 ) || "*"; } list = structure[ dataType ] = structure[ dataType ] || []; // then we add to the structure accordingly list[ placeBefore ? "unshift" : "push" ]( func ); } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, dataType /* internal */, inspected /* internal */ ) { dataType = dataType || options.dataTypes[ 0 ]; inspected = inspected || {}; inspected[ dataType ] = true; var selection, list = structure[ dataType ], i = 0, length = list ? list.length : 0, executeOnly = ( structure === prefilters ); for ( ; i < length && ( executeOnly || !selection ); i++ ) { selection = list[ i ]( options, originalOptions, jqXHR ); // If we got redirected to another dataType // we try there if executing only and not done already if ( typeof selection === "string" ) { if ( !executeOnly || inspected[ selection ] ) { selection = undefined; } else { options.dataTypes.unshift( selection ); selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, selection, inspected ); } } } // If we're only executing or nothing was selected // we try the catchall dataType if not done already if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) { selection = inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR, "*", inspected ); } // unnecessary when only executing (prefilters) // but it'll be ignored by the caller in that case return selection; } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, 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 ); } } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } // Don't do a request if no elements are being requested if ( !this.length ) { return this; } var selector, type, response, 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"; } // Request the remote document jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params, complete: function( jqXHR, status ) { if ( callback ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); } } }).done(function( responseText ) { // Save response for use in complete callback response = arguments; // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("<div>") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append( responseText.replace( rscript, "" ) ) // Locate the specified elements .find( selector ) : // If not, just inject the full result responseText ); }); return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){ jQuery.fn[ o ] = function( f ){ return this.on( o, f ); }; }); 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({ type: method, url: url, data: data, success: callback, dataType: type }); }; }); jQuery.extend({ getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, // 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 ) { if ( settings ) { // Building a settings object ajaxExtend( target, jQuery.ajaxSettings ); } else { // Extending ajaxSettings settings = target; target = jQuery.ajaxSettings; } ajaxExtend( target, settings ); return target; }, ajaxSettings: { url: ajaxLocation, isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, type: "GET", contentType: "application/x-www-form-urlencoded; charset=UTF-8", processData: true, async: true, /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { xml: "application/xml, text/xml", html: "text/html", text: "text/plain", json: "application/json, text/javascript", "*": allTypes }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // List of data converters // 1) key format is "source_type destination_type" (a single space in-between) // 2) the catchall symbol "*" can be used for source_type 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: { context: true, url: true } }, 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 // ifModified key ifModifiedKey, // Response headers responseHeadersString, responseHeaders, // transport transport, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events // It's the callbackContext if one was provided in the options // and if it's a DOM node or a jQuery collection globalEventContext = callbackContext !== s && ( callbackContext.nodeType || callbackContext instanceof 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, // Caches the header setRequestHeader: function( name, value ) { if ( !state ) { var lname = name.toLowerCase(); name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // 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 === undefined ? null : match; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Cancel the request abort: function( statusText ) { statusText = statusText || strAbort; if ( transport ) { transport.abort( statusText ); } done( 0, statusText ); return this; } }; // Callback for when everything is done // It is defined here because jslint complains if it is declared // at the end of the function (which would be more logical and readable) 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[ ifModifiedKey ] = modified; } modified = jqXHR.getResponseHeader("Etag"); if ( modified ) { jQuery.etag[ ifModifiedKey ] = modified; } } // If not modified if ( status === 304 ) { statusText = "notmodified"; isSuccess = true; // If we have data } 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 ( !statusText || status ) { 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( "ajax" + ( isSuccess ? "Success" : "Error" ), [ 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" ); } } } // Attach deferreds deferred.promise( jqXHR ); jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; jqXHR.complete = completeDeferred.add; // Status-dependent callbacks jqXHR.statusCode = function( map ) { if ( map ) { var tmp; if ( state < 2 ) { for ( tmp in map ) { statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ]; } } else { tmp = map[ jqXHR.status ]; jqXHR.always( tmp ); } } return this; }; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // We also use the url parameter if available s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace ); // Determine if a cross-domain request is in order 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; // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Get ifModifiedKey before adding the anti-cache parameter ifModifiedKey = s.url; // Add anti-cache in url if needed if ( s.cache === false ) { var ts = jQuery.now(), // try replacing _= if it is there ret = s.url.replace( rts, "$1_=" + ts ); // if nothing was replaced, add timestamp to the end s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" ); } } // 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 If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { ifModifiedKey = ifModifiedKey || s.url; if ( jQuery.lastModified[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] ); } if ( jQuery.etag[ ifModifiedKey ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] ); } } // 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; } } } return jqXHR; }, // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {} }); /* 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 ct, type, finalDataType, firstDataType, 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 conv, conv2, current, tmp, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ], converters = {}, i = 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 }; } var oldCallbacks = [], rquestion = /\?/, rjsonp = /(=)\?(?=&|$)|\?\?/, nonce = jQuery.now(); // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, data = s.data, url = s.url, hasCallback = s.jsonp !== false, replaceInUrl = hasCallback && rjsonp.test( url ), replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( data ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; overwritten = window[ callbackName ]; // Insert callback into url or form data if ( replaceInUrl ) { s.url = url.replace( rjsonp, "$1" + callbackName ); } else if ( replaceInData ) { s.data = data.replace( rjsonp, "$1" + callbackName ); } else if ( hasCallback ) { s.url += ( rquestion.test( 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 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"; } }); // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /javascript|ecmascript/ }, 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 || document.getElementsByTagName( "head" )[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement( "script" ); script.async = "async"; 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 ( head && script.parentNode ) { head.removeChild( script ); } // Dereference the script script = undefined; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709 and #4378). head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( 0, 1 ); } } }; } }); var xhrCallbacks, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject ? function() { // Abort all pending requests for ( var key in xhrCallbacks ) { xhrCallbacks[ key ]( 0, 1 ); } } : false, xhrId = 0; // 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 (function( xhr ) { jQuery.extend( jQuery.support, { ajax: !!xhr, cors: !!xhr && ( "withCredentials" in xhr ) }); })( jQuery.ajaxSettings.xhr() ); // Create transport if the browser can provide an xhr if ( jQuery.support.ajax ) { 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( _ ) {} // 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, statusText, responseHeaders, responses, xml; // 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 { status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); responses = {}; xml = xhr.responseXML; // Construct response list if ( xml && xml.documentElement /* #4958 */ ) { responses.xml = xml; } // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) try { responses.text = xhr.responseText; } catch( _ ) { } // 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, 0 ); } 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(0,1); } } }; } }); } var rroot = /^(?:body|html)$/i; jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var box, docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, top, left, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } if ( (body = doc.body) === elem ) { return jQuery.offset.bodyOffset( elem ); } docElem = doc.documentElement; // Make sure we're not dealing with a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return { top: 0, left: 0 }; } box = elem.getBoundingClientRect(); win = getWindow( doc ); clientTop = docElem.clientTop || body.clientTop || 0; clientLeft = docElem.clientLeft || body.clientLeft || 0; scrollTop = win.pageYOffset || docElem.scrollTop; scrollLeft = win.pageXOffset || docElem.scrollLeft; top = box.top + scrollTop - clientTop; left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; }; jQuery.offset = { bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) { top += parseFloat( jQuery.css(body, "marginTop") ) || 0; left += parseFloat( jQuery.css(body, "marginLeft") ) || 0; } return { top: top, left: left }; }, 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 elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset(); // Subtract 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 offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0; offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0; // Add offsetParent borders parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0; parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0; // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.body; while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.body; }); } }); // 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; } // 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 );
eric-seekas/jquery-builder
dist/1.8.1/jquery-dimensions-effects.js
JavaScript
mit
245,511
package com.actionbarsherlock.internal.view.menu; import org.holoeverywhere.LayoutInflater; import org.holoeverywhere.R; import org.holoeverywhere.widget.LinearLayout; import org.holoeverywhere.widget.TextView; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.RadioButton; public class HoloListMenuItemView extends LinearLayout implements MenuView.ItemView { private Drawable mBackground; private CheckBox mCheckBox; private boolean mForceShowIcon; private ImageView mIconView; private LayoutInflater mInflater; private MenuItemImpl mItemData; private boolean mPreserveIconSpacing; private RadioButton mRadioButton; private TextView mShortcutView; private int mTextAppearance; private Context mTextAppearanceContext; private TextView mTitleView; public HoloListMenuItemView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public HoloListMenuItemView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MenuView, defStyle, 0); mBackground = a.getDrawable(R.styleable.MenuView_dialogItemBackground); mTextAppearance = a.getResourceId( R.styleable.MenuView_dialogItemTextAppearance, -1); mPreserveIconSpacing = a.getBoolean( R.styleable.MenuView_android_preserveIconSpacing, false); mTextAppearanceContext = context; a.recycle(); } private LayoutInflater getInflater() { if (mInflater == null) { mInflater = LayoutInflater.from(getContext()); } return mInflater; } @Override public MenuItemImpl getItemData() { return mItemData; } @Override public void initialize(MenuItemImpl itemData, int menuType) { mItemData = itemData; setVisibility(itemData.isVisible() ? View.VISIBLE : View.GONE); setTitle(itemData.getTitleForItemView(this)); setCheckable(itemData.isCheckable()); setShortcut(itemData.shouldShowShortcut(), itemData.getShortcut()); setIcon(itemData.getIcon()); setEnabled(itemData.isEnabled()); } private void insertCheckBox() { LayoutInflater inflater = getInflater(); mCheckBox = (CheckBox) inflater.inflate( R.layout.list_menu_item_checkbox, this, false); addView(mCheckBox); } private void insertIconView() { LayoutInflater inflater = getInflater(); mIconView = (ImageView) inflater.inflate(R.layout.list_menu_item_icon, this, false); addView(mIconView, 0); } private void insertRadioButton() { LayoutInflater inflater = getInflater(); mRadioButton = (RadioButton) inflater.inflate( R.layout.list_menu_item_radio, this, false); addView(mRadioButton); } @SuppressWarnings("deprecation") @Override protected void onFinishInflate() { super.onFinishInflate(); setBackgroundDrawable(mBackground); mTitleView = (TextView) findViewById(R.id.title); if (mTextAppearance != -1) { mTitleView.setTextAppearance(mTextAppearanceContext, mTextAppearance); } mShortcutView = (TextView) findViewById(R.id.shortcut); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mIconView != null && mPreserveIconSpacing) { // Enforce minimum icon spacing ViewGroup.LayoutParams lp = getLayoutParams(); LayoutParams iconLp = (LayoutParams) mIconView.getLayoutParams(); if (lp.height > 0 && iconLp.width <= 0) { iconLp.width = lp.height; } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override public boolean prefersCondensedTitle() { return false; } @Override public void setCheckable(boolean checkable) { if (!checkable && mRadioButton == null && mCheckBox == null) { return; } // Depending on whether its exclusive check or not, the checkbox or // radio button will be the one in use (and the other will be // otherCompoundButton) final CompoundButton compoundButton; final CompoundButton otherCompoundButton; if (mItemData.isExclusiveCheckable()) { if (mRadioButton == null) { insertRadioButton(); } compoundButton = mRadioButton; otherCompoundButton = mCheckBox; } else { if (mCheckBox == null) { insertCheckBox(); } compoundButton = mCheckBox; otherCompoundButton = mRadioButton; } if (checkable) { compoundButton.setChecked(mItemData.isChecked()); final int newVisibility = checkable ? View.VISIBLE : View.GONE; if (compoundButton.getVisibility() != newVisibility) { compoundButton.setVisibility(newVisibility); } // Make sure the other compound button isn't visible if (otherCompoundButton != null && otherCompoundButton.getVisibility() != View.GONE) { otherCompoundButton.setVisibility(View.GONE); } } else { if (mCheckBox != null) { mCheckBox.setVisibility(View.GONE); } if (mRadioButton != null) { mRadioButton.setVisibility(View.GONE); } } } @Override public void setChecked(boolean checked) { CompoundButton compoundButton; if (mItemData.isExclusiveCheckable()) { if (mRadioButton == null) { insertRadioButton(); } compoundButton = mRadioButton; } else { if (mCheckBox == null) { insertCheckBox(); } compoundButton = mCheckBox; } compoundButton.setChecked(checked); } public void setForceShowIcon(boolean forceShow) { mPreserveIconSpacing = mForceShowIcon = forceShow; } @Override public void setIcon(Drawable icon) { final boolean showIcon = mItemData.shouldShowIcon() || mForceShowIcon; if (!showIcon && !mPreserveIconSpacing) { return; } if (mIconView == null && icon == null && !mPreserveIconSpacing) { return; } if (mIconView == null) { insertIconView(); } if (icon != null || mPreserveIconSpacing) { mIconView.setImageDrawable(showIcon ? icon : null); if (mIconView.getVisibility() != View.VISIBLE) { mIconView.setVisibility(View.VISIBLE); } } else { mIconView.setVisibility(View.GONE); } } @Override public void setShortcut(boolean showShortcut, char shortcutKey) { final int newVisibility = showShortcut && mItemData.shouldShowShortcut() ? View.VISIBLE : View.GONE; if (newVisibility == View.VISIBLE) { mShortcutView.setText(mItemData.getShortcutLabel()); } if (mShortcutView.getVisibility() != newVisibility) { mShortcutView.setVisibility(newVisibility); } } @Override public void setTitle(CharSequence title) { if (title != null) { mTitleView.setText(title); if (mTitleView.getVisibility() != View.VISIBLE) { mTitleView.setVisibility(View.VISIBLE); } } else { if (mTitleView.getVisibility() != View.GONE) { mTitleView.setVisibility(View.GONE); } } } @Override public boolean showsIcon() { return mForceShowIcon; } }
mercadolibre/HoloEverywhere
library/src/com/actionbarsherlock/internal/view/menu/HoloListMenuItemView.java
Java
mit
8,271
package net.minecraft.potion; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.ai.attributes.BaseAttributeMap; import net.minecraft.util.ResourceLocation; public class PotionAbsorption extends Potion { protected PotionAbsorption(int potionID, ResourceLocation location, boolean badEffect, int potionColor) { super(potionID, location, badEffect, potionColor); } public void removeAttributesModifiersFromEntity(EntityLivingBase entityLivingBaseIn, BaseAttributeMap p_111187_2_, int amplifier) { entityLivingBaseIn.setAbsorptionAmount(entityLivingBaseIn.getAbsorptionAmount() - (float)(4 * (amplifier + 1))); super.removeAttributesModifiersFromEntity(entityLivingBaseIn, p_111187_2_, amplifier); } public void applyAttributesModifiersToEntity(EntityLivingBase entityLivingBaseIn, BaseAttributeMap p_111185_2_, int amplifier) { entityLivingBaseIn.setAbsorptionAmount(entityLivingBaseIn.getAbsorptionAmount() + (float)(4 * (amplifier + 1))); super.applyAttributesModifiersToEntity(entityLivingBaseIn, p_111185_2_, amplifier); } }
TorchPowered/CraftBloom
src/net/minecraft/potion/PotionAbsorption.java
Java
mit
1,130
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class StorageAccountCheckNameAvailabilityParameters(Model): """The parameters used to check the availabity of the storage account name. Variables are only populated by the server, and will be ignored when sending a request. :param name: The storage account name. :type name: str :ivar type: The type of resource, Microsoft.Storage/storageAccounts. Default value: "Microsoft.Storage/storageAccounts" . :vartype type: str """ _validation = { 'name': {'required': True}, 'type': {'required': True, 'constant': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } type = "Microsoft.Storage/storageAccounts" def __init__(self, name): super(StorageAccountCheckNameAvailabilityParameters, self).__init__() self.name = name
lmazuel/azure-sdk-for-python
azure-mgmt-storage/azure/mgmt/storage/v2017_10_01/models/storage_account_check_name_availability_parameters.py
Python
mit
1,403
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var assert = require('assert'); var fork = require('child_process').fork; var net = require('net'); var EventEmitter = require('events').EventEmitter; var util = require('util'); function isObject(o) { return (typeof o === 'object' && o !== null); } var debug; if (process.env.NODE_DEBUG && /cluster/.test(process.env.NODE_DEBUG)) { debug = function(x) { var prefix = process.pid + ',' + (process.env.NODE_UNIQUE_ID ? 'Worker' : 'Master'); console.error(prefix, x); }; } else { debug = function() { }; } // cluster object: function Cluster() { EventEmitter.call(this); } util.inherits(Cluster, EventEmitter); var cluster = module.exports = new Cluster(); // Used in the master: var masterStarted = false; var ids = 0; var serverHandlers = {}; // Used in the worker: var serverListeners = {}; var queryIds = 0; var queryCallbacks = {}; // Define isWorker and isMaster cluster.isWorker = 'NODE_UNIQUE_ID' in process.env; cluster.isMaster = ! cluster.isWorker; // The worker object is only used in a worker cluster.worker = cluster.isWorker ? {} : null; // The workers array is only used in the master cluster.workers = cluster.isMaster ? {} : null; // Settings object var settings = cluster.settings = {}; // Simple function to call a function on each worker function eachWorker(cb) { // Go through all workers for (var id in cluster.workers) { if (cluster.workers.hasOwnProperty(id)) { cb(cluster.workers[id]); } } } // Extremely simple progress tracker function ProgressTracker(missing, callback) { this.missing = missing; this.callback = callback; } ProgressTracker.prototype.done = function() { this.missing -= 1; this.check(); }; ProgressTracker.prototype.check = function() { if (this.missing === 0) this.callback(); }; cluster.setupMaster = function(options) { // This can only be called from the master. assert(cluster.isMaster); // Don't allow this function to run more than once if (masterStarted) return; masterStarted = true; // Get filename and arguments options = options || {}; // By default, V8 writes the profile data of all processes to a single // v8.log. // // Running that log file through a tick processor produces bogus numbers // because many events won't match up with the recorded memory mappings // and you end up with graphs where 80+% of ticks is unaccounted for. // // Fixing the tick processor to deal with multi-process output is not very // useful because the processes may be running wildly disparate workloads. // // That's why we fix up the command line arguments to include // a "--logfile=v8-%p.log" argument (where %p is expanded to the PID) // unless it already contains a --logfile argument. var execArgv = options.execArgv || process.execArgv; if (execArgv.some(function(s) { return /^--prof/.test(s); }) && !execArgv.some(function(s) { return /^--logfile=/.test(s); })) { execArgv = execArgv.slice(); execArgv.push('--logfile=v8-%p.log'); } // Set settings object settings = cluster.settings = { exec: options.exec || process.argv[1], execArgv: execArgv, args: options.args || process.argv.slice(2), silent: options.silent || false }; // emit setup event cluster.emit('setup'); }; // Check if a message is internal only var INTERNAL_PREFIX = 'NODE_CLUSTER_'; function isInternalMessage(message) { return isObject(message) && typeof message.cmd === 'string' && message.cmd.length > INTERNAL_PREFIX.length && message.cmd.slice(0, INTERNAL_PREFIX.length) === INTERNAL_PREFIX; } // Modify message object to be internal function internalMessage(inMessage) { var outMessage = util._extend({}, inMessage); // Add internal prefix to cmd outMessage.cmd = INTERNAL_PREFIX + (outMessage.cmd || ''); return outMessage; } // Handle callback messages function handleResponse(outMessage, outHandle, inMessage, inHandle, worker) { // The message there will be sent var message = internalMessage(outMessage); // callback id - will be undefined if not set message._queryEcho = inMessage._requestEcho; // Call callback if a query echo is received if (inMessage._queryEcho) { queryCallbacks[inMessage._queryEcho](inMessage.content, inHandle); delete queryCallbacks[inMessage._queryEcho]; } // Send if outWrap contains something useful if (!(outMessage === undefined && message._queryEcho === undefined)) { sendInternalMessage(worker, message, outHandle); } } // Handle messages from both master and workers var messageHandler = {}; function handleMessage(worker, inMessage, inHandle) { // Remove internal prefix var message = util._extend({}, inMessage); message.cmd = inMessage.cmd.substr(INTERNAL_PREFIX.length); var respondUsed = false; function respond(outMessage, outHandler) { respondUsed = true; handleResponse(outMessage, outHandler, inMessage, inHandle, worker); } // Run handler if it exists if (messageHandler[message.cmd]) { messageHandler[message.cmd](message, worker, respond); } // Send respond if it hasn't been called yet if (respondUsed === false) { respond(); } } // Messages to the master will be handled using these methods if (cluster.isMaster) { // Handle online messages from workers messageHandler.online = function(message, worker) { worker.state = 'online'; debug('Worker ' + worker.process.pid + ' online'); worker.emit('online'); cluster.emit('online', worker); }; // Handle queryServer messages from workers messageHandler.queryServer = function(message, worker, send) { // This sequence of information is unique to the connection // but not to the worker var args = [message.address, message.port, message.addressType, message.fd]; var key = args.join(':'); var handler; if (serverHandlers.hasOwnProperty(key)) { handler = serverHandlers[key]; } else { if (message.addressType === 'udp4' || message.addressType === 'udp6') { var dgram = require('dgram'); handler = dgram._createSocketHandle.apply(net, args); } else { handler = net._createServerHandle.apply(net, args); } if (!handler) { send({ content: { error: process._errno } }, null); return; } serverHandlers[key] = handler; } // echo callback with the fd handler associated with it send({}, handler); }; // Handle listening messages from workers messageHandler.listening = function(message, worker) { worker.state = 'listening'; // Emit listening, now that we know the worker is listening worker.emit('listening', { address: message.address, port: message.port, addressType: message.addressType, fd: message.fd }); cluster.emit('listening', worker, { address: message.address, port: message.port, addressType: message.addressType, fd: message.fd }); }; // Handle suicide messages from workers messageHandler.suicide = function(message, worker) { worker.suicide = true; }; } // Messages to a worker will be handled using these methods else if (cluster.isWorker) { // Handle worker.disconnect from master messageHandler.disconnect = function(message, worker) { worker.disconnect(); }; } function toDecInt(value) { value = parseInt(value, 10); return isNaN(value) ? null : value; } // Create a worker object, that works both for master and worker function Worker(customEnv) { if (!(this instanceof Worker)) return new Worker(); EventEmitter.call(this); var self = this; var env = process.env; // Assign a unique id, default null this.id = cluster.isMaster ? ++ids : toDecInt(env.NODE_UNIQUE_ID); // XXX: Legacy. Remove in 0.9 this.workerID = this.uniqueID = this.id; // Assign state this.state = 'none'; // Create or get process if (cluster.isMaster) { // Create env object // first: copy and add id property var envCopy = util._extend({}, env); envCopy['NODE_UNIQUE_ID'] = this.id; // second: extend envCopy with the env argument if (isObject(customEnv)) { envCopy = util._extend(envCopy, customEnv); } // fork worker this.process = fork(settings.exec, settings.args, { 'env': envCopy, 'silent': settings.silent, 'execArgv': settings.execArgv }); } else { this.process = process; } if (cluster.isMaster) { // Save worker in the cluster.workers array cluster.workers[this.id] = this; // Emit a fork event, on next tick // There is no worker.fork event since this has no real purpose process.nextTick(function() { cluster.emit('fork', self); }); } // handle internalMessage, exit and disconnect event this.process.on('internalMessage', handleMessage.bind(null, this)); this.process.once('exit', function(exitCode, signalCode) { prepareExit(self, 'dead'); self.emit('exit', exitCode, signalCode); cluster.emit('exit', self, exitCode, signalCode); }); this.process.once('disconnect', function() { prepareExit(self, 'disconnected'); self.emit('disconnect'); cluster.emit('disconnect', self); }); // relay message and error this.process.on('message', this.emit.bind(this, 'message')); this.process.on('error', this.emit.bind(this, 'error')); } util.inherits(Worker, EventEmitter); cluster.Worker = Worker; function prepareExit(worker, state) { // set state to disconnect worker.state = state; // Make suicide a boolean worker.suicide = !!worker.suicide; // Remove from workers in the master if (cluster.isMaster) { delete cluster.workers[worker.id]; } } // Send internal message function sendInternalMessage(worker, message/*, handler, callback*/) { // Exist callback var callback = arguments[arguments.length - 1]; if (typeof callback !== 'function') { callback = undefined; } // exist handler var handler = arguments[2] !== callback ? arguments[2] : undefined; if (!isInternalMessage(message)) { message = internalMessage(message); } // Store callback for later if (callback) { message._requestEcho = worker.id + ':' + (++queryIds); queryCallbacks[message._requestEcho] = callback; } worker.send(message, handler); } // Send message to worker or master Worker.prototype.send = function() { // You could also just use process.send in a worker this.process.send.apply(this.process, arguments); }; // Kill the worker without restarting Worker.prototype.kill = Worker.prototype.destroy = function(signal) { if (!signal) signal = 'SIGTERM'; var self = this; this.suicide = true; if (cluster.isMaster) { // Disconnect IPC channel // this way the worker won't need to propagate suicide state to master if (self.process.connected) { self.process.once('disconnect', function() { self.process.kill(signal); }); self.process.disconnect(); } else { self.process.kill(signal); } } else { // Channel is open if (this.process.connected) { // Inform master to suicide and then kill sendInternalMessage(this, {cmd: 'suicide'}, function() { process.exit(0); }); // When channel is closed, terminate the process this.process.once('disconnect', function() { process.exit(0); }); } else { process.exit(0); } } }; // The .disconnect function will close all servers // and then disconnect the IPC channel. if (cluster.isMaster) { // Used in master Worker.prototype.disconnect = function() { this.suicide = true; sendInternalMessage(this, {cmd: 'disconnect'}); }; } else { // Used in workers Worker.prototype.disconnect = function() { var self = this; this.suicide = true; // keep track of open servers var servers = Object.keys(serverListeners).length; var progress = new ProgressTracker(servers, function() { // There are no more servers open so we will close the IPC channel. // Closing the IPC channel will emit a disconnect event // in both master and worker on the process object. // This event will be handled by prepareExit. self.process.disconnect(); }); // depending on where this function was called from (master or worker) // The suicide state has already been set, // but it doesn't really matter if we set it again. sendInternalMessage(this, {cmd: 'suicide'}, function() { // in case there are no servers progress.check(); // closing all servers gracefully var server; for (var key in serverListeners) { server = serverListeners[key]; // in case the server is closed we won't close it again if (server._handle === null) { progress.done(); continue; } server.on('close', progress.done.bind(progress)); server.close(); } }); }; } // Fork a new worker cluster.fork = function(env) { // This can only be called from the master. assert(cluster.isMaster); // Make sure that the master has been initialized cluster.setupMaster(); return (new cluster.Worker(env)); }; // execute .disconnect on all workers and close handlers when done cluster.disconnect = function(callback) { // This can only be called from the master. assert(cluster.isMaster); // Close all TCP handlers when all workers are disconnected var workers = Object.keys(cluster.workers).length; var progress = new ProgressTracker(workers, function() { for (var key in serverHandlers) { serverHandlers[key].close(); delete serverHandlers[key]; } // call callback when done if (callback) callback(); }); // begin disconnecting all workers eachWorker(function(worker) { worker.once('disconnect', progress.done.bind(progress)); worker.disconnect(); }); process.nextTick(function() { // in case there weren't any workers progress.check(); }); }; // Internal function. Called from src/node.js when worker process starts. cluster._setupWorker = function() { // Get worker class var worker = cluster.worker = new Worker(); // we will terminate the worker // when the worker is disconnected from the parent accidentally process.once('disconnect', function() { if (worker.suicide !== true) { process.exit(0); } }); // Tell master that the worker is online worker.state = 'online'; sendInternalMessage(worker, { cmd: 'online' }); }; // Internal function. Called by net.js and dgram.js when attempting to bind a // TCP server or UDP socket. cluster._getServer = function(tcpSelf, address, port, addressType, fd, cb) { // This can only be called from a worker. assert(cluster.isWorker); // Store tcp instance for later use var key = [address, port, addressType, fd].join(':'); serverListeners[key] = tcpSelf; // Send a listening message to the master tcpSelf.once('listening', function() { cluster.worker.state = 'listening'; sendInternalMessage(cluster.worker, { cmd: 'listening', address: address, port: tcpSelf.address().port || port, addressType: addressType, fd: fd }); }); // Request the fd handler from the master process var message = { cmd: 'queryServer', address: address, port: port, addressType: addressType, fd: fd }; // The callback will be stored until the master has responded sendInternalMessage(cluster.worker, message, function(msg, handle) { cb(handle, msg && msg.error); }); };
domenicosolazzo/philocademy
venv/src/node-v0.10.36/lib/cluster.js
JavaScript
mit
16,806
.red { background-color: red; color: white; border-radius: 0.2em; border-bottom: 1px solid rgba(100, 100, 100, 0.2); border-left: 1px solid rgba(100, 100, 100, 0.2); } .blue { background-color: blue; color: white; border-radius: 0.2em; border-bottom: 1px solid rgba(100, 100, 100, 0.2); border-left: 1px solid rgba(100, 100, 100, 0.2); } .green { background-color: green; color: white; border-radius: 0.2em; border-bottom: 1px solid rgba(100, 100, 100, 0.2); border-left: 1px solid rgba(100, 100, 100, 0.2); } body{ background-color: darkblue; color:lightcyan; } .slide h1,h2,h3,h4,h5,p,li{ color:black; } .slide pre>code { font-size: 20px; text-shadow: 0 0 0 rgba(10, 10, 10, 0.3); } code { background-color: darkblue; color: lightyellow; opacity: 1; border-radius: 0.2em; border-bottom: 1px solid rgba(100, 100, 100, 0.2); border-left: 1px solid rgba(100, 100, 100, 0.2); font-family: "Consolas", monospace; /* "Cutive mono", "Courier New", monospace; */ } .impress-enabled .step { margin: 0; opacity: 0.4; transition: opacity 2s; } .impress-enabled .step.active { opacity: 1 } #overview{ opacity: 1; }
masterfish2015/my_project
半导体物理/css/new_style6.css
CSS
mit
1,307
/*! * jQuery JavaScript Library v2.0.1 -event-alias,-offset * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-27T00:53Z */ (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+ //"use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Support: IE9 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // 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 = "2.0.1 -event-alias,-offset", // 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, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // 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 and self cleanup method completed = function() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); }; 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 ) { // 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, 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 options, name, src, copy, copyIsArray, 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({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), 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; } // 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, 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 ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, 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: JSON.parse, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // 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; }, trim: function( text ) { return text == null ? "" : core_trim.call( text ); }, // 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 ) { return arr == null ? -1 : core_indexOf.call( arr, elem, i ); }, 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 tmp, args, proxy; 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: Date.now, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. 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; } }); 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 ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } 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); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-05-15 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function() { return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf 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; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + 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 + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // 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, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !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, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 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, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * 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 keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied if the test fails * @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler */ function addHandle( attrs, handler, test ) { attrs = attrs.split("|"); var current, i = attrs.length, setHandle = test ? null : handler; while ( i-- ) { // Don't override a user's handler if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) { Expr.attrHandle[ attrs[i] ] = setHandle; } } } /** * Fetches boolean attributes by node * @param {Element} elem * @param {String} name */ function boolHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents var val = elem.getAttributeNode( name ); return val && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } /** * Fetches attributes without interpolation * http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx * @param {Element} elem * @param {String} name */ function interpolationHandler( elem, name ) { // XML does not need to be checked as this will not be assigned for XML documents return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } /** * Uses defaultValue to retrieve value in IE6/7 * @param {Element} elem * @param {String} name */ function valueHandler( elem ) { // Ignore the value *property* on inputs by using defaultValue // Fallback to Sizzle.attr by returning undefined where appropriate // XML does not need to be checked as this will not be assigned for XML documents if ( elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns Returns -1 if a precedes b, 1 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * 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; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * 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 documentIsHTML = !isXML( doc ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { // Support: IE<8 // Prevent attribute/property "interpolation" div.innerHTML = "<a href='#'></a>"; addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" ); // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies addHandle( booleans, boolHandler, div.getAttribute("disabled") == null ); div.className = "i"; return !div.getAttribute("className"); }); // Support: IE<9 // Retrieving value should defer to defaultValue support.input = assert(function( div ) { div.innerHTML = "<input>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }); // IE6/7 still return empty string for value, // but are actually retrieving the property addHandle( "value", valueHandler, support.attributes && support.input ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? 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; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = 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 explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // 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 ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").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.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // 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; }; /* Sorting ---------------------------------------------------------------------- */ // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( doc.createElement("div") ) & 1; }); // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method 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 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined ); return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array 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, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[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[3] && match[4] !== undefined ) { 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( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== 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 identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is 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( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // 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" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } 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, seed ); 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, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Initialize against the default document setDocument(); // Support: Chrome<<14 // Always assume duplicates if they aren't passed to the comparison function [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; 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 ); // 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 // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { 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( support ) { var input = document.createElement("input"), fragment = document.createDocumentFragment(), div = document.createElement("div"), select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Finish early in limited environments if ( !input.type ) { return support; } input.type = "checkbox"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Will be defined later support.reliableMarginRight = true; support.boxSizingReliable = true; support.pixelPosition = false; // Make sure checked status is properly cloned // Support: IE9, IE10 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; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement("input"); input.value = "t"; input.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.appendChild( input ); // Support: Safari 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: Firefox, Chrome, Safari // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) support.focusinBubbles = "onfocusin" in window; 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, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;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"; // Check box-sizing and margin behavior. body.appendChild( container ).appendChild( div ); div.innerHTML = ""; // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // 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"; // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right 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 ); } body.removeChild( container ); }); return support; })( {} ); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var data_user, data_priv, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType ? owner.nodeType === 1 || owner.nodeType === 9 : true; }; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { return this.get( owner, key ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // 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 = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( core_rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; // These may be used throughout the jQuery core codebase data_user = new Data(); data_priv = new Data(); jQuery.extend({ acceptData: Data.accepts, hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); 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 = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return jQuery.access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { 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 ) ? JSON.parse( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( 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 data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", 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 = data_priv.get( 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\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button)$/i; 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 ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); }, 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 data_priv.set( 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 ? "" : data_priv.get( 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 hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // 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 ]; // IE6-9 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 optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, 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: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ // Temporarily disable this handler to check existence (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; // Restore handler jQuery.expr.attrHandle[ name ] = fn; return ret; }; }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( 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 types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } 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, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( 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; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, 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 ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( 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( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( 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; elem[ type ](); 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, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( data_priv.get( 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 i, matches, sel, handleObj, 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 process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( 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; }, // 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 offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // 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 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; } }, 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: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.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 = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; 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.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 && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ 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; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari 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 origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, 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 = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return core_indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return core_indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, 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) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && 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 matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, 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 = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 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 ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } 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 && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, 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, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because core_push.apply(_, arraylike) throws core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !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 ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], 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, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, i = 0, l = elems.length, fragment = context.createDocumentFragment(), nodes = []; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws 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 || fragment.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.firstChild; } // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; 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( fragment.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 ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( Data.accepts( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { 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 ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var l = elems.length, i = 0; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.fn.extend({ wrapAll: function( html ) { var wrap; 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 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.firstElementChild ) { elem = elem.firstElementChild; } 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(); } }); var curCSS, iframe, // 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 ); } // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. function getStyles( elem ) { return window.getComputedStyle( elem, null ); } 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 ] = data_priv.get( 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 ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { data_priv.set( 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 styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { 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; } } } }, // Don't automatically add "px" to these possibly-unitless properties 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": "cssFloat" }, // 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 specifying 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 ) { style[ name ] = value; } } 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 val, num, 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; } }); curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // Support: IE9 // 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 ); } // Support: Safari 5.1 // A tribute to the "awesome hack by Dean Edwards" // 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; }; 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 ); } }; }); // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { // Support: Android 2.3 if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // Support: Android 2.3 // 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.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 ); } } var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #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 key, deep, 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, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off ); 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.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // 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 (prefilters might expect it) // 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; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // 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 crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); 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"; } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrSupported = jQuery.ajaxSettings.xhr(), xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, // Support: IE9 // We need to keep track of outbound xhr and abort them manually // because IE is not smart enough to do it all by itself xhrId = 0, xhrCallbacks = {}; if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } xhrCallbacks = undefined; }); } jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); jQuery.support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, id, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file protocol always yields status 0, assume 404 xhr.status || 404, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // #11426: When requesting binary data, IE9 will throw an exception // on any attempt to access responseText typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[( id = xhrId++ )] = callback("abort"); // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( options.hasContent && options.data || null ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { tween.unit = unit; tween.start = +start || +target || 0; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } 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, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do 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" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // 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 || data_priv.get( 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 = data_priv.get( 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 = data_priv.get( 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; }; } // 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 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() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } // If there is a window object, that at least has a document property, // define jQuery and $ identifiers if ( typeof window === "object" && typeof window.document === "object" ) { window.jQuery = window.$ = jQuery; } })( window );
michael829/jquery-builder
dist/2.0.1/jquery-event-alias-offset.js
JavaScript
mit
237,326
/** * \file * * \brief Touch screen interface functions for the UC3C-EK * * Copyright (c) 2014 Atmel Corporation. All rights reserved. * * \asf_license_start * * \page License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The name of Atmel may not be used to endorse or promote products derived * from this software without specific prior written permission. * * 4. This software may only be redistributed and used in connection with an * Atmel microcontroller product. * * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \asf_license_stop * */ /** * Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a> */ #include <asf.h> #include "touch_interface.h" /** Flag to indicate that a new touch event is ready to be processed */ static bool touch_event_ready = false; /** * \brief Handler for the touchscreen touch event callback * * Callback function from the touchscreen driver when a new touch event has * been generated. * * \param event Event generated from the touchscreen driver */ static void touch_event_handler(rtouch_event_t const *event) { touch_event_ready = true; } /** * \brief Convert touch events from the touchscreen into window pointer events * * Reads touch events in from the touchscreen and converts them into a * Window Manager pointer event, for enqueuing into the window event queue. * * \return Boolean \c true if a touch event was read, false if no touch event * or a corrupt touch event was received */ bool touch_interface_read(struct win_pointer_event *win_touch_event) { rtouch_event_t touch_event; if (touch_event_ready == false) { return false; } irqflags_t irq_flags = cpu_irq_save(); rtouch_get_event(&touch_event); touch_event_ready = false; cpu_irq_restore(irq_flags); switch (touch_event.type) { case RTOUCH_NO_EVENT: return false; case RTOUCH_PRESS: win_touch_event->type = WIN_POINTER_PRESS; break; case RTOUCH_RELEASE: win_touch_event->type = WIN_POINTER_RELEASE; break; case RTOUCH_MOVE: win_touch_event->type = WIN_POINTER_MOVE; break; } /* Indicate the touch event is a non-relative movement with the virtual * touch button pressed */ win_touch_event->is_relative = false; win_touch_event->buttons = WIN_TOUCH_BUTTON; /* Translate the touch X and Y position into a screen coordinate */ win_touch_event->pos.x = touch_event.panelX; win_touch_event->pos.y = touch_event.panelY; return true; } /** * \brief Determine if the display is currently being touched * * Checks if the user is currently touching the display, with debouncing. * * \return Boolean \c true if the display is being touched, \c false otherwise. */ static bool touch_interface_is_touched(void) { uint8_t steady_samples = 0; bool touch_state = false; /* Debounce touches to the display */ while (steady_samples < 5) { steady_samples++; /* Sample is different to previous state, touch is bouncing */ if (touch_state != rtouch_is_touched()) { touch_state = rtouch_is_touched(); steady_samples = 0; } delay_ms(10); } return touch_state; } /** * \brief Waits until a full display touch event has completed * * Reads touch events in from the touchscreen and waits for a full touch and * release event before continuing. */ static void touch_interface_wait_touch(void) { while (touch_interface_is_touched() == false) { /* Wait for debounced touch of the display */ }; while (touch_interface_is_touched() == true) { /* Wait for end of debounced touch of the display */ }; } /** * \brief Prompts and stores a single calibration point on the display * * Prompts the user for a single calibration point on the display at the * nominated coordinates, and saves the resulting raw touch point. * * \param point Calibration point structure to fill with a touch coordinate */ static void touch_interface_get_calibration_point( rtouch_calibration_point_t* point) { rtouch_event_t event; gfx_draw_circle( point->panelX, point->panelY, 4, GFX_COLOR_BLUE, GFX_WHOLE); touch_interface_wait_touch(); rtouch_get_event(&event); point->rawX = event.rawX; point->rawY = event.rawY; gfx_draw_filled_circle( point->panelX, point->panelY, 4, GFX_COLOR_BLUE, GFX_WHOLE); } /** * \brief Calibrates the touchscreen on the display * * Runs a full calibration with user prompts of the display. */ static void touch_interface_calibrate(void) { static rtouch_calibration_matrix_t matrix; rtouch_calibration_points_t points; /* Create a three-point calibration coordinate list */ points.point1.panelX = 30; points.point1.panelY = 30; points.point2.panelX = 170; points.point2.panelY = 220; points.point3.panelX = 300; points.point3.panelY = 120; /* Show calibration prompt to the user */ gfx_draw_string_aligned( "Screen calibration\n" "Touch circles to continue", gfx_get_width() / 2, gfx_get_height() / 2, &sysfont, GFX_COLOR_TRANSPARENT, GFX_COLOR_RED, TEXT_POS_CENTER, TEXT_ALIGN_CENTER); /* Get calibraton touch points from the user */ touch_interface_get_calibration_point(&points.point1); touch_interface_get_calibration_point(&points.point2); touch_interface_get_calibration_point(&points.point3); /* Compute and set the touchscreen calibration matrix */ rtouch_compute_calibration_matrix(&points, &matrix); rtouch_set_calibration_matrix(&matrix); } /** * \brief Initializes the touchscreen, ready to detect user input * * Performs and initialization and calibration of the touchscreen, so that it * is ready for use. */ void touch_interface_init(void) { rtouch_init(); rtouch_enable(); touch_interface_calibrate(); rtouch_set_event_handler(touch_event_handler); }
femtoio/femto-usb-blink-example
blinky/common/services/wtk/example1_widgets/at32uc3c0512c_uc3c_ek/touch_interface.c
C
mit
6,937
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html><head><title></title> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta name="generator" content="Doxygen 1.8.14"/> <link rel="stylesheet" type="text/css" href="search.css"/> <script type="text/javascript" src="files_13.js"></script> <script type="text/javascript" src="search.js"></script> </head> <body class="SRPage"> <div id="SRIndex"> <div class="SRStatus" id="Loading">Loading...</div> <div id="SRResults"></div> <script type="text/javascript"><!-- /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ createResults(); /* @license-end */ --></script> <div class="SRStatus" id="Searching">Searching...</div> <div class="SRStatus" id="NoMatches">No Matches</div> <script type="text/javascript"><!-- /* @license magnet:?xt=urn:btih:cf05388f2679ee054f2beb29a391d25f4e673ac3&amp;dn=gpl-2.0.txt GPL-v2 */ document.getElementById("Loading").style.display="none"; document.getElementById("NoMatches").style.display="none"; var searchResults = new SearchResults("searchResults"); searchResults.Search(); /* @license-end */ --></script> </div> </body> </html>
kumakoko/KumaGL
third_lib/glm/0.9.9.5/share/doc/glm/api/search/files_13.html
HTML
mit
1,288
--- author: jonhmchan tags: - company - engineering date: "2015-04-14 00:00:00" draft: true layout: post title: "Redefining Developer Evangelism" --- # Hello world!
StackExchange/stack-blog
_posts/2015-04-14-redefining-developer-evangelism.markdown
Markdown
mit
172
/// <reference path="../bpmn-js.d.ts" /> import MMPair from "diagram-js-minimap" const Minimap = MMPair.minimap[1]; export class CustomMinimap extends (Minimap as any) { static $inject = ['config.minimap', 'injector', 'eventBus', 'canvas', 'elementRegistry']; constructor(config: any, injector: any, eventBus: any, canvas: any, elementRegistry: any) { super(config, injector, eventBus, canvas, elementRegistry); } } export var __init__ = ['minimap']; export var minimap = ['type', CustomMinimap];
signumsoftware/extensions
Signum.React.Extensions/Workflow/Bpmn/CustomMinimap.ts
TypeScript
mit
526
{-# LANGUAGE OverloadedStrings #-} import Network.PushNotify.Mpns import Text.XML import Network import Network.HTTP.Conduit import qualified Data.HashSet as HS main :: IO () main = send def send :: MPNSmessage -> IO () send msg = withSocketsDo $ do m <- newManagerMPNS def res <- sendMPNS m def msg{ deviceURIs = HS.singleton "DeviceUri" -- here you complete with the device URI. , restXML = parseText_ def "<?xml version=\"1.0\" encoding=\"utf-8\"?> <root> <value1> Hello World!! </value1> </root>" } print res return ()
MarcosPividori/GSoC-push-notify
test/testMPNS/exampleMPNS.hs
Haskell
mit
636
// // Copyright (c) 2008-2018 the Urho3D project. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #include "../Precompiled.h" #include "../Math/Random.h" #include "../DebugNew.h" namespace Urho3D { static unsigned randomSeed = 1; void SetRandomSeed(unsigned seed) { randomSeed = seed; } unsigned GetRandomSeed() { return randomSeed; } int Rand() { randomSeed = randomSeed * 214013 + 2531011; return (randomSeed >> 16) & 32767; } float RandStandardNormal() { float val = 0.0f; for (int i = 0; i < 12; i++) val += Rand() / 32768.0f; val -= 6.0f; // Now val is approximatly standard normal distributed return val; } }
victorholt/Urho3D
Source/Urho3D/Math/Random.cpp
C++
mit
1,761
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v19.1.4 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("../../context/context"); var agComponentUtils_1 = require("./agComponentUtils"); var ComponentMetadataProvider = /** @class */ (function () { function ComponentMetadataProvider() { } ComponentMetadataProvider.prototype.postConstruct = function () { this.componentMetaData = { dateComponent: { mandatoryMethodList: ['getDate', 'setDate'], optionalMethodList: ['afterGuiAttached'] }, detailCellRenderer: { mandatoryMethodList: [], optionalMethodList: [] }, headerComponent: { mandatoryMethodList: [], optionalMethodList: [] }, headerGroupComponent: { mandatoryMethodList: [], optionalMethodList: [] }, loadingOverlayComponent: { mandatoryMethodList: [], optionalMethodList: [] }, noRowsOverlayComponent: { mandatoryMethodList: [], optionalMethodList: [] }, floatingFilterComponent: { mandatoryMethodList: ['onParentModelChanged'], optionalMethodList: ['afterGuiAttached'] }, floatingFilterWrapperComponent: { mandatoryMethodList: [], optionalMethodList: [] }, cellRenderer: { mandatoryMethodList: [], optionalMethodList: ['refresh', 'afterGuiAttached'], functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils) }, cellEditor: { mandatoryMethodList: ['getValue'], optionalMethodList: ['isPopup', 'isCancelBeforeStart', 'isCancelAfterEnd', 'focusIn', 'focusOut', 'afterGuiAttached'] }, innerRenderer: { mandatoryMethodList: [], optionalMethodList: ['afterGuiAttached'], functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils) }, fullWidthCellRenderer: { mandatoryMethodList: [], optionalMethodList: ['afterGuiAttached'], functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils) }, pinnedRowCellRenderer: { mandatoryMethodList: [], optionalMethodList: ['refresh', 'afterGuiAttached'], functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils) }, groupRowInnerRenderer: { mandatoryMethodList: [], optionalMethodList: ['afterGuiAttached'], functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils) }, groupRowRenderer: { mandatoryMethodList: [], optionalMethodList: ['afterGuiAttached'], functionAdapter: this.agComponentUtils.adaptCellRendererFunction.bind(this.agComponentUtils) }, filter: { mandatoryMethodList: ['isFilterActive', 'doesFilterPass', 'getModel', 'setModel'], optionalMethodList: ['afterGuiAttached', 'onNewRowsLoaded', 'getModelAsString', 'onFloatingFilterChanged'] }, filterComponent: { mandatoryMethodList: ['isFilterActive', 'doesFilterPass', 'getModel', 'setModel'], optionalMethodList: ['afterGuiAttached', 'onNewRowsLoaded', 'getModelAsString', 'onFloatingFilterChanged'] }, statusPanel: { mandatoryMethodList: [], optionalMethodList: ['afterGuiAttached'], }, toolPanel: { mandatoryMethodList: [], optionalMethodList: ['refresh', 'afterGuiAttached'] } }; }; ComponentMetadataProvider.prototype.retrieve = function (name) { return this.componentMetaData[name]; }; __decorate([ context_1.Autowired("agComponentUtils"), __metadata("design:type", agComponentUtils_1.AgComponentUtils) ], ComponentMetadataProvider.prototype, "agComponentUtils", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], ComponentMetadataProvider.prototype, "postConstruct", null); ComponentMetadataProvider = __decorate([ context_1.Bean("componentMetadataProvider") ], ComponentMetadataProvider); return ComponentMetadataProvider; }()); exports.ComponentMetadataProvider = ComponentMetadataProvider;
extend1994/cdnjs
ajax/libs/ag-grid/19.1.4/lib/components/framework/componentMetadataProvider.js
JavaScript
mit
5,914
{% extends "base.html" %} {% block body_class %}template-homepage{% endblock %} {% block content %} <h1>Welcome to your new Wagtail site!</h1> <p>You can access the admin interface <a href="{% url 'wagtailadmin_home' %}">here</a> (make sure you have run "./manage.py createsuperuser" in the console first). <p>If you haven't already given the documentation a read, head over to <a href="http://docs.wagtail.io/">http://docs.wagtail.io</a> to start building on Wagtail</p> {% endblock %}
markussitzmann/webapps
wagtail/project_template/appservercms/home/templates/home/home_page.html
HTML
mit
503
/* ========================================================== * bc-bootstrap-collection.js * http://bootstrap.braincrafted.com * ========================================================== * Copyright 2013 Florian Eckerstorfer * * ========================================================== */ !function ($) { "use strict"; // jshint ;_; /* COLLECTION CLASS DEFINITION * ====================== */ var addField = '[data-addfield="collection"]', removeField = '[data-removefield="collection"]', CollectionAdd = function (el) { $(el).on('click', addField, this.addField); }, CollectionRemove = function (el) { $(el).on('click', removeField, this.removeField); } ; CollectionAdd.prototype.addField = function (e) { var $this = $(this), selector = $this.attr('data-collection'), $parent ; $parent = $(selector); e && e.preventDefault(); var collection = $('#'+selector), list = collection.find('ul'), count = list.find('li').size() ; var newWidget = collection.attr('data-prototype'); // Check if an element with this ID already exists. // If it does, increase the count by one and try again var newName = newWidget.match(/id="(.*?)"/); while ($('#' + newName[1].replace(/__name__/g, count)).size() > 0) { count++; } newWidget = newWidget.replace(/__name__/g, count); newWidget = newWidget.replace(/__id__/g, newName[1].replace(/__name__/g, count)); var newLi = $('<li></li>').html(newWidget); newLi.appendTo(list); }; CollectionRemove.prototype.removeField = function (e) { var $this = $(this); e && e.preventDefault(); var listElement = $this.closest('li').remove(); } /* COLLECTION PLUGIN DEFINITION * ======================= */ var oldAdd = $.fn.addField; var oldRemove = $.fn.removeField; $.fn.addField = function (option) { return this.each(function () { var $this = $(this), data = $this.data('addfield') ; if (!data) { $this.data('addfield', (data = new CollectionAdd(this))); } if (typeof option == 'string') { data[option].call($this); } }); }; $.fn.removeField = function (option) { return this.each(function() { var $this = $(this), data = $this.data('removefield') ; if (!data) { $this.data('removefield', (data = new CollectionRemove(this))); } if (typeof option == 'string') { data[option].call($this); } }); }; $.fn.addField.Constructor = CollectionAdd; $.fn.removeField.Constructor = CollectionRemove; /* COLLECTION NO CONFLICT * ================= */ $.fn.addField.noConflict = function () { $.fn.addField = oldAdd; return this; } $.fn.removeField.noConflict = function () { $.fn.removeField = oldRemove; return this; } /* COLLECTION DATA-API * ============== */ $(document).on('click.addfield.data-api', addField, CollectionAdd.prototype.addField); $(document).on('click.removefield.data-api', removeField, CollectionRemove.prototype.removeField); }(window.jQuery);
pugalessandria/hackathon2013
web/js/bootstrap_bc-bootstrap-collection_14.js
JavaScript
mit
3,511
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. #if __name__ == "__main__": # print "Hello World" from ProgrammingOutlook import ParseOutlookMessageFile import jpype import os.path asposeapispath = os.path.join(os.path.abspath("./../../../"), "lib/") dataDir = os.path.join(os.path.abspath("./"), "data/") print "You need to put your Aspose.Email for Java APIs .jars in this folder:\n"+asposeapispath #print dataDir jpype.startJVM(jpype.getDefaultJVMPath(), "-Djava.ext.dirs=%s" % asposeapispath) hw = ParseOutlookMessageFile(dataDir) hw.main()
aspose-email/Aspose.Email-for-Java
Plugins/Aspose.Email Java for Python/tests/ProgrammingOutlook/ParseOutlookMessageFile/ParseOutlookMessageFile.py
Python
mit
680
/**************************************************************************** * * tttypes.h * * Basic SFNT/TrueType type definitions and interface (specification * only). * * Copyright (C) 1996-2021 by * David Turner, Robert Wilhelm, and Werner Lemberg. * * This file is part of the FreeType project, and may only be used, * modified, and distributed under the terms of the FreeType project * license, LICENSE.TXT. By continuing to use, modify, or distribute * this file you indicate that you have read the license and * understand and accept it fully. * */ #ifndef TTTYPES_H_ #define TTTYPES_H_ #include <freetype/tttables.h> #include <freetype/internal/ftobjs.h> #include <freetype/ftcolor.h> #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT #include <freetype/ftmm.h> #endif FT_BEGIN_HEADER /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** REQUIRED TRUETYPE/OPENTYPE TABLES DEFINITIONS ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /************************************************************************** * * @struct: * TTC_HeaderRec * * @description: * TrueType collection header. This table contains the offsets of the * font headers of each distinct TrueType face in the file. * * @fields: * tag :: * Must be 'ttc~' to indicate a TrueType collection. * * version :: * The version number. * * count :: * The number of faces in the collection. The specification says this * should be an unsigned long, but we use a signed long since we need * the value -1 for specific purposes. * * offsets :: * The offsets of the font headers, one per face. */ typedef struct TTC_HeaderRec_ { FT_ULong tag; FT_Fixed version; FT_Long count; FT_ULong* offsets; } TTC_HeaderRec; /************************************************************************** * * @struct: * SFNT_HeaderRec * * @description: * SFNT file format header. * * @fields: * format_tag :: * The font format tag. * * num_tables :: * The number of tables in file. * * search_range :: * Must be '16 * (max power of 2 <= num_tables)'. * * entry_selector :: * Must be log2 of 'search_range / 16'. * * range_shift :: * Must be 'num_tables * 16 - search_range'. */ typedef struct SFNT_HeaderRec_ { FT_ULong format_tag; FT_UShort num_tables; FT_UShort search_range; FT_UShort entry_selector; FT_UShort range_shift; FT_ULong offset; /* not in file */ } SFNT_HeaderRec, *SFNT_Header; /************************************************************************** * * @struct: * TT_TableRec * * @description: * This structure describes a given table of a TrueType font. * * @fields: * Tag :: * A four-bytes tag describing the table. * * CheckSum :: * The table checksum. This value can be ignored. * * Offset :: * The offset of the table from the start of the TrueType font in its * resource. * * Length :: * The table length (in bytes). */ typedef struct TT_TableRec_ { FT_ULong Tag; /* table type */ FT_ULong CheckSum; /* table checksum */ FT_ULong Offset; /* table file offset */ FT_ULong Length; /* table length */ } TT_TableRec, *TT_Table; /************************************************************************** * * @struct: * TT_LongMetricsRec * * @description: * A structure modeling the long metrics of the 'hmtx' and 'vmtx' * TrueType tables. The values are expressed in font units. * * @fields: * advance :: * The advance width or height for the glyph. * * bearing :: * The left-side or top-side bearing for the glyph. */ typedef struct TT_LongMetricsRec_ { FT_UShort advance; FT_Short bearing; } TT_LongMetricsRec, *TT_LongMetrics; /************************************************************************** * * @type: * TT_ShortMetrics * * @description: * A simple type to model the short metrics of the 'hmtx' and 'vmtx' * tables. */ typedef FT_Short TT_ShortMetrics; /************************************************************************** * * @struct: * TT_NameRec * * @description: * A structure modeling TrueType name records. Name records are used to * store important strings like family name, style name, copyright, * etc. in _localized_ versions (i.e., language, encoding, etc). * * @fields: * platformID :: * The ID of the name's encoding platform. * * encodingID :: * The platform-specific ID for the name's encoding. * * languageID :: * The platform-specific ID for the name's language. * * nameID :: * The ID specifying what kind of name this is. * * stringLength :: * The length of the string in bytes. * * stringOffset :: * The offset to the string in the 'name' table. * * string :: * A pointer to the string's bytes. Note that these are usually UTF-16 * encoded characters. */ typedef struct TT_NameRec_ { FT_UShort platformID; FT_UShort encodingID; FT_UShort languageID; FT_UShort nameID; FT_UShort stringLength; FT_ULong stringOffset; /* this last field is not defined in the spec */ /* but used by the FreeType engine */ FT_Byte* string; } TT_NameRec, *TT_Name; /************************************************************************** * * @struct: * TT_LangTagRec * * @description: * A structure modeling language tag records in SFNT 'name' tables, * introduced in OpenType version 1.6. * * @fields: * stringLength :: * The length of the string in bytes. * * stringOffset :: * The offset to the string in the 'name' table. * * string :: * A pointer to the string's bytes. Note that these are UTF-16BE * encoded characters. */ typedef struct TT_LangTagRec_ { FT_UShort stringLength; FT_ULong stringOffset; /* this last field is not defined in the spec */ /* but used by the FreeType engine */ FT_Byte* string; } TT_LangTagRec, *TT_LangTag; /************************************************************************** * * @struct: * TT_NameTableRec * * @description: * A structure modeling the TrueType name table. * * @fields: * format :: * The format of the name table. * * numNameRecords :: * The number of names in table. * * storageOffset :: * The offset of the name table in the 'name' TrueType table. * * names :: * An array of name records. * * numLangTagRecords :: * The number of language tags in table. * * langTags :: * An array of language tag records. * * stream :: * The file's input stream. */ typedef struct TT_NameTableRec_ { FT_UShort format; FT_UInt numNameRecords; FT_UInt storageOffset; TT_NameRec* names; FT_UInt numLangTagRecords; TT_LangTagRec* langTags; FT_Stream stream; } TT_NameTableRec, *TT_NameTable; /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** OPTIONAL TRUETYPE/OPENTYPE TABLES DEFINITIONS ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /************************************************************************** * * @struct: * TT_GaspRangeRec * * @description: * A tiny structure used to model a gasp range according to the TrueType * specification. * * @fields: * maxPPEM :: * The maximum ppem value to which `gaspFlag` applies. * * gaspFlag :: * A flag describing the grid-fitting and anti-aliasing modes to be * used. */ typedef struct TT_GaspRangeRec_ { FT_UShort maxPPEM; FT_UShort gaspFlag; } TT_GaspRangeRec, *TT_GaspRange; #define TT_GASP_GRIDFIT 0x01 #define TT_GASP_DOGRAY 0x02 /************************************************************************** * * @struct: * TT_GaspRec * * @description: * A structure modeling the TrueType 'gasp' table used to specify * grid-fitting and anti-aliasing behaviour. * * @fields: * version :: * The version number. * * numRanges :: * The number of gasp ranges in table. * * gaspRanges :: * An array of gasp ranges. */ typedef struct TT_Gasp_ { FT_UShort version; FT_UShort numRanges; TT_GaspRange gaspRanges; } TT_GaspRec; /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** EMBEDDED BITMAPS SUPPORT ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /************************************************************************** * * @struct: * TT_SBit_MetricsRec * * @description: * A structure used to hold the big metrics of a given glyph bitmap in a * TrueType or OpenType font. These are usually found in the 'EBDT' * (Microsoft) or 'bloc' (Apple) table. * * @fields: * height :: * The glyph height in pixels. * * width :: * The glyph width in pixels. * * horiBearingX :: * The horizontal left bearing. * * horiBearingY :: * The horizontal top bearing. * * horiAdvance :: * The horizontal advance. * * vertBearingX :: * The vertical left bearing. * * vertBearingY :: * The vertical top bearing. * * vertAdvance :: * The vertical advance. */ typedef struct TT_SBit_MetricsRec_ { FT_UShort height; FT_UShort width; FT_Short horiBearingX; FT_Short horiBearingY; FT_UShort horiAdvance; FT_Short vertBearingX; FT_Short vertBearingY; FT_UShort vertAdvance; } TT_SBit_MetricsRec, *TT_SBit_Metrics; /************************************************************************** * * @struct: * TT_SBit_SmallMetricsRec * * @description: * A structure used to hold the small metrics of a given glyph bitmap in * a TrueType or OpenType font. These are usually found in the 'EBDT' * (Microsoft) or the 'bdat' (Apple) table. * * @fields: * height :: * The glyph height in pixels. * * width :: * The glyph width in pixels. * * bearingX :: * The left-side bearing. * * bearingY :: * The top-side bearing. * * advance :: * The advance width or height. */ typedef struct TT_SBit_Small_Metrics_ { FT_Byte height; FT_Byte width; FT_Char bearingX; FT_Char bearingY; FT_Byte advance; } TT_SBit_SmallMetricsRec, *TT_SBit_SmallMetrics; /************************************************************************** * * @struct: * TT_SBit_LineMetricsRec * * @description: * A structure used to describe the text line metrics of a given bitmap * strike, for either a horizontal or vertical layout. * * @fields: * ascender :: * The ascender in pixels. * * descender :: * The descender in pixels. * * max_width :: * The maximum glyph width in pixels. * * caret_slope_enumerator :: * Rise of the caret slope, typically set to 1 for non-italic fonts. * * caret_slope_denominator :: * Rise of the caret slope, typically set to 0 for non-italic fonts. * * caret_offset :: * Offset in pixels to move the caret for proper positioning. * * min_origin_SB :: * Minimum of horiBearingX (resp. vertBearingY). * min_advance_SB :: * Minimum of * * horizontal advance - ( horiBearingX + width ) * * resp. * * vertical advance - ( vertBearingY + height ) * * max_before_BL :: * Maximum of horiBearingY (resp. vertBearingY). * * min_after_BL :: * Minimum of * * horiBearingY - height * * resp. * * vertBearingX - width * * pads :: * Unused (to make the size of the record a multiple of 32 bits. */ typedef struct TT_SBit_LineMetricsRec_ { FT_Char ascender; FT_Char descender; FT_Byte max_width; FT_Char caret_slope_numerator; FT_Char caret_slope_denominator; FT_Char caret_offset; FT_Char min_origin_SB; FT_Char min_advance_SB; FT_Char max_before_BL; FT_Char min_after_BL; FT_Char pads[2]; } TT_SBit_LineMetricsRec, *TT_SBit_LineMetrics; /************************************************************************** * * @struct: * TT_SBit_RangeRec * * @description: * A TrueType/OpenType subIndexTable as defined in the 'EBLC' (Microsoft) * or 'bloc' (Apple) tables. * * @fields: * first_glyph :: * The first glyph index in the range. * * last_glyph :: * The last glyph index in the range. * * index_format :: * The format of index table. Valid values are 1 to 5. * * image_format :: * The format of 'EBDT' image data. * * image_offset :: * The offset to image data in 'EBDT'. * * image_size :: * For index formats 2 and 5. This is the size in bytes of each glyph * bitmap. * * big_metrics :: * For index formats 2 and 5. This is the big metrics for each glyph * bitmap. * * num_glyphs :: * For index formats 4 and 5. This is the number of glyphs in the code * array. * * glyph_offsets :: * For index formats 1 and 3. * * glyph_codes :: * For index formats 4 and 5. * * table_offset :: * The offset of the index table in the 'EBLC' table. Only used during * strike loading. */ typedef struct TT_SBit_RangeRec_ { FT_UShort first_glyph; FT_UShort last_glyph; FT_UShort index_format; FT_UShort image_format; FT_ULong image_offset; FT_ULong image_size; TT_SBit_MetricsRec metrics; FT_ULong num_glyphs; FT_ULong* glyph_offsets; FT_UShort* glyph_codes; FT_ULong table_offset; } TT_SBit_RangeRec, *TT_SBit_Range; /************************************************************************** * * @struct: * TT_SBit_StrikeRec * * @description: * A structure used describe a given bitmap strike in the 'EBLC' * (Microsoft) or 'bloc' (Apple) tables. * * @fields: * num_index_ranges :: * The number of index ranges. * * index_ranges :: * An array of glyph index ranges. * * color_ref :: * Unused. `color_ref` is put in for future enhancements, but these * fields are already in use by other platforms (e.g. Newton). For * details, please see * * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6bloc.html * * hori :: * The line metrics for horizontal layouts. * * vert :: * The line metrics for vertical layouts. * * start_glyph :: * The lowest glyph index for this strike. * * end_glyph :: * The highest glyph index for this strike. * * x_ppem :: * The number of horizontal pixels per EM. * * y_ppem :: * The number of vertical pixels per EM. * * bit_depth :: * The bit depth. Valid values are 1, 2, 4, and 8. * * flags :: * Is this a vertical or horizontal strike? For details, please see * * https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6bloc.html */ typedef struct TT_SBit_StrikeRec_ { FT_Int num_ranges; TT_SBit_Range sbit_ranges; FT_ULong ranges_offset; FT_ULong color_ref; TT_SBit_LineMetricsRec hori; TT_SBit_LineMetricsRec vert; FT_UShort start_glyph; FT_UShort end_glyph; FT_Byte x_ppem; FT_Byte y_ppem; FT_Byte bit_depth; FT_Char flags; } TT_SBit_StrikeRec, *TT_SBit_Strike; /************************************************************************** * * @struct: * TT_SBit_ComponentRec * * @description: * A simple structure to describe a compound sbit element. * * @fields: * glyph_code :: * The element's glyph index. * * x_offset :: * The element's left bearing. * * y_offset :: * The element's top bearing. */ typedef struct TT_SBit_ComponentRec_ { FT_UShort glyph_code; FT_Char x_offset; FT_Char y_offset; } TT_SBit_ComponentRec, *TT_SBit_Component; /************************************************************************** * * @struct: * TT_SBit_ScaleRec * * @description: * A structure used describe a given bitmap scaling table, as defined in * the 'EBSC' table. * * @fields: * hori :: * The horizontal line metrics. * * vert :: * The vertical line metrics. * * x_ppem :: * The number of horizontal pixels per EM. * * y_ppem :: * The number of vertical pixels per EM. * * x_ppem_substitute :: * Substitution x_ppem value. * * y_ppem_substitute :: * Substitution y_ppem value. */ typedef struct TT_SBit_ScaleRec_ { TT_SBit_LineMetricsRec hori; TT_SBit_LineMetricsRec vert; FT_Byte x_ppem; FT_Byte y_ppem; FT_Byte x_ppem_substitute; FT_Byte y_ppem_substitute; } TT_SBit_ScaleRec, *TT_SBit_Scale; /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** POSTSCRIPT GLYPH NAMES SUPPORT ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /************************************************************************** * * @struct: * TT_Post_20Rec * * @description: * Postscript names sub-table, format 2.0. Stores the PS name of each * glyph in the font face. * * @fields: * num_glyphs :: * The number of named glyphs in the table. * * num_names :: * The number of PS names stored in the table. * * glyph_indices :: * The indices of the glyphs in the names arrays. * * glyph_names :: * The PS names not in Mac Encoding. */ typedef struct TT_Post_20Rec_ { FT_UShort num_glyphs; FT_UShort num_names; FT_UShort* glyph_indices; FT_Char** glyph_names; } TT_Post_20Rec, *TT_Post_20; /************************************************************************** * * @struct: * TT_Post_25Rec * * @description: * Postscript names sub-table, format 2.5. Stores the PS name of each * glyph in the font face. * * @fields: * num_glyphs :: * The number of glyphs in the table. * * offsets :: * An array of signed offsets in a normal Mac Postscript name encoding. */ typedef struct TT_Post_25_ { FT_UShort num_glyphs; FT_Char* offsets; } TT_Post_25Rec, *TT_Post_25; /************************************************************************** * * @struct: * TT_Post_NamesRec * * @description: * Postscript names table, either format 2.0 or 2.5. * * @fields: * loaded :: * A flag to indicate whether the PS names are loaded. * * format_20 :: * The sub-table used for format 2.0. * * format_25 :: * The sub-table used for format 2.5. */ typedef struct TT_Post_NamesRec_ { FT_Bool loaded; union { TT_Post_20Rec format_20; TT_Post_25Rec format_25; } names; } TT_Post_NamesRec, *TT_Post_Names; /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** GX VARIATION TABLE SUPPORT ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT typedef struct GX_BlendRec_ *GX_Blend; #endif /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** EMBEDDED BDF PROPERTIES TABLE SUPPORT ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /* * These types are used to support a `BDF ' table that isn't part of the * official TrueType specification. It is mainly used in SFNT-based bitmap * fonts that were generated from a set of BDF fonts. * * The format of the table is as follows. * * USHORT version `BDF ' table version number, should be 0x0001. USHORT * strikeCount Number of strikes (bitmap sizes) in this table. ULONG * stringTable Offset (from start of BDF table) to string * table. * * This is followed by an array of `strikeCount' descriptors, having the * following format. * * USHORT ppem Vertical pixels per EM for this strike. USHORT numItems * Number of items for this strike (properties and * atoms). Maximum is 255. * * This array in turn is followed by `strikeCount' value sets. Each `value * set' is an array of `numItems' items with the following format. * * ULONG item_name Offset in string table to item name. * USHORT item_type The item type. Possible values are * 0 => string (e.g., COMMENT) * 1 => atom (e.g., FONT or even SIZE) * 2 => int32 * 3 => uint32 * 0x10 => A flag to indicate a properties. This * is ORed with the above values. * ULONG item_value For strings => Offset into string table without * the corresponding double quotes. * For atoms => Offset into string table. * For integers => Direct value. * * All strings in the string table consist of bytes and are * zero-terminated. * */ #ifdef TT_CONFIG_OPTION_BDF typedef struct TT_BDFRec_ { FT_Byte* table; FT_Byte* table_end; FT_Byte* strings; FT_ULong strings_size; FT_UInt num_strikes; FT_Bool loaded; } TT_BDFRec, *TT_BDF; #endif /* TT_CONFIG_OPTION_BDF */ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /*** ***/ /*** ***/ /*** ORIGINAL TT_FACE CLASS DEFINITION ***/ /*** ***/ /*** ***/ /*************************************************************************/ /*************************************************************************/ /*************************************************************************/ /************************************************************************** * * This structure/class is defined here because it is common to the * following formats: TTF, OpenType-TT, and OpenType-CFF. * * Note, however, that the classes TT_Size and TT_GlyphSlot are not shared * between font drivers, and are thus defined in `ttobjs.h`. * */ /************************************************************************** * * @type: * TT_Face * * @description: * A handle to a TrueType face/font object. A TT_Face encapsulates the * resolution and scaling independent parts of a TrueType font resource. * * @note: * The TT_Face structure is also used as a 'parent class' for the * OpenType-CFF class (T2_Face). */ typedef struct TT_FaceRec_* TT_Face; /* a function type used for the truetype bytecode interpreter hooks */ typedef FT_Error (*TT_Interpreter)( void* exec_context ); /* forward declaration */ typedef struct TT_LoaderRec_* TT_Loader; /************************************************************************** * * @functype: * TT_Loader_GotoTableFunc * * @description: * Seeks a stream to the start of a given TrueType table. * * @input: * face :: * A handle to the target face object. * * tag :: * A 4-byte tag used to name the table. * * stream :: * The input stream. * * @output: * length :: * The length of the table in bytes. Set to 0 if not needed. * * @return: * FreeType error code. 0 means success. * * @note: * The stream cursor must be at the font file's origin. */ typedef FT_Error (*TT_Loader_GotoTableFunc)( TT_Face face, FT_ULong tag, FT_Stream stream, FT_ULong* length ); /************************************************************************** * * @functype: * TT_Loader_StartGlyphFunc * * @description: * Seeks a stream to the start of a given glyph element, and opens a * frame for it. * * @input: * loader :: * The current TrueType glyph loader object. * * glyph index :: The index of the glyph to access. * * offset :: * The offset of the glyph according to the 'locations' table. * * byte_count :: * The size of the frame in bytes. * * @return: * FreeType error code. 0 means success. * * @note: * This function is normally equivalent to FT_STREAM_SEEK(offset) * followed by FT_FRAME_ENTER(byte_count) with the loader's stream, but * alternative formats (e.g. compressed ones) might use something * different. */ typedef FT_Error (*TT_Loader_StartGlyphFunc)( TT_Loader loader, FT_UInt glyph_index, FT_ULong offset, FT_UInt byte_count ); /************************************************************************** * * @functype: * TT_Loader_ReadGlyphFunc * * @description: * Reads one glyph element (its header, a simple glyph, or a composite) * from the loader's current stream frame. * * @input: * loader :: * The current TrueType glyph loader object. * * @return: * FreeType error code. 0 means success. */ typedef FT_Error (*TT_Loader_ReadGlyphFunc)( TT_Loader loader ); /************************************************************************** * * @functype: * TT_Loader_EndGlyphFunc * * @description: * Closes the current loader stream frame for the glyph. * * @input: * loader :: * The current TrueType glyph loader object. */ typedef void (*TT_Loader_EndGlyphFunc)( TT_Loader loader ); typedef enum TT_SbitTableType_ { TT_SBIT_TABLE_TYPE_NONE = 0, TT_SBIT_TABLE_TYPE_EBLC, /* `EBLC' (Microsoft), */ /* `bloc' (Apple) */ TT_SBIT_TABLE_TYPE_CBLC, /* `CBLC' (Google) */ TT_SBIT_TABLE_TYPE_SBIX, /* `sbix' (Apple) */ /* do not remove */ TT_SBIT_TABLE_TYPE_MAX } TT_SbitTableType; /* OpenType 1.8 brings new tables for variation font support; */ /* to make the old MM and GX fonts still work we need to check */ /* the presence (and validity) of the functionality provided */ /* by those tables. The following flag macros are for the */ /* field `variation_support'. */ /* */ /* Note that `fvar' gets checked immediately at font loading, */ /* while the other features are only loaded if MM support is */ /* actually requested. */ /* FVAR */ #define TT_FACE_FLAG_VAR_FVAR ( 1 << 0 ) /* HVAR */ #define TT_FACE_FLAG_VAR_HADVANCE ( 1 << 1 ) #define TT_FACE_FLAG_VAR_LSB ( 1 << 2 ) #define TT_FACE_FLAG_VAR_RSB ( 1 << 3 ) /* VVAR */ #define TT_FACE_FLAG_VAR_VADVANCE ( 1 << 4 ) #define TT_FACE_FLAG_VAR_TSB ( 1 << 5 ) #define TT_FACE_FLAG_VAR_BSB ( 1 << 6 ) #define TT_FACE_FLAG_VAR_VORG ( 1 << 7 ) /* MVAR */ #define TT_FACE_FLAG_VAR_MVAR ( 1 << 8 ) /************************************************************************** * * TrueType Face Type * * @struct: * TT_Face * * @description: * The TrueType face class. These objects model the resolution and * point-size independent data found in a TrueType font file. * * @fields: * root :: * The base FT_Face structure, managed by the base layer. * * ttc_header :: * The TrueType collection header, used when the file is a 'ttc' rather * than a 'ttf'. For ordinary font files, the field `ttc_header.count` * is set to 0. * * format_tag :: * The font format tag. * * num_tables :: * The number of TrueType tables in this font file. * * dir_tables :: * The directory of TrueType tables for this font file. * * header :: * The font's font header ('head' table). Read on font opening. * * horizontal :: * The font's horizontal header ('hhea' table). This field also * contains the associated horizontal metrics table ('hmtx'). * * max_profile :: * The font's maximum profile table. Read on font opening. Note that * some maximum values cannot be taken directly from this table. We * thus define additional fields below to hold the computed maxima. * * vertical_info :: * A boolean which is set when the font file contains vertical metrics. * If not, the value of the 'vertical' field is undefined. * * vertical :: * The font's vertical header ('vhea' table). This field also contains * the associated vertical metrics table ('vmtx'), if found. * IMPORTANT: The contents of this field is undefined if the * `vertical_info` field is unset. * * num_names :: * The number of name records within this TrueType font. * * name_table :: * The table of name records ('name'). * * os2 :: * The font's OS/2 table ('OS/2'). * * postscript :: * The font's PostScript table ('post' table). The PostScript glyph * names are not loaded by the driver on face opening. See the * 'ttpost' module for more details. * * cmap_table :: * Address of the face's 'cmap' SFNT table in memory (it's an extracted * frame). * * cmap_size :: * The size in bytes of the `cmap_table` described above. * * goto_table :: * A function called by each TrueType table loader to position a * stream's cursor to the start of a given table according to its tag. * It defaults to TT_Goto_Face but can be different for strange formats * (e.g. Type 42). * * access_glyph_frame :: * A function used to access the frame of a given glyph within the * face's font file. * * forget_glyph_frame :: * A function used to forget the frame of a given glyph when all data * has been loaded. * * read_glyph_header :: * A function used to read a glyph header. It must be called between * an 'access' and 'forget'. * * read_simple_glyph :: * A function used to read a simple glyph. It must be called after the * header was read, and before the 'forget'. * * read_composite_glyph :: * A function used to read a composite glyph. It must be called after * the header was read, and before the 'forget'. * * sfnt :: * A pointer to the SFNT service. * * psnames :: * A pointer to the PostScript names service. * * mm :: * A pointer to the Multiple Masters service. * * var :: * A pointer to the Metrics Variations service. * * hdmx :: * The face's horizontal device metrics ('hdmx' table). This table is * optional in TrueType/OpenType fonts. * * gasp :: * The grid-fitting and scaling properties table ('gasp'). This table * is optional in TrueType/OpenType fonts. * * pclt :: * The 'pclt' SFNT table. * * num_sbit_scales :: * The number of sbit scales for this font. * * sbit_scales :: * Array of sbit scales embedded in this font. This table is optional * in a TrueType/OpenType font. * * postscript_names :: * A table used to store the Postscript names of the glyphs for this * font. See the file `ttconfig.h` for comments on the * TT_CONFIG_OPTION_POSTSCRIPT_NAMES option. * * palette_data :: * Some fields from the 'CPAL' table that are directly indexed. * * palette_index :: * The current palette index, as set by @FT_Palette_Select. * * palette :: * An array containing the current palette's colors. * * have_foreground_color :: * There was a call to @FT_Palette_Set_Foreground_Color. * * foreground_color :: * The current foreground color corresponding to 'CPAL' color index * 0xFFFF. Only valid if `have_foreground_color` is set. * * font_program_size :: * Size in bytecodes of the face's font program. 0 if none defined. * Ignored for Type 2 fonts. * * font_program :: * The face's font program (bytecode stream) executed at load time, * also used during glyph rendering. Comes from the 'fpgm' table. * Ignored for Type 2 font fonts. * * cvt_program_size :: * The size in bytecodes of the face's cvt program. Ignored for Type 2 * fonts. * * cvt_program :: * The face's cvt program (bytecode stream) executed each time an * instance/size is changed/reset. Comes from the 'prep' table. * Ignored for Type 2 fonts. * * cvt_size :: * Size of the control value table (in entries). Ignored for Type 2 * fonts. * * cvt :: * The face's original control value table. Coordinates are expressed * in unscaled font units (in 26.6 format). Comes from the 'cvt~' * table. Ignored for Type 2 fonts. * * If varied by the `CVAR' table, non-integer values are possible. * * interpreter :: * A pointer to the TrueType bytecode interpreters field is also used * to hook the debugger in 'ttdebug'. * * extra :: * Reserved for third-party font drivers. * * postscript_name :: * The PS name of the font. Used by the postscript name service. * * glyf_len :: * The length of the 'glyf' table. Needed for malformed 'loca' tables. * * glyf_offset :: * The file offset of the 'glyf' table. * * is_cff2 :: * Set if the font format is CFF2. * * doblend :: * A boolean which is set if the font should be blended (this is for GX * var). * * blend :: * Contains the data needed to control GX variation tables (rather like * Multiple Master data). * * variation_support :: * Flags that indicate which OpenType functionality related to font * variation support is present, valid, and usable. For example, * TT_FACE_FLAG_VAR_FVAR is only set if we have at least one design * axis. * * var_postscript_prefix :: * The PostScript name prefix needed for constructing a variation font * instance's PS name . * * var_postscript_prefix_len :: * The length of the `var_postscript_prefix` string. * * horz_metrics_size :: * The size of the 'hmtx' table. * * vert_metrics_size :: * The size of the 'vmtx' table. * * num_locations :: * The number of glyph locations in this TrueType file. This should be * identical to the number of glyphs. Ignored for Type 2 fonts. * * glyph_locations :: * An array of longs. These are offsets to glyph data within the * 'glyf' table. Ignored for Type 2 font faces. * * hdmx_table :: * A pointer to the 'hdmx' table. * * hdmx_table_size :: * The size of the 'hdmx' table. * * hdmx_record_count :: * The number of hdmx records. * * hdmx_record_size :: * The size of a single hdmx record. * * hdmx_record_sizes :: * An array holding the ppem sizes available in the 'hdmx' table. * * sbit_table :: * A pointer to the font's embedded bitmap location table. * * sbit_table_size :: * The size of `sbit_table`. * * sbit_table_type :: * The sbit table type (CBLC, sbix, etc.). * * sbit_num_strikes :: * The number of sbit strikes exposed by FreeType's API, omitting * invalid strikes. * * sbit_strike_map :: * A mapping between the strike indices exposed by the API and the * indices used in the font's sbit table. * * cpal :: * A pointer to data related to the 'CPAL' table. `NULL` if the table * is not available. * * colr :: * A pointer to data related to the 'COLR' table. `NULL` if the table * is not available. * * kern_table :: * A pointer to the 'kern' table. * * kern_table_size :: * The size of the 'kern' table. * * num_kern_tables :: * The number of supported kern subtables (up to 32; FreeType * recognizes only horizontal ones with format 0). * * kern_avail_bits :: * The availability status of kern subtables; if bit n is set, table n * is available. * * kern_order_bits :: * The sortedness status of kern subtables; if bit n is set, table n is * sorted. * * bdf :: * Data related to an SFNT font's 'bdf' table; see `tttypes.h`. * * horz_metrics_offset :: * The file offset of the 'hmtx' table. * * vert_metrics_offset :: * The file offset of the 'vmtx' table. * * sph_found_func_flags :: * Flags identifying special bytecode functions (used by the v38 * implementation of the bytecode interpreter). * * sph_compatibility_mode :: * This flag is set if we are in ClearType backward compatibility mode * (used by the v38 implementation of the bytecode interpreter). * * ebdt_start :: * The file offset of the sbit data table (CBDT, bdat, etc.). * * ebdt_size :: * The size of the sbit data table. */ typedef struct TT_FaceRec_ { FT_FaceRec root; TTC_HeaderRec ttc_header; FT_ULong format_tag; FT_UShort num_tables; TT_Table dir_tables; TT_Header header; /* TrueType header table */ TT_HoriHeader horizontal; /* TrueType horizontal header */ TT_MaxProfile max_profile; FT_Bool vertical_info; TT_VertHeader vertical; /* TT Vertical header, if present */ FT_UShort num_names; /* number of name records */ TT_NameTableRec name_table; /* name table */ TT_OS2 os2; /* TrueType OS/2 table */ TT_Postscript postscript; /* TrueType Postscript table */ FT_Byte* cmap_table; /* extracted `cmap' table */ FT_ULong cmap_size; TT_Loader_GotoTableFunc goto_table; TT_Loader_StartGlyphFunc access_glyph_frame; TT_Loader_EndGlyphFunc forget_glyph_frame; TT_Loader_ReadGlyphFunc read_glyph_header; TT_Loader_ReadGlyphFunc read_simple_glyph; TT_Loader_ReadGlyphFunc read_composite_glyph; /* a typeless pointer to the SFNT_Interface table used to load */ /* the basic TrueType tables in the face object */ void* sfnt; /* a typeless pointer to the FT_Service_PsCMapsRec table used to */ /* handle glyph names <-> unicode & Mac values */ void* psnames; #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT /* a typeless pointer to the FT_Service_MultiMasters table used to */ /* handle variation fonts */ void* mm; /* a typeless pointer to the FT_Service_MetricsVariationsRec table */ /* used to handle the HVAR, VVAR, and MVAR OpenType tables */ void* var; #endif /* a typeless pointer to the PostScript Aux service */ void* psaux; /************************************************************************ * * Optional TrueType/OpenType tables * */ /* grid-fitting and scaling table */ TT_GaspRec gasp; /* the `gasp' table */ /* PCL 5 table */ TT_PCLT pclt; /* embedded bitmaps support */ FT_ULong num_sbit_scales; TT_SBit_Scale sbit_scales; /* postscript names table */ TT_Post_NamesRec postscript_names; /* glyph colors */ FT_Palette_Data palette_data; /* since 2.10 */ FT_UShort palette_index; FT_Color* palette; FT_Bool have_foreground_color; FT_Color foreground_color; /************************************************************************ * * TrueType-specific fields (ignored by the CFF driver) * */ /* the font program, if any */ FT_ULong font_program_size; FT_Byte* font_program; /* the cvt program, if any */ FT_ULong cvt_program_size; FT_Byte* cvt_program; /* the original, unscaled, control value table */ FT_ULong cvt_size; FT_Int32* cvt; /* A pointer to the bytecode interpreter to use. This is also */ /* used to hook the debugger for the `ttdebug' utility. */ TT_Interpreter interpreter; /************************************************************************ * * Other tables or fields. This is used by derivative formats like * OpenType. * */ FT_Generic extra; const char* postscript_name; FT_ULong glyf_len; FT_ULong glyf_offset; /* since 2.7.1 */ FT_Bool is_cff2; /* since 2.7.1 */ #ifdef TT_CONFIG_OPTION_GX_VAR_SUPPORT FT_Bool doblend; GX_Blend blend; FT_UInt32 variation_support; /* since 2.7.1 */ const char* var_postscript_prefix; /* since 2.7.2 */ FT_UInt var_postscript_prefix_len; /* since 2.7.2 */ #endif /* since version 2.2 */ FT_ULong horz_metrics_size; FT_ULong vert_metrics_size; FT_ULong num_locations; /* in broken TTF, gid > 0xFFFF */ FT_Byte* glyph_locations; FT_Byte* hdmx_table; FT_ULong hdmx_table_size; FT_UInt hdmx_record_count; FT_ULong hdmx_record_size; FT_Byte* hdmx_record_sizes; FT_Byte* sbit_table; FT_ULong sbit_table_size; TT_SbitTableType sbit_table_type; FT_UInt sbit_num_strikes; FT_UInt* sbit_strike_map; FT_Byte* kern_table; FT_ULong kern_table_size; FT_UInt num_kern_tables; FT_UInt32 kern_avail_bits; FT_UInt32 kern_order_bits; #ifdef TT_CONFIG_OPTION_BDF TT_BDFRec bdf; #endif /* TT_CONFIG_OPTION_BDF */ /* since 2.3.0 */ FT_ULong horz_metrics_offset; FT_ULong vert_metrics_offset; #ifdef TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY /* since 2.4.12 */ FT_ULong sph_found_func_flags; /* special functions found */ /* for this face */ FT_Bool sph_compatibility_mode; #endif /* TT_SUPPORT_SUBPIXEL_HINTING_INFINALITY */ #ifdef TT_CONFIG_OPTION_EMBEDDED_BITMAPS /* since 2.7 */ FT_ULong ebdt_start; /* either `CBDT', `EBDT', or `bdat' */ FT_ULong ebdt_size; #endif /* since 2.10 */ void* cpal; void* colr; } TT_FaceRec; /************************************************************************** * * @struct: * TT_GlyphZoneRec * * @description: * A glyph zone is used to load, scale and hint glyph outline * coordinates. * * @fields: * memory :: * A handle to the memory manager. * * max_points :: * The maximum size in points of the zone. * * max_contours :: * Max size in links contours of the zone. * * n_points :: * The current number of points in the zone. * * n_contours :: * The current number of contours in the zone. * * org :: * The original glyph coordinates (font units/scaled). * * cur :: * The current glyph coordinates (scaled/hinted). * * tags :: * The point control tags. * * contours :: * The contours end points. * * first_point :: * Offset of the current subglyph's first point. */ typedef struct TT_GlyphZoneRec_ { FT_Memory memory; FT_UShort max_points; FT_Short max_contours; FT_UShort n_points; /* number of points in zone */ FT_Short n_contours; /* number of contours */ FT_Vector* org; /* original point coordinates */ FT_Vector* cur; /* current point coordinates */ FT_Vector* orus; /* original (unscaled) point coordinates */ FT_Byte* tags; /* current touch flags */ FT_UShort* contours; /* contour end points */ FT_UShort first_point; /* offset of first (#0) point */ } TT_GlyphZoneRec, *TT_GlyphZone; /* handle to execution context */ typedef struct TT_ExecContextRec_* TT_ExecContext; /************************************************************************** * * @type: * TT_Size * * @description: * A handle to a TrueType size object. */ typedef struct TT_SizeRec_* TT_Size; /* glyph loader structure */ typedef struct TT_LoaderRec_ { TT_Face face; TT_Size size; FT_GlyphSlot glyph; FT_GlyphLoader gloader; FT_ULong load_flags; FT_UInt glyph_index; FT_Stream stream; FT_Int byte_len; FT_Short n_contours; FT_BBox bbox; FT_Int left_bearing; FT_Int advance; FT_Int linear; FT_Bool linear_def; FT_Vector pp1; FT_Vector pp2; /* the zone where we load our glyphs */ TT_GlyphZoneRec base; TT_GlyphZoneRec zone; TT_ExecContext exec; FT_Byte* instructions; FT_ULong ins_pos; /* for possible extensibility in other formats */ void* other; /* since version 2.1.8 */ FT_Int top_bearing; FT_Int vadvance; FT_Vector pp3; FT_Vector pp4; /* since version 2.2.1 */ FT_Byte* cursor; FT_Byte* limit; /* since version 2.6.2 */ FT_ListRec composites; } TT_LoaderRec; FT_END_HEADER #endif /* TTTYPES_H_ */ /* END */
daid/SeriousProton
libs/freetype2/include/freetype/internal/tttypes.h
C
mit
52,829
/* */ "format register"; define(["exports","aurelia-metadata","./behavior-instance","./behaviors","./util"], function (exports, _aureliaMetadata, _behaviorInstance, _behaviors, _util) { "use strict"; var _prototypeProperties = function (child, staticProps, instanceProps) { if (staticProps) Object.defineProperties(child, staticProps); if (instanceProps) Object.defineProperties(child.prototype, instanceProps); }; var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; var ResourceType = _aureliaMetadata.ResourceType; var BehaviorInstance = _behaviorInstance.BehaviorInstance; var configureBehavior = _behaviors.configureBehavior; var hyphenate = _util.hyphenate; var TemplateController = (function (ResourceType) { function TemplateController(attribute) { this.name = attribute; this.properties = []; this.attributes = {}; this.liftsContent = true; } _inherits(TemplateController, ResourceType); _prototypeProperties(TemplateController, { convention: { value: function convention(name) { if (name.endsWith("TemplateController")) { return new TemplateController(hyphenate(name.substring(0, name.length - 18))); } }, writable: true, enumerable: true, configurable: true } }, { analyze: { value: function analyze(container, target) { configureBehavior(container, this, target); }, writable: true, enumerable: true, configurable: true }, load: { value: function load(container, target) { return Promise.resolve(this); }, writable: true, enumerable: true, configurable: true }, register: { value: function register(registry, name) { registry.registerAttribute(name || this.name, this, this.name); }, writable: true, enumerable: true, configurable: true }, compile: { value: function compile(compiler, resources, node, instruction, parentNode) { if (!instruction.viewFactory) { var template = document.createElement("template"), fragment = document.createDocumentFragment(); node.removeAttribute(instruction.originalAttrName); if (node.parentNode) { node.parentNode.replaceChild(template, node); } else if (window.ShadowDOMPolyfill) { ShadowDOMPolyfill.unwrap(parentNode).replaceChild(ShadowDOMPolyfill.unwrap(template), ShadowDOMPolyfill.unwrap(node)); } else { parentNode.replaceChild(template, node); } fragment.appendChild(node); instruction.viewFactory = compiler.compile(fragment, resources); node = template; } instruction.suppressBind = true; return node; }, writable: true, enumerable: true, configurable: true }, create: { value: function create(container, instruction, element) { var executionContext = instruction.executionContext || container.get(this.target), behaviorInstance = new BehaviorInstance(this, executionContext, instruction); element.primaryBehavior = behaviorInstance; return behaviorInstance; }, writable: true, enumerable: true, configurable: true } }); return TemplateController; })(ResourceType); exports.TemplateController = TemplateController; });
sonnylazuardi/todomvc-aurelia
lib/github/aurelia/[email protected]/amd/template-controller.js
JavaScript
mit
4,047
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Style::RescueStandardError, :config do context 'implicit' do let(:cop_config) do { 'EnforcedStyle' => 'implicit', 'SupportedStyles' => %w[implicit explicit] } end context 'when rescuing in a begin block' do it 'accpets rescuing no error class' do expect_no_offenses(<<~RUBY) begin foo rescue bar end RUBY end it 'accepts rescuing no error class, assigned to a variable' do expect_no_offenses(<<~RUBY) begin foo rescue => e bar end RUBY end it 'accepts rescuing a single error class other than StandardError' do expect_no_offenses(<<~RUBY) begin foo rescue BarError bar end RUBY end it 'accepts rescuing a single error class other than StandardError, assigned to a variable' do expect_no_offenses(<<~RUBY) begin foo rescue BarError => e bar end RUBY end context 'when rescuing StandardError by itself' do it 'registers an offense' do expect_offense(<<~RUBY) begin foo rescue StandardError ^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself. bar end RUBY expect_correction(<<~RUBY) begin foo rescue bar end RUBY end context 'with ::StandardError' do it 'registers an offense' do expect_offense(<<~RUBY) begin foo rescue ::StandardError ^^^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself. bar end RUBY expect_correction(<<~RUBY) begin foo rescue bar end RUBY end end context 'when the error is assigned to a variable' do it 'registers an offense' do expect_offense(<<~RUBY) begin foo rescue StandardError => e ^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself. bar end RUBY expect_correction(<<~RUBY) begin foo rescue => e bar end RUBY end context 'with ::StandardError' do it 'registers an offense' do expect_offense(<<~RUBY) begin foo rescue ::StandardError => e ^^^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself. bar end RUBY end end end end it 'accepts rescuing StandardError with other errors' do expect_no_offenses(<<~RUBY) begin foo rescue StandardError, BarError bar rescue BazError, StandardError baz end RUBY end it 'accepts rescuing ::StandardError with other errors' do expect_no_offenses(<<~RUBY) begin foo rescue ::StandardError, BarError bar rescue ::BazError, ::StandardError baz end RUBY end it 'accepts rescuing StandardError with other errors, assigned to a variable' do expect_no_offenses(<<~RUBY) begin foo rescue StandardError, BarError => e bar rescue BazError, StandardError => e baz end RUBY end end context 'when rescuing in a method definition' do it 'accepts rescuing no error class' do expect_no_offenses(<<~RUBY) def baz foo rescue bar end RUBY end it 'accepts rescuing no error class, assigned to a variable' do expect_no_offenses(<<~RUBY) def baz foo rescue => e bar end RUBY end it 'accepts rescuing a single error other than StandardError' do expect_no_offenses(<<~RUBY) def baz foo rescue BarError bar end RUBY end it 'accepts rescuing a single error other than StandardError, assigned to a variable' do expect_no_offenses(<<~RUBY) def baz foo rescue BarError => e bar end RUBY end context 'when rescuing StandardError by itself' do it 'registers an offense' do expect_offense(<<~RUBY) def foobar foo rescue StandardError ^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself. bar end RUBY expect_correction(<<~RUBY) def foobar foo rescue bar end RUBY end context 'when the error is assigned to a variable' do it 'registers an offense' do expect_offense(<<~RUBY) def foobar foo rescue StandardError => e ^^^^^^^^^^^^^^^^^^^^ Omit the error class when rescuing `StandardError` by itself. bar end RUBY expect_correction(<<~RUBY) def foobar foo rescue => e bar end RUBY end end end it 'accepts rescuing StandardError with other errors' do expect_no_offenses(<<~RUBY) def foobar foo rescue StandardError, BarError bar rescue BazError, StandardError baz end RUBY end it 'accepts rescuing StandardError with other errors, assigned to a variable' do expect_no_offenses(<<~RUBY) def foobar foo rescue StandardError, BarError => e bar rescue BazError, StandardError => e baz end RUBY end end it 'accepts rescue modifier' do expect_no_offenses(<<~RUBY) foo rescue 42 RUBY end end context 'explicit' do let(:cop_config) do { 'EnforcedStyle' => 'explicit', 'SupportedStyles' => %w[implicit explicit] } end context 'when rescuing in a begin block' do context 'when calling rescue without an error class' do it 'registers an offense' do expect_offense(<<~RUBY) begin foo rescue ^^^^^^ Avoid rescuing without specifying an error class. bar end RUBY expect_correction(<<~RUBY) begin foo rescue StandardError bar end RUBY end context 'when the error is assigned to a variable' do it 'registers an offense' do expect_offense(<<~RUBY) begin foo rescue => e ^^^^^^ Avoid rescuing without specifying an error class. bar end RUBY expect_correction(<<~RUBY) begin foo rescue StandardError => e bar end RUBY end end end it 'accepts rescuing a single error other than StandardError' do expect_no_offenses(<<~RUBY) begin foo rescue BarError bar end RUBY end it 'accepts rescuing a single error other than StandardErrorassigned to a variable' do expect_no_offenses(<<~RUBY) begin foo rescue BarError => e bar end RUBY end it 'accepts rescuing StandardError by itself' do expect_no_offenses(<<~RUBY) begin foo rescue StandardError bar end RUBY end it 'accepts rescuing StandardError by itself, assigned to a variable' do expect_no_offenses(<<~RUBY) begin foo rescue StandardError => e bar end RUBY end it 'accepts rescuing StandardError with other errors' do expect_no_offenses(<<~RUBY) begin foo rescue StandardError, BarError bar rescue BazError, StandardError baz end RUBY end it 'accepts rescuing StandardError with other errors, assigned to a variable' do expect_no_offenses(<<~RUBY) begin foo rescue StandardError, BarError => e bar rescue BazError, StandardError => e baz end RUBY end end context 'when rescuing in a method definition' do context 'when rescue is called without an error class' do it 'registers an offense' do expect_offense(<<~RUBY) def baz foo rescue ^^^^^^ Avoid rescuing without specifying an error class. bar end RUBY expect_correction(<<~RUBY) def baz foo rescue StandardError bar end RUBY end end context 'when the error is assigned to a variable' do it 'registers an offense' do expect_offense(<<~RUBY) def baz foo rescue => e ^^^^^^ Avoid rescuing without specifying an error class. bar end RUBY expect_correction(<<~RUBY) def baz foo rescue StandardError => e bar end RUBY end end it 'accepts rescueing a single error other than StandardError' do expect_no_offenses(<<~RUBY) def baz foo rescue BarError bar end RUBY end it 'accepts rescueing a single error other than StandardError, assigned to a variable' do expect_no_offenses(<<~RUBY) def baz foo rescue BarError => e bar end RUBY end it 'accepts rescuing StandardError by itself' do expect_no_offenses(<<~RUBY) def foobar foo rescue StandardError bar end RUBY end it 'accepts rescuing StandardError by itself, assigned to a variable' do expect_no_offenses(<<~RUBY) def foobar foo rescue StandardError => e bar end RUBY end it 'accepts rescuing StandardError with other errors' do expect_no_offenses(<<~RUBY) def foobar foo rescue StandardError, BarError bar rescue BazError, StandardError baz end RUBY end it 'accepts rescuing StandardError with other errors, assigned to a variable' do expect_no_offenses(<<~RUBY) def foobar foo rescue StandardError, BarError => e bar rescue BazError, StandardError => e baz end RUBY end end it 'accepts rescue modifier' do expect_no_offenses(<<~RUBY) foo rescue 42 RUBY end end end
tejasbubane/rubocop
spec/rubocop/cop/style/rescue_standard_error_spec.rb
Ruby
mit
12,258
require 'mspec/runner/formatters/base' class YamlFormatter < BaseFormatter def initialize(out = nil) super(nil) if out.nil? @finish = $stdout else @finish = File.open out, "w" end end def switch @out = @finish end def finish switch print "---\n" print "exceptions:\n" @exceptions.each do |exc| outcome = exc.failure? ? "FAILED" : "ERROR" str = "#{exc.description} #{outcome}\n" str << exc.message << "\n" << exc.backtrace print "- ", str.inspect, "\n" end print "time: ", @timer.elapsed, "\n" print "files: ", @tally.counter.files, "\n" print "examples: ", @tally.counter.examples, "\n" print "expectations: ", @tally.counter.expectations, "\n" print "failures: ", @tally.counter.failures, "\n" print "errors: ", @tally.counter.errors, "\n" print "tagged: ", @tally.counter.tagged, "\n" end end
pmq20/ruby-compiler
ruby/spec/mspec/lib/mspec/runner/formatters/yaml.rb
Ruby
mit
993
.root{ width: 360px; margin: 0 auto; background: #fff; padding: 20px; }
envman/e-net
web/src/views/Main/Login/styles.module.css
CSS
mit
80
package com.xeiam.xchange.poloniex.service.marketdata; import static org.fest.assertions.api.Assertions.assertThat; import org.junit.Test; import com.xeiam.xchange.Exchange; import com.xeiam.xchange.ExchangeFactory; import com.xeiam.xchange.currency.CurrencyPair; import com.xeiam.xchange.dto.marketdata.Ticker; import com.xeiam.xchange.poloniex.PoloniexExchange; import com.xeiam.xchange.service.polling.marketdata.PollingMarketDataService; /** * @author timmolter */ public class TickerFetchIntegration { @Test public void tickerFetchTest() throws Exception { Exchange exchange = ExchangeFactory.INSTANCE.createExchange(PoloniexExchange.class.getName()); exchange.remoteInit(); PollingMarketDataService marketDataService = exchange.getPollingMarketDataService(); CurrencyPair currencyPair = exchange.getMetaData().getMarketMetaDataMap().keySet().iterator().next(); Ticker ticker = marketDataService.getTicker(currencyPair); System.out.println(ticker.toString()); assertThat(ticker).isNotNull(); } }
Muffon/XChange
xchange-poloniex/src/test/java/com/xeiam/xchange/poloniex/service/marketdata/TickerFetchIntegration.java
Java
mit
1,044