answer
stringlengths
15
1.25M
// Multi-threading test // This software is provided 'as-is', without any express or implied // arising from the use of this software. // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // 3. This notice may not be removed or altered from any source // distribution. // This test is intended to verify whether the OpenGL context part of // the GLFW API is able to be used from multiple threads #include "tinycthread.h" #include <glad/gl.h> #include <GLFW/glfw3.h> #include <stdio.h> #include <stdlib.h> #include <math.h> typedef struct { GLFWwindow* window; const char* title; float r, g, b; thrd_t id; } Thread; static volatile int running = GLFW_TRUE; static void error_callback(int error, const char* description) { fprintf(stderr, "Error: %s\n", description); } static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) <API key>(window, GLFW_TRUE); } static int thread_main(void* data) { const Thread* thread = data; <API key>(thread->window); glfwSwapInterval(1); while (running) { const float v = (float) fabs(sin(glfwGetTime() * 2.f)); glClearColor(thread->r * v, thread->g * v, thread->b * v, 0.f); glClear(GL_COLOR_BUFFER_BIT); glfwSwapBuffers(thread->window); } <API key>(NULL); return 0; } int main(void) { int i, result; Thread threads[] = { { NULL, "Red", 1.f, 0.f, 0.f, 0 }, { NULL, "Green", 0.f, 1.f, 0.f, 0 }, { NULL, "Blue", 0.f, 0.f, 1.f, 0 } }; const int count = sizeof(threads) / sizeof(Thread); <API key>(error_callback); if (!glfwInit()) exit(EXIT_FAILURE); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); for (i = 0; i < count; i++) { threads[i].window = glfwCreateWindow(200, 200, threads[i].title, NULL, NULL); if (!threads[i].window) { glfwTerminate(); exit(EXIT_FAILURE); } glfwSetKeyCallback(threads[i].window, key_callback); glfwSetWindowPos(threads[i].window, 200 + 250 * i, 200); glfwShowWindow(threads[i].window); } <API key>(threads[0].window); gladLoadGL(glfwGetProcAddress); <API key>(NULL); for (i = 0; i < count; i++) { if (thrd_create(&threads[i].id, thread_main, threads + i) != thrd_success) { fprintf(stderr, "Failed to create secondary thread\n"); glfwTerminate(); exit(EXIT_FAILURE); } } while (running) { glfwWaitEvents(); for (i = 0; i < count; i++) { if (<API key>(threads[i].window)) running = GLFW_FALSE; } } for (i = 0; i < count; i++) glfwHideWindow(threads[i].window); for (i = 0; i < count; i++) thrd_join(threads[i].id, &result); exit(EXIT_SUCCESS); }
.oo-ui-icon-bigger { background-image: url('themes/wikimediaui/images/icons/bigger.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bigger.svg'); } .oo-ui-icon-smaller { background-image: url('themes/wikimediaui/images/icons/smaller.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/smaller.svg'); } .<API key> { background-image: url('themes/wikimediaui/images/icons/subscript-rtl.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/subscript-rtl.svg'); } .<API key> { background-image: url('themes/wikimediaui/images/icons/superscript-rtl.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/superscript-rtl.svg'); } .oo-ui-icon-bold { background-image: url('themes/wikimediaui/images/icons/bold-a.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-a.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(ar) { background-image: url('themes/wikimediaui/images/icons/bold-arab-ain.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-arab-ain.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(be) { background-image: url('themes/wikimediaui/images/icons/bold-cyrl-te.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-cyrl-te.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(ce) { background-image: url('themes/wikimediaui/images/icons/bold-cyrl-palochka.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-cyrl-palochka.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(cs) { background-image: url('themes/wikimediaui/images/icons/bold-b.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-b.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(en) { background-image: url('themes/wikimediaui/images/icons/bold-b.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-b.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(he) { background-image: url('themes/wikimediaui/images/icons/bold-b.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-b.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(ml) { background-image: url('themes/wikimediaui/images/icons/bold-b.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-b.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(pl) { background-image: url('themes/wikimediaui/images/icons/bold-b.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-b.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(sco) { background-image: url('themes/wikimediaui/images/icons/bold-b.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-b.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(da) { background-image: url('themes/wikimediaui/images/icons/bold-f.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-f.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(de) { background-image: url('themes/wikimediaui/images/icons/bold-f.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-f.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(hu) { background-image: url('themes/wikimediaui/images/icons/bold-f.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-f.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(ksh) { background-image: url('themes/wikimediaui/images/icons/bold-f.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-f.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(nn) { background-image: url('themes/wikimediaui/images/icons/bold-f.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-f.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(no) { background-image: url('themes/wikimediaui/images/icons/bold-f.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-f.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(sv) { background-image: url('themes/wikimediaui/images/icons/bold-f.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-f.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(es) { background-image: url('themes/wikimediaui/images/icons/bold-n.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-n.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(gl) { background-image: url('themes/wikimediaui/images/icons/bold-n.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-n.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(pt) { background-image: url('themes/wikimediaui/images/icons/bold-n.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-n.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(eu) { background-image: url('themes/wikimediaui/images/icons/bold-l.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-l.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(fi) { background-image: url('themes/wikimediaui/images/icons/bold-l.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-l.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(fa) { background-image: url('themes/wikimediaui/images/icons/bold-arab-dad.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-arab-dad.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(fr) { background-image: url('themes/wikimediaui/images/icons/bold-g.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-g.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(it) { background-image: url('themes/wikimediaui/images/icons/bold-g.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-g.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(hy) { background-image: url('themes/wikimediaui/images/icons/bold-armn-to.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-armn-to.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(ka) { background-image: url('themes/wikimediaui/images/icons/bold-geor-man.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-geor-man.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(ky) { background-image: url('themes/wikimediaui/images/icons/bold-cyrl-zhe.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-cyrl-zhe.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(ru) { background-image: url('themes/wikimediaui/images/icons/bold-cyrl-zhe.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-cyrl-zhe.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(uk) { background-image: url('themes/wikimediaui/images/icons/bold-cyrl-zhe.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-cyrl-zhe.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(nl) { background-image: url('themes/wikimediaui/images/icons/bold-v.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-v.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(os) { background-image: url('themes/wikimediaui/images/icons/bold-cyrl-be.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-cyrl-be.svg'); } /* @noflip */ .oo-ui-icon-bold:lang(ur) { background-image: url('themes/wikimediaui/images/icons/bold-arab-jeem.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/bold-arab-jeem.svg'); } .<API key> { background-image: url('themes/wikimediaui/images/icons/highlight.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/highlight.svg'); } .oo-ui-icon-italic { background-image: url('themes/wikimediaui/images/icons/italic-a.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-a.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(ar) { background-image: url('themes/wikimediaui/images/icons/italic-arab-meem.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-arab-meem.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(cs) { background-image: url('themes/wikimediaui/images/icons/italic-i.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-i.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(en) { background-image: url('themes/wikimediaui/images/icons/italic-i.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-i.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(fr) { background-image: url('themes/wikimediaui/images/icons/italic-i.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-i.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(he) { background-image: url('themes/wikimediaui/images/icons/italic-i.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-i.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(ml) { background-image: url('themes/wikimediaui/images/icons/italic-i.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-i.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(pl) { background-image: url('themes/wikimediaui/images/icons/italic-i.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-i.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(pt) { background-image: url('themes/wikimediaui/images/icons/italic-i.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-i.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(sco) { background-image: url('themes/wikimediaui/images/icons/italic-i.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-i.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(be) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(ce) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(da) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(de) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(fi) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(ky) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(nn) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(no) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(os) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(sv) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(ru) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(uk) { background-image: url('themes/wikimediaui/images/icons/italic-k.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-k.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(es) { background-image: url('themes/wikimediaui/images/icons/italic-c.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-c.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(gl) { background-image: url('themes/wikimediaui/images/icons/italic-c.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-c.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(it) { background-image: url('themes/wikimediaui/images/icons/italic-c.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-c.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(nl) { background-image: url('themes/wikimediaui/images/icons/italic-c.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-c.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(eu) { background-image: url('themes/wikimediaui/images/icons/italic-e.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-e.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(fa) { background-image: url('themes/wikimediaui/images/icons/<API key>.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/<API key>.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(hu) { background-image: url('themes/wikimediaui/images/icons/italic-d.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-d.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(hy) { background-image: url('themes/wikimediaui/images/icons/italic-armn-sha.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-armn-sha.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(ksh) { background-image: url('themes/wikimediaui/images/icons/italic-s.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-s.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(ka) { background-image: url('themes/wikimediaui/images/icons/italic-geor-kan.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-geor-kan.svg'); } /* @noflip */ .oo-ui-icon-italic:lang(ur) { background-image: url('themes/wikimediaui/images/icons/italic-arab-teh.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/italic-arab-teh.svg'); } .<API key> { background-image: url('themes/wikimediaui/images/icons/strikethrough-a.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/strikethrough-a.svg'); } /* @noflip */ .<API key>:lang(en) { background-image: url('themes/wikimediaui/images/icons/strikethrough-s.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/strikethrough-s.svg'); } /* @noflip */ .<API key>:lang(fi) { background-image: url('themes/wikimediaui/images/icons/strikethrough-y.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/strikethrough-y.svg'); } .<API key> { background-image: url('themes/wikimediaui/images/icons/underline-a.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/underline-a.svg'); } /* @noflip */ .<API key>:lang(en) { background-image: url('themes/wikimediaui/images/icons/underline-u.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/underline-u.svg'); } /* @noflip */ .<API key>:lang(de) { background-image: url('themes/wikimediaui/images/icons/underline-u.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/underline-u.svg'); } .<API key> { background-image: url('themes/wikimediaui/images/icons/language.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/language.svg'); } .<API key> { background-image: url('themes/wikimediaui/images/icons/textDirLTR.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/textDirLTR.svg'); } .<API key> { background-image: url('themes/wikimediaui/images/icons/textDirRTL.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/textDirRTL.svg'); } .<API key> { background-image: url('themes/wikimediaui/images/icons/textStyle.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/textStyle.svg'); }
{% extends path1+"/_layout-info.html" %} {% block citizen_content %} {{ data.nuggets | log }} <p class="no-kdBar"><a href="javascript: history.go(-1)" class="link-back">Back</a></p> <h1 class="heading-large mt10 "> <span class="heading-secondary">Mental Health</span> Behaviour</h1> <div class="grid-row"> <div class="column-two-thirds"> <p>Things you should be assessing</p> <ul class="list list-bullet"> <li>Eye contact</li> <li>Rapport</li> <li>Activity Rocking</li> <li>Arousal</li> <li>Facial Expression</li> <li>Activity General</li> <li>Coping at intrerview</li> </ul> <form action="<API key>" method="POST" class="form"> <div class="form-group"> <label class="form-label-bold" for="mh-behaviour">Observation</label> <textarea class="form-control form-control-3-4" name="mhbehaviour" id="mh-behaviour" rows="8">{{mhbehaviour}}</textarea> </div> <input type="submit" class="button" value="Save"> <div class="multiple-choice" style="display:none"> <input id="radio-inline-4" type="radio" name="Behaviour" value="Behaviour" checked> <label for="radio-4">hidden radio one</label> </div> </form> </div><!-- column --> </div><!-- row --> {% endblock %} {% macro physGroup(name,sel) %} {% set s = name | slug %} <!-- GROUP --> <div class="multiple-choice" data-target="group_{{s}}_yes"> <input id="group_{{s}}" type="checkbox" name="group_{{s}}" sue="group_{{s}}" {% if sel %} checked="checked"{% endif %}> <label for="group_{{s}}">{{name}}</label> </div> {% endmacro %} {% macro physObs(name,sel) %} {% set s = name | slug %} <div class="multiple-choice" data-target="phys_{{s}}_yes"> <input id="phys_{{s}}" type="checkbox" name="mobility" value="phys_{{s}}" {% if sel %} checked="checked"{% endif %}> <label for="phys_{{s}}">{{name}}</label> </div> <div class="form-group panel panel-border-narrow js-hidden mt0 mb20" id="phys_{{s}}_yes"> <p> <label class="form-label" for="phys_{{s}}_obs">Observation, Palpation, Movement</label> <textarea class="form-control form-control-3-4" name="phys_{{s}}_obs" id="phys_{{s}}_obs" rows="4"></textarea> </p> </div> {% endmacro %} {% block footer_top %} {{ super() }} <p class="font-xsmall"> <a href="/{{ path2 }}/phys_exam_1">exam v1</a> | <a href="/{{ path2 }}/phys_exam_2">exam v2</a> </p> {% endblock %} {% block page_scripts %} {{ super() }} <script type="text/javascript"> $(document).on('ready',function() { $('#submitButton').on('click',function(e) { e.preventDefault(); // get values from the form you're submitting. var nugget = $('#nugget').val(); console.log(nugget) // gather values into a data object. var formdata = JSON.stringify({"nugget":nugget}); console.log(formdata) console.log({url: '/{{ path }}/saveText'}) // send data object off to node route for saving. $.ajax({ url: '/{{ path }}/saveText', method: "POST", contentType: 'application/json', data: formdata, dataType: 'json', complete: function(data,status,xhr) { // sort out the page after data is successfully saved. // $('#status_form').hide(); // $('#status_button').show(); window.location.href = '/{{path2}}/physical-updated'; } }); }); }); </script> {% endblock %}
<!DOCTYPE html> <html data-require="math"> <head> <title>Sorting Lower Bound: Summary Questions</title> <script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.min.js"></script> <script src="../../khan-exercises/local-only/main.js" ></script> </head> <body data-height="650" data-width="950"> <div class="exercise" data-name="SortBoundMCQ1"></div> <div class="exercise" data-name="SortBoundMCQ2"></div> <div class="exercise" data-name="SortBoundMCQ3"></div> <div class="exercise" data-name="SortBoundMCQ5"></div> <div class="exercise" data-name="SortBoundMCQ6"></div> <div class="exercise" data-name="SortBoundMCQ7"></div> <div class="exercise" data-name="SortBoundTF4"></div> </body> </html>
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Taxonomy Browser</title> <! NOTE: "Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3" <script src="//code.jquery.com/jquery-1.12.4.min.js"></script> <script src="//code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <script type="text/javascript"> if( !$.browser ) { console.warn("Monkey-patching jQuery.browser.msie to get BBQ working"); var ua = navigator.userAgent.toLowerCase(); $.browser = { msie: /msie/.test(ua) && !/opera/.test(ua) }; } </script> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery.ba-bbq/1.2.1/jquery.ba-bbq.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.5/handlebars.min.js"></script> <! <link href="//cdn.jsdelivr.net/jquery.truncate/0.1/jquery.truncate.min.js" rel="stylesheet"> <script src="https://rawgit.com/tbasse/jquery-truncate/master/jquery.truncate.js" type="text/javascript"></script> <link href="//cdn.jsdelivr.net/jquery.fancytree/2/skin-bootstrap/ui.fancytree.min.css" rel="stylesheet"> <! <link href="../../src/skin-bootstrap/ui.fancytree.css" rel="stylesheet"> <script src="//cdn.jsdelivr.net/jquery.fancytree/2/jquery.fancytree-all.min.js"></script> <! <script src="../../src/jquery.fancytree.js"></script> <script src="../../src/jquery.fancytree.edit.js"></script> <script src="../../src/jquery.fancytree.filter.js"></script> <script src="../../src/jquery.fancytree.glyph.js"></script> <script src="../../src/jquery.fancytree.table.js"></script> <script src="../../src/jquery.fancytree.wide.js"></script> <link href="style.css" rel="stylesheet"> <script src="taxonomy-browser.js"></script> </head> <body> <div class="page-header"> <h1>Taxonomy Browser <! <small><a href="http://wwwendt.de/tech/fancytree/demo/taxonomy-browser/">home</a></small> </h1> </div> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Search <acronym title="Global Biodiversity Information Facility">GBIF</acronym></h3> </div> <div class="panel-body hidden-print"> <input type="text" name="query" id="query" autocorrect="off" autocomplete="off" placeholder="Enter Search Phrase"> <button id="btnResetSearch" class="btn btn-default btn-sm">&times;</button> <button id="btnSearch" class="btn btn-default btn-sm">Search</button> <div class="collapse" id="searchResultPane"> <table id="searchResultTree" class="table table-striped table-hover table-condensed table-bordered"> <colgroup> <col width="10em"></col> <col width="10em"></col> <col width="*"></col> <col width="30em"></col> <col width="30em"></col> <col width="30em"></col> <col width="30em"></col> <col width="30em"></col> <col width="10em"></col> <col width="10em"></col> <col width="30em"></col> <col width="30em"></col> </colgroup> <thead> <tr> <th class="visible-lg">Key</th> <th class="hidden-xs">Rank</th> <th>Scientific Name</th> <th class="hidden-xs hidden-sm">Vernacular Names</th> <th class="hidden-xs hidden-sm">Canonical Name</th> <th class="visible-lg">According to</th> <th class="hidden-xs">Status</th> <th class="hidden-xs">Name Type</th> <th class="hidden-xs"># Occur.</th> <th class="hidden-xs"># Desc.</th> <th class="visible-lg">Author</th> <th class="visible-lg">Published in</th> <! canonicalName accordingTo extinct numDescendants numOccurrences publishedIn synonym </tr> </thead> <tbody> <tr> <td class="visible-lg"/> <td class="hidden-xs" /> <td/> <td class="hidden-xs hidden-sm" /> <td class="hidden-xs hidden-sm" /> <td class="visible-lg" /> <td class="hidden-xs" /> <td class="hidden-xs" /> <td class="hidden-xs" /> <td class="hidden-xs" /> <td class="visible-lg" /> <td class="visible-lg" /> </tr> </tbody> </table> </div> </div> </div> <div class="row"> <div class="col-md-4"> <div class="btn-group"> <button id="btnPin" class="btn btn-default btn-xs">Pin</button> <button id="btnUnpin" class="btn btn-default btn-xs">Unpin</button> </div> <div id="taxonTree" class="<API key>"> </div> </div> <div class="col-md-8"> <!-- Breadcrumb --> <ol class="breadcrumb"> <li class="active">Please select an element.</li> </ol> <span id="tmplInfoPane"> </span> </div> </div> <div class="panel panel-warning"> <div class="panel-heading"> Disclaimer </div> <div class="panel-body"> <p> This site accesses data from external sources, namely the <a href="http: There is no guarantee, that the display is correct, complete, or permanently available. Please refer to those original sources for authorative information. </p> <p> Copyright &copy; 2015 Martin Wendt. Created as a demo for <a href="https://github.com/mar10/fancytree">Fancytree</a>. </p> </div> </div> </body> </html>
# <API key>: true require 'spec_helper' RSpec.describe 'getting Alert Management Alert Assignees' do include GraphqlHelpers let_it_be(:project) { create(:project) } let_it_be(:current_user) { create(:user) } let(:fields) do <<~QUERY nodes { iid metricsDashboardUrl } QUERY end let(:graphql_query) do graphql_query_for( 'project', { 'fullPath' => project.full_path }, query_graphql_field('<API key>', {}, fields) ) end let(:alerts) { graphql_data.dig('project', '<API key>', 'nodes') } let(:first_alert) { alerts.first } before do project.add_developer(current_user) end context 'with self-managed prometheus payload' do include_context 'self-managed prometheus alert attributes' before do create(:<API key>, :prometheus, project: project, payload: payload) end it 'includes the correct metrics dashboard url' do post_graphql(graphql_query, current_user: current_user) expect(first_alert).to include('metricsDashboardUrl' => <API key>) end end context 'with gitlab-managed prometheus payload' do include_context 'gitlab-managed prometheus alert attributes' before do create(:<API key>, :prometheus, project: project, payload: payload, prometheus_alert: prometheus_alert) end it 'includes the correct metrics dashboard url' do post_graphql(graphql_query, current_user: current_user) expect(first_alert).to include('metricsDashboardUrl' => <API key>) end end end
# Run znc in a container # docker run --restart always -d \ # --name znc \ # -p 6697:6697 \ # -v /volumes/znc:/home/user/.znc \ # jess/znc FROM alpine:latest LABEL maintainer "Jessie Frazelle <jess@linux.com>" RUN apk add --no-cache \ ca-certificates \ glib \ perl \ perl-datetime \ perl-libwww ENV HOME /home/user RUN adduser -u 1001 -D user \ && chown -R user:user $HOME ENV LANG C.UTF-8 ENV ZNC_VERSION 1.8.1-rc1 RUN set -x \ && apk add --no-cache --virtual .build-deps \ build-base \ curl \ libressl-dev \ perl-dev \ tar \ && curl -sSL "http://znc.in/releases/znc-${ZNC_VERSION}.tar.gz" -o /tmp/znc.tar.gz \ && mkdir -p /usr/src/znc \ && tar -xzf /tmp/znc.tar.gz -C /usr/src/znc --strip-components 1 \ && rm /tmp/znc.tar.gz* \ && ( \ cd /usr/src/znc \ && ./configure \ && make -j8 \ && make install \ ) \ && rm -rf /usr/src/znc \ && runDeps="$( \ scanelf --needed --nobanner --recursive /usr \ | awk '{ gsub(/,/, "\nso:", $2); print "so:" $2 }' \ | sort -u \ | xargs -r apk info --installed \ | sort -u \ )" \ && apk add --no-cache --virtual .irssi-rundeps $runDeps \ && apk del .build-deps WORKDIR $HOME USER user ENTRYPOINT [ "znc" ] CMD [ "-f" ]
<?php namespace CrEOF\Spatial\Tests\PHP\Types\Geometry; use CrEOF\Spatial\PHP\Types\Geometry\Point; class PointTest extends \<API key> { public function <API key>() { $point1 = new Point(-73.7562317, 42.6525793); $this->assertEquals(42.6525793, $point1->getLatitude()); $this->assertEquals(-73.7562317, $point1->getLongitude()); } public function <API key>() { $point2 = new Point('79:56:55W', '40:26:46N'); $this->assertEquals(40.446111111111, $point2->getLatitude()); $this->assertEquals(-79.948611111111, $point2->getLongitude()); $point3 = new Point('79°56\'55"W', '40°26\'46"N'); $this->assertEquals(40.446111111111, $point3->getLatitude()); $this->assertEquals(-79.948611111111, $point3->getLongitude()); $point4 = new Point('79° 56\' 55" W', '40° 26\' 46" N'); $this->assertEquals(40.446111111111, $point4->getLatitude()); $this->assertEquals(-79.948611111111, $point4->getLongitude()); $point5 = new Point('79°56′55″W', '40°26′46″N'); $this->assertEquals(40.446111111111, $point5->getLatitude()); $this->assertEquals(-79.948611111111, $point5->getLongitude()); $point6 = new Point('79° 56′ 55″ W', '40° 26′ 46″ N'); $this->assertEquals(40.446111111111, $point6->getLatitude()); $this->assertEquals(-79.948611111111, $point6->getLongitude()); $point7 = new Point('79:56:55.832W', '40:26:46.543N'); $this->assertEquals(40.446261944444, $point7->getLatitude()); $this->assertEquals(-79.948842222222, $point7->getLongitude()); $point7 = new Point('112:4:0W', '33:27:0N'); $this->assertEquals(33.45, $point7->getLatitude()); $this->assertEquals(-112.06666666667, $point7->getLongitude()); } /** * Test bad string parameters - invalid latitude direction * * @expectedException \CrEOF\Spatial\Exception\<API key> * @<API key> 84:26:46Q is not a valid coordinate value. */ public function <API key>() { new Point('100:56:55W', '84:26:46Q'); } /** * Test bad string parameters - latitude degrees greater that 90 * * @expectedException \CrEOF\Spatial\Exception\<API key> * @<API key> 92:26:46N is not a valid coordinate value. */ public function <API key>() { new Point('79:56:55W', '92:26:46N'); } /** * Test bad string parameters - latitude minutes greater than 59 * * @expectedException \CrEOF\Spatial\Exception\<API key> * @<API key> 84:64:46N is not a valid coordinate value. */ public function <API key>() { new Point('108:42:55W', '84:64:46N'); } /** * Test bad string parameters - latitude seconds greater than 59 * * @expectedException \CrEOF\Spatial\Exception\<API key> * @<API key> 84:23:75N is not a valid coordinate value. */ public function <API key>() { new Point('108:42:55W', '84:23:75N'); } /** * Test bad string parameters - invalid longitude direction * * @expectedException \CrEOF\Spatial\Exception\<API key> * @<API key> 100:56:55P is not a valid coordinate value. */ public function <API key>() { new Point('100:56:55P', '84:26:46N'); } /** * Test bad string parameters - longitude degrees greater than 180 * * @expectedException \CrEOF\Spatial\Exception\<API key> * @<API key> 190:56:55W is not a valid coordinate value. */ public function <API key>() { new Point('190:56:55W', '84:26:46N'); } /** * Test bad string parameters - longitude minutes greater than 59 * * @expectedException \CrEOF\Spatial\Exception\<API key> * @<API key> 108:62:55W is not a valid coordinate value. */ public function <API key>() { new Point('108:62:55W', '84:26:46N'); } /** * Test bad string parameters - longitude seconds greater than 59 * * @expectedException \CrEOF\Spatial\Exception\<API key> * @<API key> 108:53:94W is not a valid coordinate value. */ public function <API key>() { new Point('108:53:94W', '84:26:46N'); } public function testToArray() { $expected = array(10, 10); $point = new Point(10, 10); $result = $point->toArray(); $this->assertEquals($expected, $result); } public function testPointWithSrid() { $point = new Point(10, 10, 4326); $result = $point->getSrid(); $this->assertEquals(4326, $result); } public function testGetType() { $point = new Point(10, 10); $result = $point->getType(); $this->assertEquals('Point', $result); } public function <API key>() { $expected = '5 5'; $point = new Point(array(5, 5)); $this->assertEquals($expected, (string) $point); } /** * @expectedException \CrEOF\Spatial\Exception\<API key> * @<API key> Invalid parameters passed to CrEOF\Spatial\PHP\Types\Geometry\Point::__construct: "5", "5", "5", "5" */ public function <API key>() { new Point(5, 5, 5, 5); } /** * @expectedException \CrEOF\Spatial\Exception\<API key> * @<API key> Invalid parameters passed to CrEOF\Spatial\PHP\Types\Geometry\Point::__construct: Array, Array, "1234" */ public function <API key>() { new Point(array(), array(), '1234'); } }
using System; using System.Collections.Generic; using Umbraco.Cms.Core.Composing; namespace Umbraco.Cms.Core.WebAssets { public class <API key> : <API key><IAssetFile> { public <API key>(Func<IEnumerable<IAssetFile>> items) : base(items) { } } }
<h1 id="<API key>">Week 09 Days One and Two</h1> <h2 id="aws">AWS</h2> <ul> <li><p>Automate Setup</p></li> <li><p>Running Scripts on Linux</p></li> </ul> <h2 id="git">Git</h2> <ul> <li><p>More on updates, adds, commits</p></li> <li><p>Private Repos on BitBucket</p></li> <li><p><a href="http: </ul> <h2 id="node">Node</h2> <ul> <li><p>Setup</p></li> <li><p>Express</p></li> <li><p>Posting Data</p></li> </ul> <h2 id="unit-tests">Unit Tests</h2> <ul> <li><p>Setting up the HTML</p></li> <li><p>Setting up the JavaScript</p></li> <li><p>QUnit</p></li> </ul> <h2 id="day-02">Day 02</h2> <p>Here are some of the things covered on day 2.</p> <h2 id="setting-up-qunit">Setting up QUnit</h2> <p>Here is the new code for the QUnit html file:</p> <pre><code> &lt;div id=&quot;qunit&quot;&gt; &lt;/div&gt; &lt;div id=&quot;qunit-fixture&quot;&gt; &lt;/div&gt; &lt;div&gt; &lt;ul id=&quot;debugList&quot;&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> <p>Here was the old style QUnit code for your HTML file:</p> <pre><code> &lt;div id=&quot;qunit-fixture&quot;&gt; \\ tests depend on markup that goes here &lt;/div&gt; &lt;h1 id=&quot;qunit-header&quot;&gt;Using QUnit&lt;/h1&gt; &lt;h2 id=&quot;qunit-banner&quot;&gt; &lt;/h2&gt; &lt;h2 id=&quot;qunit-userAgent&quot;&gt; &lt;/h2&gt; &lt;ol id=&quot;qunit-tests&quot;&gt; &lt;/ol&gt;</code></pre> <h2 id="git-1">Git</h2> <ul> <li><a href="http: </ul> <h1 id="example-script">Example Script</h1> <pre><code> ECHO ====== Create SSH Dir ====== ECHO ============================ ECHO This script expects your server&#39;s password as a parameter ECHO ECHO Example: ECHO CreateSshDir.bat MyPassword ECHO ECHO Before you run this script, set ELF_USER and ELF_IP ECHO Your ELF_IP might be your elastic ip if you are using ECHO EC2. You can set ELF_USER and ELF_IP by using ECHO the ENVIRONMENT VARIABLES dialog. Alternatively ECHO you can set them at the command prompt like this: ECHO set ELF_USER=MyUserName ECHO set ELF_IP=MyRemoteIp ECHO For instance: ECHO set ELF_USER=charlie ECHO set ELF_IP=192.168.2.3 ECHO ECHO You should also create a file called PublicKey.txt ECHO That contains your public key. This script will ECHO use the file to create an authorized keys ECHO file on the server. The key should be all on one ECHO line and the line should end with a UNIX style LF. ECHO ============================</code></pre> <figure> <img src="https://bc.instructure.com/courses/795060/files/24309741/preview" /> </figure>
# This is intended to be used inside Docker containers git clone --recursive https://github.com/$env:fork/PowerShell.git -b $env:branch Set-Location PowerShell Import-Module ./build.psm1 Start-PSBootstrap -Package -NoSudo Start-PSBuild -Crossgen Start-PSPackage
<?php echo 'hello';
import { JsonObject, JsonValue } from '../../json'; import { JsonAstArray, JsonAstKeyValue, JsonAstNode, JsonAstObject } from '../../json/parser_ast'; const stableStringify = require('<API key>'); interface CacheEntry { value?: JsonValue; node?: JsonAstNode; parent: JsonAstArray | JsonAstKeyValue | JsonAstObject; } export type ChangeListener = ( op: 'add' | 'remove' | 'replace', path: string, node: JsonAstArray | JsonAstObject | JsonAstKeyValue, value?: JsonValue, ) => void; type ChangeReporter = ( path: string, parent: JsonAstArray | JsonAstKeyValue | JsonAstObject, node?: JsonAstNode, old?: JsonValue, current?: JsonValue, ) => void; // lib.es5 PropertyKey is string | number | symbol which doesn't overlap ProxyHandler PropertyKey which is string | symbol. type ProxyPropertyKey = string | symbol; function findNode( parent: JsonAstArray | JsonAstObject, p: ProxyPropertyKey, ): { node?: JsonAstNode; parent: JsonAstArray | JsonAstKeyValue | JsonAstObject } { if (parent.kind === 'object') { const entry = parent.properties.find((entry) => entry.key.value === p); if (entry) { return { node: entry.value, parent: entry }; } } else { const index = Number(p); if (!isNaN(index)) { return { node: parent.elements[index], parent }; } } return { parent }; } function <API key>(value: JsonValue | undefined): PropertyDescriptor { return { configurable: true, enumerable: true, writable: true, value, }; } export function escapeKey(key: string | number): string | number { if (typeof key === 'number') { return key; } return key.replace('~', '~0').replace('/', '~1'); } export function unescapeKey(key: string | number): string | number { if (typeof key === 'number') { return key; } return key.replace('~1', '/').replace('~0', '~'); } export function <API key><T extends object = JsonObject>( root: JsonAstObject, options: { exclude?: string[]; include?: string[]; listener?: ChangeListener; base?: object; } = {}, ): T { const reporter: ChangeReporter = (path, parent, node, old, current) => { if (options.listener) { if (old === current || stableStringify(old) === stableStringify(current)) { return; } const op = old === undefined ? 'add' : current === undefined ? 'remove' : 'replace'; options.listener(op, path, parent, current); } }; return create( root, '', reporter, new Set(options.exclude), options.include && options.include.length > 0 ? new Set(options.include) : undefined, options.base, ) as T; } function create( ast: JsonAstObject | JsonAstArray, path: string, reporter: ChangeReporter, excluded = new Set<ProxyPropertyKey>(), included?: Set<ProxyPropertyKey>, base?: object, ) { const cache = new Map<string, CacheEntry>(); const alteredNodes = new Set<JsonAstNode>(); if (!base) { if (ast.kind === 'object') { base = Object.create(null) as object; } else { base = []; (base as Array<unknown>).length = ast.elements.length; } } return new Proxy(base, { <API key>(target: {}, p: ProxyPropertyKey): PropertyDescriptor | undefined { const descriptor = Reflect.<API key>(target, p); if (descriptor || typeof p === 'symbol') { return descriptor; } else if (excluded.has(p) || (included && !included.has(p))) { return undefined; } const propertyPath = path + '/' + escapeKey(p); const cacheEntry = cache.get(propertyPath); if (cacheEntry) { if (cacheEntry.value !== undefined) { return <API key>(cacheEntry.value); } return undefined; } const { node } = findNode(ast, p); if (node) { return <API key>(node.value); } return undefined; }, has(target: {}, p: ProxyPropertyKey): boolean { if (Reflect.has(target, p)) { return true; } else if (typeof p === 'symbol' || excluded.has(p)) { return false; } return cache.has(path + '/' + escapeKey(p)) || findNode(ast, p) !== undefined; }, get(target: {}, p: ProxyPropertyKey): unknown { if (typeof p === 'symbol' || Reflect.has(target, p)) { return Reflect.get(target, p); } else if (excluded.has(p) || (included && !included.has(p))) { return undefined; } const propertyPath = path + '/' + escapeKey(p); const cacheEntry = cache.get(propertyPath); if (cacheEntry) { return cacheEntry.value; } const { node, parent } = findNode(ast, p); let value; if (node) { if (node.kind === 'object' || node.kind === 'array') { value = create(node, propertyPath, (path, parent, vnode, old, current) => { if (!alteredNodes.has(node)) { reporter(path, parent, vnode, old, current); } }); } else { value = node.value; } cache.set(propertyPath, { node, parent, value }); } return value; }, set(target: {}, p: ProxyPropertyKey, value: unknown): boolean { if (value === undefined) { // setting to undefined is equivalent to a delete // <API key> @typescript-eslint/<API key> return this.deleteProperty!(target, p); } if (typeof p === 'symbol' || Reflect.has(target, p)) { return Reflect.set(target, p, value); } else if (excluded.has(p) || (included && !included.has(p))) { return false; } // TODO: Check if is JSON value const jsonValue = value as JsonValue; const propertyPath = path + '/' + escapeKey(p); const cacheEntry = cache.get(propertyPath); if (cacheEntry) { const oldValue = cacheEntry.value; cacheEntry.value = value as JsonValue; if (cacheEntry.node && oldValue !== value) { alteredNodes.add(cacheEntry.node); } reporter(propertyPath, cacheEntry.parent, cacheEntry.node, oldValue, jsonValue); } else { const { node, parent } = findNode(ast, p); cache.set(propertyPath, { node, parent, value: value as JsonValue }); if (node && node.value !== value) { alteredNodes.add(node); } reporter(propertyPath, parent, node, node && node.value, value as JsonValue); } return true; }, deleteProperty(target: {}, p: ProxyPropertyKey): boolean { if (typeof p === 'symbol' || Reflect.has(target, p)) { return Reflect.deleteProperty(target, p); } else if (excluded.has(p) || (included && !included.has(p))) { return false; } const propertyPath = path + '/' + escapeKey(p); const cacheEntry = cache.get(propertyPath); if (cacheEntry) { const oldValue = cacheEntry.value; cacheEntry.value = undefined; if (cacheEntry.node) { alteredNodes.add(cacheEntry.node); } if (cacheEntry.parent.kind === 'keyvalue') { // Remove the entire key/value pair from this JSON object reporter(propertyPath, ast, cacheEntry.node, oldValue, undefined); } else { reporter(propertyPath, cacheEntry.parent, cacheEntry.node, oldValue, undefined); } } else { const { node, parent } = findNode(ast, p); if (node) { cache.set(propertyPath, { node, parent, value: undefined }); alteredNodes.add(node); if (parent.kind === 'keyvalue') { // Remove the entire key/value pair from this JSON object reporter(propertyPath, ast, node, node && node.value, undefined); } else { reporter(propertyPath, parent, node, node && node.value, undefined); } } } return true; }, defineProperty(target: {}, p: ProxyPropertyKey, attributes: PropertyDescriptor): boolean { if (typeof p === 'symbol') { return Reflect.defineProperty(target, p, attributes); } return false; }, ownKeys(target: {}): ProxyPropertyKey[] { let keys: ProxyPropertyKey[]; if (ast.kind === 'object') { keys = ast.properties .map((entry) => entry.key.value) .filter((p) => !excluded.has(p) && (!included || included.has(p))); } else { keys = []; } for (const key of cache.keys()) { const relativeKey = key.substr(path.length + 1); if (relativeKey.length > 0 && !relativeKey.includes('/')) { keys.push(`${unescapeKey(relativeKey)}`); } } return [...new Set([...keys, ...Reflect.ownKeys(target)])]; }, }); }
@media print { .no-print, .no-print * { display: none !important; } #receipt_wrapper, #table { /*background-color:#FFFFFF;*/ font-size:75%; } .topbar { display:none; } #menubar, #footer { display:none; } #sale_return_policy { width:100%; text-align:center; } #receipt_items td { white-space:nowrap; } /* Hide links in table for printing */ table.innertable { display: table; } table.innertable a { color: #000000; text-decoration: none; } table.report a.expand { visibility: hidden; } table.report a { color: #000000; text-decoration: none; } table.innertable thead { /*display:none;*/ } .print_show { display:block !important; } .print_hide { display:none !important; } .<API key> { border: none; } .<API key> thead th .sortable { padding-right: 10px; } }
using System; using System.ComponentModel; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace NSwag.Demo.Web.Models { <summary>The DTO class for a person.</summary> public class Person { <summary>Gets or sets the first name.</summary> [JsonProperty("firstName")] [DefaultValue("Rico")] public string FirstName { get; set; } public string LastName { get; set; } public DateTime Birthday { get; set; } <summary>Gets or sets the height in cm.</summary> public decimal Height { get; set; } public Car[] Cars { get; set; } [JsonConverter(typeof(StringEnumConverter))] public ObjectType Type { get; set; } } }
<?php namespace Concrete\Controller; use Concrete\Core\Cache\Cache; use Concrete\Core\Controller\Controller; use Concrete\Core\Encryption\PasswordHasher; use Concrete\Core\Error\<API key>; use Concrete\Core\Http\<API key>; use Concrete\Core\Install\<API key>; use Concrete\Core\Install\Installer; use Concrete\Core\Install\InstallerOptions; use Concrete\Core\Install\PreconditionResult; use Concrete\Core\Install\PreconditionService; use Concrete\Core\Install\<API key>; use Concrete\Core\Localization\Localization; use Concrete\Core\Localization\Service\<API key>; use Concrete\Core\Localization\Translation\Remote\ProviderInterface as <API key>; use Concrete\Core\Url\Resolver\Manager\<API key>; use Concrete\Core\Url\UrlImmutable; use Concrete\Core\View\View; use Exception; use Punic\Comparer as PunicComparer; use stdClass; defined('C5_EXECUTE') or die('Access Denied.'); class Install extends Controller { /** * Install step: choose locale. * * @var int */ const STEP_CHOOSELOCALE = 1; /** * Install step: precondition checks. * * @var int */ const STEP_PRECONDITIONS = 2; /** * Install step: precondition checks. * * @var int */ const STEP_CONFIGURATION = 3; /** * Install step: installing/installed. * * @var int */ const STEP_INSTALL = 4; /** * {@inheritdoc} * * @see \Concrete\Core\Controller\AbstractController::$helpers */ public $helpers = ['form', 'html']; /** * The installer instance. * * @var Installer|null */ private $installer = null; /** * {@inheritdoc} * * @see \Concrete\Core\Controller\Controller::getViewObject() */ public function getViewObject() { $v = new View('/frontend/install'); $v->setViewTheme('concrete'); $v->setViewTemplate('background_image.php'); return $v; } /** * {@inheritdoc} * * @see \Concrete\Core\Controller\AbstractController::on_start() */ public function on_start() { $this->set('urlResolver', $this->app->make(<API key>::class)); $config = $this->app->make('config'); $this->set('pageTitle', t('Install concrete5')); $image = date('Ymd') . '.jpg'; $this->set('concreteVersion', $config->get('concrete.version')); $locale = $this->request->request->get('locale'); if ($locale) { $loc = Localization::changeLocale($locale); $this->set('locale', $locale); } Cache::disableAll(); if ($this->app->isInstalled()) { throw new <API key>(t('concrete5 is already installed.')); } } public function view() { if ($this->getInstallerOptions()-><API key>()) { $this->testAndRunInstall(); } else { list($locales, $onlineLocales) = $this->getLocales(); $this->set('locales', $locales); $this->set('onlineLocales', $onlineLocales); } $this->setInstallStep(); } public function select_language() { $localeID = $this->request->request->get('wantedLocale'); if ($localeID) { if ($localeID !== Localization::BASE_LOCALE) { $localLocales = Localization::<API key>(null); if (!isset($localLocales[$localeID])) { $ti = $this->app->make(<API key>::class); try { $ti-><API key>($localeID); } catch (Exception $x) { $this->set('error', $x); $this->view(); $localeID = null; } } } if ($localeID) { $this->set('locale', $localeID); Localization::changeLocale($localeID); } } $this->setInstallStep(); } /** * @return \Concrete\Core\Install\<API key>[][] */ public function getPreconditions() { $service = $this->app->make(PreconditionService::class); $required = []; $optional = []; foreach ($service->getPreconditions() as $precondition) { if ($precondition->isOptional()) { $optional[] = $precondition; } else { $required[] = $precondition; } } return [$required, $optional]; } public function setup() { $config = $this->app['config']; $passwordMinLength = (int) $config->get('concrete.user.password.minimum', 5); $passwordMaxLength = (int) $config->get('concrete.user.password.maximum'); $passwordAttributes = [ 'autocomplete' => 'off', ]; if ($passwordMinLength > 0) { $passwordAttributes['required'] = 'required'; if ($passwordMaxLength > 0) { $passwordAttributes['placeholder'] = t('Between %1$s and %2$s Characters', $passwordMinLength, $passwordMaxLength); $passwordAttributes['pattern'] = '.{' . $passwordMinLength . ',' . $passwordMaxLength . '}'; } else { $passwordAttributes['placeholder'] = t('at least %s characters', $passwordMinLength); $passwordAttributes['pattern'] = '.{' . $passwordMinLength . ',}'; } } elseif ($passwordMaxLength > 0) { $passwordAttributes['placeholder'] = t('up to %s characters', $passwordMaxLength); $passwordAttributes['pattern'] = '.{0,' . $passwordMaxLength . '}'; } $this->set('passwordAttributes', $passwordAttributes); $canonicalUrl = ''; $canonicalUrlChecked = false; $<API key> = ''; $<API key> = false; $uri = $this->request->getUri(); if (preg_match('/^(https?)(:.+?)(?:\/' . preg_quote(DISPATCHER_FILENAME, '%') . ')?\/install(?:$|\/|\?)/i', $uri, $m)) { switch (strtolower($m[1])) { case 'http': $canonicalUrl = (string) UrlImmutable::createFromUrl('http' . $m[2]); $<API key> = (string) UrlImmutable::createFromUrl('https' . $m[2]); //$canonicalUrlChecked = true; break; case 'https': $canonicalUrl = (string) UrlImmutable::createFromUrl('https' . $m[2]); $<API key> = (string) UrlImmutable::createFromUrl('http' . $m[2]); //$canonicalUrlChecked = true; break; } } $countries = []; $ll = $this->app->make('localization/languages'); $chunks = explode('_', Localization::activeLocale()); $<API key> = $chunks[0]; $languages = $ll->getLanguageList(); $this->set('languages', $languages); $countries = $this-><API key>($<API key>); $this->set('countries', $countries); $this->set('<API key>', $<API key>); if (isset($chunks[1])) { $<API key> = $chunks[1]; } else { if (is_array(current($countries))) { $<API key> = key(current($countries)); } else { $<API key> = key($countries); } } $this->set('<API key>', $<API key>); $this->set('setInitialState', $this->request->post('SITE') === null); $this->set('canonicalUrl', $canonicalUrl); $this->set('canonicalUrlChecked', $canonicalUrlChecked); $this->set('<API key>', $<API key>); $this->set('<API key>', $<API key>); $this->set('SERVER_TIMEZONE', @<API key>() ?: 'UTC'); $this->set('availableTimezones', $this->app->make('date')->getGroupedTimezones()); $this->setInstallStep(); } public function <API key>($viewLocaleID, $languageID, $<API key>) { Localization::changeLocale($viewLocaleID); $countries = $this-><API key>($languageID); $form = $this->app->make('helper/form'); $rf = $this->app->make(<API key>::class); return $rf->json($form->select('siteLocaleCountry', $countries, $<API key>)); } public function web_precondition($handle, $argument = '') { $service = $this->app->make(PreconditionService::class); $precondition = $service-><API key>($handle); if (!$precondition instanceof <API key>) { throw new Exception(sprintf('%s is not a valid precondition handle', $handle)); } $result = $precondition->getAjaxAnswer($argument); $rf = $this->app->make(<API key>::class); return $rf->json($result); } /** * @return \Concrete\Core\Error\Error */ public function configure() { $post = $this->request->request; $error = $this->app->make('helper/validation/error'); $warnings = $this->app->make('helper/validation/error'); $ignoreWarnings = !empty($post->get('ignore-warnings')); try { $val = $this->app->make('helper/validation/form'); $val->setData($this->post()); $val->addRequired('SITE', t("Please specify your site's name")); $val->addRequiredEmail('uEmail', t('Please specify a valid email address')); $val->addRequired('DB_DATABASE', t('You must specify a valid database name')); $val->addRequired('DB_SERVER', t('You must specify a valid database server')); $val->addRequired('SERVER_TIMEZONE', t('You must specify the system time zone')); $val->addRequired('privacy', t('You must agree to the privacy policy')); $password = $post->get('uPassword'); $passwordConfirm = $post->get('uPasswordConfirm'); $this->app->make('validator/password')->isValid($password, $error); if ($password) { if ($password != $passwordConfirm) { $error->add(t('The two passwords provided do not match.')); } } if (!$val->test()) { $error->add($val->getError()); } elseif (!$error->has()) { /** * @var $options InstallerOptions */ $options = $this->app->make(InstallerOptions::class); $config = $this->app->make('config'); $configuration = $post->get('SITE_CONFIG'); if (!is_array($configuration)) { $configuration = []; } $configuration['database'] = [ 'default-connection' => 'concrete', 'connections' => [ 'concrete' => [ 'driver' => 'c5_pdo_mysql', 'server' => $post->get('DB_SERVER'), 'database' => $post->get('DB_DATABASE'), 'username' => $post->get('DB_USERNAME'), 'password' => $post->get('DB_PASSWORD'), 'character_set' => $config->get('database.<API key>'), 'collation' => $config->get('database.fallback_collation'), ], ], ]; $configuration['canonical-url'] = $post->get('canonicalUrlChecked') === '1' ? $post->get('canonicalUrl') : ''; $configuration['<API key>'] = $post->get('<API key>') === '1' ? $post->get('<API key>') : ''; $configuration['session-handler'] = $post->get('sessionHandler'); $options->setConfiguration($configuration); $hasher = $this->app->make(PasswordHasher::class); $options -><API key>($post->get('privacy') == '1' ? true : false) ->setUserEmail($post->get('uEmail')) ->setUserPasswordHash($hasher->hashPassword($post->get('uPassword'))) -><API key>($post->get('SAMPLE_CONTENT')) ->setSiteName($post->get('SITE')) ->setSiteLocaleId($post->get('siteLocaleLanguage') . '_' . $post->get('siteLocaleCountry')) ->setUiLocaleId($post->get('locale')) ->setServerTimeZoneId($post->get('SERVER_TIMEZONE')) ; $installer = $this->app->make(Installer::class); $installer->setOptions($options); try { $connection = $installer->createConnection(); } catch (<API key> $x) { $error->add($x->getMessage()); $connection = null; } $preconditions = $this->app->make(PreconditionService::class)-><API key>(); foreach ($preconditions as $precondition) { if ($precondition instanceof <API key>) { if ($connection === null) { continue; } $precondition->setConnection($connection); } $precondition->setInstallerOptions($options); $check = $precondition->performCheck(); switch ($check->getState()) { case PreconditionResult::STATE_SKIPPED: case PreconditionResult::STATE_PASSED: break; case PreconditionResult::STATE_WARNING: $warnings->addHtml('<span class="label label-warning">' . h($precondition->getName()) . '</span><br />' . nl2br(h($check->getMessage()))); break; case PreconditionResult::STATE_FAILED: default: if ($precondition->isOptional()) { $warnings->addHtml('<span class="label label-warning">' . h($precondition->getName()) . '</span><br />' . nl2br(h($check->getMessage()))); } else { $error->addHtml('<span class="label label-danger">' . h($precondition->getName()) . '</span><br />' . nl2br(h($check->getMessage()))); } break; } } if (!$error->has() && ($ignoreWarnings || !$warnings->has())) { $options->save(); $this->redirect('/'); } } } catch (Exception $ex) { $error->add($ex); } $this->getInstallerOptions()->deleteFiles(); $this->set('error', $error); $this->set('warnings', $warnings); $this->setup(); $this->setInstallStep(); } public function run_routine($pkgHandle, $routine) { $options = $this->getInstallerOptions(); $options->load(); $options-><API key>($pkgHandle); $jsx = $this->app->make('helper/json'); $js = new stdClass(); try { $spl = $this->installer->getStartingPoint(false); $spl-><API key>($routine); $js->error = false; } catch (Exception $e) { $js->error = true; $js->message = tc('InstallError', '%s.<br><br>Trace:<br>%s', $e->getMessage(), $e->getTraceAsString()); $options->deleteFiles(); } return $this->app->make(<API key>::class)->json($js); } /** * Get the installer instance. * * @return Installer */ protected function getInstaller() { if ($this->installer === null) { $this->installer = $this->app->make(Installer::class); } return $this->installer; } /** * Get the options used by the installer. * * @return \Concrete\Core\Install\InstallerOptions */ protected function getInstallerOptions() { return $this->getInstaller()->getOptions(); } /** * @return array */ protected function getLocales() { $localLocales = Localization::<API key>(null); $coreVersion = $this->app->make('config')->get('concrete.version_installed'); $rtp = $this->app->make(<API key>::class); // We may be offline, so let's ignore connection issues try { $remoteLocaleStats = $rtp-><API key>($coreVersion); } catch (Exception $x) { $remoteLocaleStats = []; } $remoteLocales = []; foreach (array_keys($remoteLocaleStats) as $remoteLocaleID) { if (!isset($localLocales[$remoteLocaleID])) { $remoteLocales[$remoteLocaleID] = Localization::<API key>($remoteLocaleID, null); } } $comparer = new PunicComparer(); $comparer->sort($remoteLocales, true); if (empty($localLocales) && !empty($remoteLocales)) { $localLocales = [ Localization::BASE_LOCALE => Localization::<API key>(Localization::BASE_LOCALE, null), ]; } return [$localLocales, $remoteLocales]; } protected function testAndRunInstall() { $e = $this->app->make('helper/validation/error'); try { $installerOptions = $this->getInstallerOptions(); $installerOptions->load(); $uiLocaleId = $installerOptions->getUiLocaleId(); if ($uiLocaleId !== '') { Localization::changeLocale($uiLocaleId); } $connection = $this->getInstaller()->createConnection(); $preconditions = $this->app->make(PreconditionService::class)-><API key>(); foreach ($preconditions as $precondition) { if ($precondition->isOptional()) { continue; } if ($precondition instanceof <API key>) { $precondition->setConnection($connection); } $precondition->setInstallerOptions($installerOptions); $check = $precondition->performCheck(); switch ($check->getState()) { case PreconditionResult::STATE_SKIPPED: case PreconditionResult::STATE_PASSED: case PreconditionResult::STATE_WARNING: break; case PreconditionResult::STATE_FAILED: default: $e->addHtml('<span class="label label-danger">' . h($precondition->getName()) . '</span><br />' . nl2br(h($check->getMessage()))); break; } } } catch (<API key> $x) { $e->add($x); } if ($e->has()) { $this->set('error', $e); } else { $spl = $this->getInstaller()->getStartingPoint(true); $this->set('installPackage', $spl->getPackageHandle()); $this->set('installRoutines', $spl->getInstallRoutines()); $this->set( 'successMessage', t( 'concrete5 has been installed. You have been logged in as <b>%s</b> with the password you chose. If you wish to change this password, you may do so from the users area of the dashboard.', USER_SUPER ) ); } } private function setInstallStep() { $sets = $this->getSets(); if (isset($sets['successMessage'])) { $installStep = static::STEP_INSTALL; } elseif ($this->getAction() == 'setup' || $this->getAction() == 'configure') { $installStep = static::STEP_CONFIGURATION; } elseif (isset($sets['locale']) || (empty($sets['locales']) && empty($sets['onlineLocales']))) { $installStep = static::STEP_PRECONDITIONS; } else { $installStep = static::STEP_CHOOSELOCALE; } $this->set('installStep', $installStep); } /** * @param string $languageID * * @return array */ private function <API key>($languageID) { $cl = $this->app->make('lists/countries'); $<API key> = []; foreach ($cl-><API key>($languageID) as $countryID) { $<API key>[$countryID] = $cl->getCountryName($countryID); } $otherCountries = []; foreach ($cl->getCountries() as $countryID => $countryName) { if (!isset($<API key>[$countryID])) { $otherCountries[$countryID] = $countryName; } } if (count($<API key>) === 0) { $result = $otherCountries; } elseif (count($otherCountries) === 0) { $result = $<API key>; } else { $result = [ t('** Recommended Countries') => $<API key>, t('** Other Countries') => $otherCountries, ]; } return $result; } }
<!DOCTYPE html><html lang="fr"><head> <meta charset="utf-8"> <title>Backgrounds and Skyboxes</title> <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:site" content="@threejs"> <meta name="twitter:title" content="Three.js – Backgrounds and Skyboxes"> <meta property="og:image" content="https://threejs.org/files/share.png"> <link rel="shortcut icon" href="/files/favicon_white.ico" media="(<API key>: dark)"> <link rel="shortcut icon" href="/files/favicon.ico" media="(<API key>: light)"> <link rel="stylesheet" href="/manual/resources/lesson.css"> <link rel="stylesheet" href="/manual/resources/lang.css"> <!-- Import maps polyfill --> <!-- Remove this when import maps will be widely supported --> <script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script> <script type="importmap"> { "imports": { "three": "../../build/three.module.js" } } </script> </head> <body> <div class="container"> <div class="lesson-title"> <h1>Backgrounds and Skyboxes</h1> </div> <div class="lesson"> <div class="lesson-main"> <p>Désolé, cet article n'a pas encore été traduit. <a href="https://github.com/mrdoob/three.js">Les traductions sont le bienvenue</a>! </p> <p><a href="/manual/en/backgrounds.html">Voici l'article anglais originel pour le moment</a>.</p> </div> </div> </div> <script src="/manual/resources/prettify.js"></script> <script src="/manual/resources/lesson.js"></script> </body></html>
package com.udacity.gradle.multidex; public class Methods33 { public void method_0() { } public void method_1() { } public void method_2() { } public void method_3() { } public void method_4() { } public void method_5() { } public void method_6() { } public void method_7() { } public void method_8() { } public void method_9() { } public void method_10() { } public void method_11() { } public void method_12() { } public void method_13() { } public void method_14() { } public void method_15() { } public void method_16() { } public void method_17() { } public void method_18() { } public void method_19() { } public void method_20() { } public void method_21() { } public void method_22() { } public void method_23() { } public void method_24() { } public void method_25() { } public void method_26() { } public void method_27() { } public void method_28() { } public void method_29() { } public void method_30() { } public void method_31() { } public void method_32() { } public void method_33() { } public void method_34() { } public void method_35() { } public void method_36() { } public void method_37() { } public void method_38() { } public void method_39() { } public void method_40() { } public void method_41() { } public void method_42() { } public void method_43() { } public void method_44() { } public void method_45() { } public void method_46() { } public void method_47() { } public void method_48() { } public void method_49() { } public void method_50() { } public void method_51() { } public void method_52() { } public void method_53() { } public void method_54() { } public void method_55() { } public void method_56() { } public void method_57() { } public void method_58() { } public void method_59() { } public void method_60() { } public void method_61() { } public void method_62() { } public void method_63() { } public void method_64() { } public void method_65() { } public void method_66() { } public void method_67() { } public void method_68() { } public void method_69() { } public void method_70() { } public void method_71() { } public void method_72() { } public void method_73() { } public void method_74() { } public void method_75() { } public void method_76() { } public void method_77() { } public void method_78() { } public void method_79() { } public void method_80() { } public void method_81() { } public void method_82() { } public void method_83() { } public void method_84() { } public void method_85() { } public void method_86() { } public void method_87() { } public void method_88() { } public void method_89() { } public void method_90() { } public void method_91() { } public void method_92() { } public void method_93() { } public void method_94() { } public void method_95() { } public void method_96() { } public void method_97() { } public void method_98() { } public void method_99() { } public void method_100() { } public void method_101() { } public void method_102() { } public void method_103() { } public void method_104() { } public void method_105() { } public void method_106() { } public void method_107() { } public void method_108() { } public void method_109() { } public void method_110() { } public void method_111() { } public void method_112() { } public void method_113() { } public void method_114() { } public void method_115() { } public void method_116() { } public void method_117() { } public void method_118() { } public void method_119() { } public void method_120() { } public void method_121() { } public void method_122() { } public void method_123() { } public void method_124() { } public void method_125() { } public void method_126() { } public void method_127() { } public void method_128() { } public void method_129() { } public void method_130() { } public void method_131() { } public void method_132() { } public void method_133() { } public void method_134() { } public void method_135() { } public void method_136() { } public void method_137() { } public void method_138() { } public void method_139() { } public void method_140() { } public void method_141() { } public void method_142() { } public void method_143() { } public void method_144() { } public void method_145() { } public void method_146() { } public void method_147() { } public void method_148() { } public void method_149() { } public void method_150() { } public void method_151() { } public void method_152() { } public void method_153() { } public void method_154() { } public void method_155() { } public void method_156() { } public void method_157() { } public void method_158() { } public void method_159() { } public void method_160() { } public void method_161() { } public void method_162() { } public void method_163() { } public void method_164() { } public void method_165() { } public void method_166() { } public void method_167() { } public void method_168() { } public void method_169() { } public void method_170() { } public void method_171() { } public void method_172() { } public void method_173() { } public void method_174() { } public void method_175() { } public void method_176() { } public void method_177() { } public void method_178() { } public void method_179() { } public void method_180() { } public void method_181() { } public void method_182() { } public void method_183() { } public void method_184() { } public void method_185() { } public void method_186() { } public void method_187() { } public void method_188() { } public void method_189() { } public void method_190() { } public void method_191() { } public void method_192() { } public void method_193() { } public void method_194() { } public void method_195() { } public void method_196() { } public void method_197() { } public void method_198() { } public void method_199() { } public void method_200() { } public void method_201() { } public void method_202() { } public void method_203() { } public void method_204() { } public void method_205() { } public void method_206() { } public void method_207() { } public void method_208() { } public void method_209() { } public void method_210() { } public void method_211() { } public void method_212() { } public void method_213() { } public void method_214() { } public void method_215() { } public void method_216() { } public void method_217() { } public void method_218() { } public void method_219() { } public void method_220() { } public void method_221() { } public void method_222() { } public void method_223() { } public void method_224() { } public void method_225() { } public void method_226() { } public void method_227() { } public void method_228() { } public void method_229() { } public void method_230() { } public void method_231() { } public void method_232() { } public void method_233() { } public void method_234() { } public void method_235() { } public void method_236() { } public void method_237() { } public void method_238() { } public void method_239() { } public void method_240() { } public void method_241() { } public void method_242() { } public void method_243() { } public void method_244() { } public void method_245() { } public void method_246() { } public void method_247() { } public void method_248() { } public void method_249() { } public void method_250() { } public void method_251() { } public void method_252() { } public void method_253() { } public void method_254() { } public void method_255() { } public void method_256() { } public void method_257() { } public void method_258() { } public void method_259() { } public void method_260() { } public void method_261() { } public void method_262() { } public void method_263() { } public void method_264() { } public void method_265() { } public void method_266() { } public void method_267() { } public void method_268() { } public void method_269() { } public void method_270() { } public void method_271() { } public void method_272() { } public void method_273() { } public void method_274() { } public void method_275() { } public void method_276() { } public void method_277() { } public void method_278() { } public void method_279() { } public void method_280() { } public void method_281() { } public void method_282() { } public void method_283() { } public void method_284() { } public void method_285() { } public void method_286() { } public void method_287() { } public void method_288() { } public void method_289() { } public void method_290() { } public void method_291() { } public void method_292() { } public void method_293() { } public void method_294() { } public void method_295() { } public void method_296() { } public void method_297() { } public void method_298() { } public void method_299() { } public void method_300() { } public void method_301() { } public void method_302() { } public void method_303() { } public void method_304() { } public void method_305() { } public void method_306() { } public void method_307() { } public void method_308() { } public void method_309() { } public void method_310() { } public void method_311() { } public void method_312() { } public void method_313() { } public void method_314() { } public void method_315() { } public void method_316() { } public void method_317() { } public void method_318() { } public void method_319() { } public void method_320() { } public void method_321() { } public void method_322() { } public void method_323() { } public void method_324() { } public void method_325() { } public void method_326() { } public void method_327() { } public void method_328() { } public void method_329() { } public void method_330() { } public void method_331() { } public void method_332() { } public void method_333() { } public void method_334() { } public void method_335() { } public void method_336() { } public void method_337() { } public void method_338() { } public void method_339() { } public void method_340() { } public void method_341() { } public void method_342() { } public void method_343() { } public void method_344() { } public void method_345() { } public void method_346() { } public void method_347() { } public void method_348() { } public void method_349() { } public void method_350() { } public void method_351() { } public void method_352() { } public void method_353() { } public void method_354() { } public void method_355() { } public void method_356() { } public void method_357() { } public void method_358() { } public void method_359() { } public void method_360() { } public void method_361() { } public void method_362() { } public void method_363() { } public void method_364() { } public void method_365() { } public void method_366() { } public void method_367() { } public void method_368() { } public void method_369() { } public void method_370() { } public void method_371() { } public void method_372() { } public void method_373() { } public void method_374() { } public void method_375() { } public void method_376() { } public void method_377() { } public void method_378() { } public void method_379() { } public void method_380() { } public void method_381() { } public void method_382() { } public void method_383() { } public void method_384() { } public void method_385() { } public void method_386() { } public void method_387() { } public void method_388() { } public void method_389() { } public void method_390() { } public void method_391() { } public void method_392() { } public void method_393() { } public void method_394() { } public void method_395() { } public void method_396() { } public void method_397() { } public void method_398() { } public void method_399() { } public void method_400() { } public void method_401() { } public void method_402() { } public void method_403() { } public void method_404() { } public void method_405() { } public void method_406() { } public void method_407() { } public void method_408() { } public void method_409() { } public void method_410() { } public void method_411() { } public void method_412() { } public void method_413() { } public void method_414() { } public void method_415() { } public void method_416() { } public void method_417() { } public void method_418() { } public void method_419() { } public void method_420() { } public void method_421() { } public void method_422() { } public void method_423() { } public void method_424() { } public void method_425() { } public void method_426() { } public void method_427() { } public void method_428() { } public void method_429() { } public void method_430() { } public void method_431() { } public void method_432() { } public void method_433() { } public void method_434() { } public void method_435() { } public void method_436() { } public void method_437() { } public void method_438() { } public void method_439() { } public void method_440() { } public void method_441() { } public void method_442() { } public void method_443() { } public void method_444() { } public void method_445() { } public void method_446() { } public void method_447() { } public void method_448() { } public void method_449() { } public void method_450() { } public void method_451() { } public void method_452() { } public void method_453() { } public void method_454() { } public void method_455() { } public void method_456() { } public void method_457() { } public void method_458() { } public void method_459() { } public void method_460() { } public void method_461() { } public void method_462() { } public void method_463() { } public void method_464() { } public void method_465() { } public void method_466() { } public void method_467() { } public void method_468() { } public void method_469() { } public void method_470() { } public void method_471() { } public void method_472() { } public void method_473() { } public void method_474() { } public void method_475() { } public void method_476() { } public void method_477() { } public void method_478() { } public void method_479() { } public void method_480() { } public void method_481() { } public void method_482() { } public void method_483() { } public void method_484() { } public void method_485() { } public void method_486() { } public void method_487() { } public void method_488() { } public void method_489() { } public void method_490() { } public void method_491() { } public void method_492() { } public void method_493() { } public void method_494() { } public void method_495() { } public void method_496() { } public void method_497() { } public void method_498() { } public void method_499() { } public void method_500() { } public void method_501() { } public void method_502() { } public void method_503() { } public void method_504() { } public void method_505() { } public void method_506() { } public void method_507() { } public void method_508() { } public void method_509() { } public void method_510() { } public void method_511() { } public void method_512() { } public void method_513() { } public void method_514() { } public void method_515() { } public void method_516() { } public void method_517() { } public void method_518() { } public void method_519() { } public void method_520() { } public void method_521() { } public void method_522() { } public void method_523() { } public void method_524() { } public void method_525() { } public void method_526() { } public void method_527() { } public void method_528() { } public void method_529() { } public void method_530() { } public void method_531() { } public void method_532() { } public void method_533() { } public void method_534() { } public void method_535() { } public void method_536() { } public void method_537() { } public void method_538() { } public void method_539() { } public void method_540() { } public void method_541() { } public void method_542() { } public void method_543() { } public void method_544() { } public void method_545() { } public void method_546() { } public void method_547() { } public void method_548() { } public void method_549() { } public void method_550() { } public void method_551() { } public void method_552() { } public void method_553() { } public void method_554() { } public void method_555() { } public void method_556() { } public void method_557() { } public void method_558() { } public void method_559() { } public void method_560() { } public void method_561() { } public void method_562() { } public void method_563() { } public void method_564() { } public void method_565() { } public void method_566() { } public void method_567() { } public void method_568() { } public void method_569() { } public void method_570() { } public void method_571() { } public void method_572() { } public void method_573() { } public void method_574() { } public void method_575() { } public void method_576() { } public void method_577() { } public void method_578() { } public void method_579() { } public void method_580() { } public void method_581() { } public void method_582() { } public void method_583() { } public void method_584() { } public void method_585() { } public void method_586() { } public void method_587() { } public void method_588() { } public void method_589() { } public void method_590() { } public void method_591() { } public void method_592() { } public void method_593() { } public void method_594() { } public void method_595() { } public void method_596() { } public void method_597() { } public void method_598() { } public void method_599() { } public void method_600() { } public void method_601() { } public void method_602() { } public void method_603() { } public void method_604() { } public void method_605() { } public void method_606() { } public void method_607() { } public void method_608() { } public void method_609() { } public void method_610() { } public void method_611() { } public void method_612() { } public void method_613() { } public void method_614() { } public void method_615() { } public void method_616() { } public void method_617() { } public void method_618() { } public void method_619() { } public void method_620() { } public void method_621() { } public void method_622() { } public void method_623() { } public void method_624() { } public void method_625() { } public void method_626() { } public void method_627() { } public void method_628() { } public void method_629() { } public void method_630() { } public void method_631() { } public void method_632() { } public void method_633() { } public void method_634() { } public void method_635() { } public void method_636() { } public void method_637() { } public void method_638() { } public void method_639() { } public void method_640() { } public void method_641() { } public void method_642() { } public void method_643() { } public void method_644() { } public void method_645() { } public void method_646() { } public void method_647() { } public void method_648() { } public void method_649() { } public void method_650() { } public void method_651() { } public void method_652() { } public void method_653() { } public void method_654() { } public void method_655() { } public void method_656() { } public void method_657() { } public void method_658() { } public void method_659() { } public void method_660() { } public void method_661() { } public void method_662() { } public void method_663() { } public void method_664() { } public void method_665() { } public void method_666() { } public void method_667() { } public void method_668() { } public void method_669() { } public void method_670() { } public void method_671() { } public void method_672() { } public void method_673() { } public void method_674() { } public void method_675() { } public void method_676() { } public void method_677() { } public void method_678() { } public void method_679() { } public void method_680() { } public void method_681() { } public void method_682() { } public void method_683() { } public void method_684() { } public void method_685() { } public void method_686() { } public void method_687() { } public void method_688() { } public void method_689() { } public void method_690() { } public void method_691() { } public void method_692() { } public void method_693() { } public void method_694() { } public void method_695() { } public void method_696() { } public void method_697() { } public void method_698() { } public void method_699() { } public void method_700() { } }
Ti=Article 36 - Prior consultation 1.sec=The {_controller} shall consult the {<API key>} prior to {_processing} where a data protection impact assessment under Article 35 indicates that the {_processing} would result in a high risk in the absence of measures taken by the {_controller} to mitigate the risk. 2.sec=Where the {<API key>} is of the opinion that the intended {_processing} referred to in paragraph 1 would infringe this Regulation, in particular where the {_controller} has insufficiently identified or mitigated the risk, the {<API key>} shall, within period of up to eight weeks of receipt of the request for consultation, provide written advice to the {_controller} and, where applicable to the {_processor}, and may use any of its powers referred to in Article 58. That period may be extended by six weeks, taking into account the complexity of the intended {_processing}. The {<API key>} shall inform the {_controller} and, where applicable, the {_processor}, of any such extension within one month of receipt of the request for consultation together with the reasons for the delay. Those periods may be suspended until the {<API key>} has obtained information it has requested for the purposes of the consultation. 3.0.sec=When consulting the {<API key>} pursuant to paragraph 1, the {_controller} shall provide the {<API key>} with: 3.1.sec=where applicable, the respective responsibilities of the {_controller}, joint {_controllers} and {_processors} involved in the {_processing}, in particular for {_processing} within a {<API key>}; 3.2.sec=the purposes and means of the intended {_processing}; 3.3.sec=the measures and safeguards provided to protect the rights and freedoms of {_data_subjects} pursuant to this Regulation; 3.4.sec=where applicable, the contact details of the data protection officer; 3.5.sec=the data protection impact assessment provided for in Article 35; and 3.6.sec=any other information requested by the {<API key>}. 3.=[G/Z/ol-a/s6] 4.sec=Member States shall consult the {<API key>} during the preparation of a proposal for a legislative measure to be adopted by a national parliament, or of a regulatory measure based on such a legislative measure, which relates to {_processing}. 5.sec=Notwithstanding paragraph 1, Member State law may require {_controllers} to consult with, and obtain prior authorisation from, the {<API key>} in relation to {_processing} by a {_controller} for the performance of a task carried out by the {_controller} in the public interest, including {_processing} in relation to social protection and public health. =[G/Z/ol/s5]
package endpoint import ( "errors" "golang.org/x/net/context" ) // Endpoint is the fundamental building block of servers and clients. // It represents a single RPC method. type Endpoint func(ctx context.Context, request interface{}) (response interface{}, err error) // Nop is an endpoint that does nothing and returns a nil error. // Useful for tests. func Nop(context.Context, interface{}) (interface{}, error) { return struct{}{}, nil } // Middleware is a chainable behavior modifier for endpoints. type Middleware func(Endpoint) Endpoint // ErrBadCast indicates an unexpected concrete request or response struct was // received from an endpoint. var ErrBadCast = errors.New("bad cast") // ErrContextCanceled indicates the request context was canceled. var ErrContextCanceled = errors.New("context canceled") // Chain is a helper function for composing middlewares. Requests will // traverse them in the order they're declared. That is, the first middleware // is treated as the outermost middleware. func Chain(outer Middleware, others ...Middleware) Middleware { return func(next Endpoint) Endpoint { for i := len(others) - 1; i >= 0; i-- { // reverse next = others[i](next) } return outer(next) } }
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Sun Nov 03 15:35:47 CET 2013 --> <title>Uses of Class com.badlogic.gdx.graphics.g2d.SpriteCache (libgdx API)</title> <meta name="date" content="2013-11-03"> <link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.badlogic.gdx.graphics.g2d.SpriteCache (libgdx API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../com/badlogic/gdx/graphics/g2d/SpriteCache.html" title="class in com.badlogic.gdx.graphics.g2d">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> libgdx API <style> body, td, th { font-family:Helvetica, Tahoma, Arial, sans-serif; font-size:10pt } pre, code, tt { font-size:9pt; font-family:Lucida Console, Courier New, sans-serif } h1, h2, h3, .FrameTitleFont, .FrameHeadingFont, .TableHeadingColor font { font-size:105%; font-weight:bold } .TableHeadingColor { background:#EEEEFF; } a { text-decoration:none } a:hover { text-decoration:underline } a:link, a:visited { color:blue } table { border:0px } .TableRowColor td:first-child { border-left:1px solid black } .TableRowColor td { border:0px; border-bottom:1px solid black; border-right:1px solid black } hr { border:0px; border-bottom:1px solid #333366; } </style> </em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?com/badlogic/gdx/graphics/g2d/class-use/SpriteCache.html" target="_top">Frames</a></li> <li><a href="SpriteCache.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <h2 title="Uses of Class com.badlogic.gdx.graphics.g2d.SpriteCache" class="title">Uses of Class<br>com.badlogic.gdx.graphics.g2d.SpriteCache</h2> </div> <div class="classUseContainer">No usage of com.badlogic.gdx.graphics.g2d.SpriteCache</div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../../com/badlogic/gdx/graphics/g2d/SpriteCache.html" title="class in com.badlogic.gdx.graphics.g2d">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em>libgdx API</em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../../index.html?com/badlogic/gdx/graphics/g2d/class-use/SpriteCache.html" target="_top">Frames</a></li> <li><a href="SpriteCache.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small> <div style="font-size:9pt"><i> Copyright &copy; 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com) </i></div> </small></p> </body> </html>
#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #include <QUrl> #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("zedcoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::<API key>() { genCode(); } void QRCodeDialog::<API key>() { genCode(); } void QRCodeDialog::<API key>() { genCode(); } void QRCodeDialog::<API key>() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::<API key>(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } }
module.exports = { 'type': 'MultiPolygon', 'coordinates': [ [ [ [ 102.0, 2.0 ], [ 103.0, 2.0 ], [ 103.0, 3.0 ], [ 102.0, 3.0 ], [ 102.0, 2.0 ] ] ], [ [ [ 100.0, 0.0 ], [ 101.0, 0.0 ], [ 101.0, 1.0 ], [ 100.0, 1.0 ], [ 100.0, 0.0 ] ], [ [ 100.2, 0.2 ], [ 100.8, 0.2 ], [ 100.8, 0.8 ], [ 100.2, 0.8 ], [ 100.2, 0.2 ] ] ] ] };
define({ "_themeLabel": "Sklopiva tema", "_layout_default": "Podrazumevani raspored", "_layout_layout1": "Raspored 1" });
module.exports = require('./lib/sphinxapi.js');
<?php /** * @namespace */ namespace Zend\GData\EXIF\Extension; class Model extends \Zend\GData\Extension { protected $_rootNamespace = 'exif'; protected $_rootElement = 'model'; /** * Constructs a new <API key> object. * * @param string $text (optional) The value to use for this element. */ public function __construct($text = null) { $this-><API key>(\Zend\GData\EXIF::$namespaces); parent::__construct(); $this->setText($text); } }
from django.core.management.base import BaseCommand from django.core import serializers from opps.boxes.models import QuerySet from opps.channels.models import Channel from opps.containers.models import ContainerBox class Command(BaseCommand): def handle(self, *args, **options): models = [Channel, ContainerBox, QuerySet] for m in models: data = serializers.serialize("json", m.objects.all()) out = open("opps_{0}.json".format(m.__name__), "w") out.write(data) out.close()
#ifndef IMAGE_INCLUDED #define IMAGE_INCLUDED #define SUPPORT_TILES #include <string.h> #include "MyMiscellany.h" struct ImageReader { virtual unsigned int nextRow( unsigned char* row ) = 0; static unsigned char* Read( const char* fileName , unsigned int& width , unsigned int& height , unsigned int& channels ) { ImageReader* reader = Get( fileName ); width = reader->width() , height = reader->height() , channels = reader->channels(); unsigned char* pixels = new unsigned char[ width*height*channels ]; for( unsigned int j=0 ; j<height ; j++ ) reader->nextRow( pixels + j*width*channels ); delete reader; return pixels; } static unsigned char* ReadColor( const char* fileName , unsigned int& width , unsigned int& height ) { unsigned int channels; ImageReader* reader = Get( fileName ); width = reader->width() , height = reader->height() , channels = reader->channels(); if( channels!=1 && channels!=3 ) ERROR_OUT( "Requres one- or three-channel input" ); unsigned char* pixels = new unsigned char[ width*height*3 ]; unsigned char* pixelRow = new unsigned char[ width*channels]; for( unsigned int j=0 ; j<height ; j++ ) { reader->nextRow( pixelRow ); if ( channels==3 ) memcpy( pixels+j*width*3 , pixelRow , sizeof(unsigned char)*width*3 ); else if( channels==1 ) for( unsigned int i=0 ; i<width ; i++ ) for( unsigned int c=0 ; c<3 ; c++ ) pixels[j*width*3+i*3+c] = pixelRow[i]; } delete[] pixelRow; delete reader; return pixels; } static bool ValidExtension( const char *ext ); static ImageReader* Get( const char* fileName ); static void GetInfo( const char* fileName , unsigned int& width , unsigned int& height , unsigned int& channels ); virtual ~ImageReader( void ){ } unsigned int width( void ) const { return _width; } unsigned int height( void ) const { return _height; } unsigned int channels( void ) const { return _channels; } protected: unsigned int _width , _height , _channels; }; struct ImageWriterParams { static const char* <API key>; unsigned int quality; #ifdef SUPPORT_TILES const char* tileExtension; unsigned int tileWidth , tileHeight; ImageWriterParams* tileParams; ImageWriterParams( void ) : quality( 100 ) , tileExtension( <API key> ) , tileWidth( 4096 ) , tileHeight( 4096 ) , tileParams( NULL ){}; #else // !SUPPORT_TILES ImageWriterParams( void ) : quality( 100 ){}; #endif // SUPPORT_TILES }; const char* ImageWriterParams::<API key> = "jpg"; struct ImageWriter { virtual unsigned int nextRow( const unsigned char* row ) = 0; virtual unsigned int nextRows( const unsigned char* rows , unsigned int rowNum ){ unsigned int row ; for( unsigned int r=0 ; r<rowNum ; r++ ) row = nextRow( rows + _width * _channels * r ) ; return row; } static void Write( const char* fileName , const unsigned char* pixels , unsigned int width , unsigned int height , unsigned int channels , ImageWriterParams params=ImageWriterParams() ) { ImageWriter* writer = Get( fileName , width , height , channels , params ); for( unsigned int j=0 ; j<height ; j++ ) writer->nextRow( pixels + j*width*channels ); delete writer; } static bool ValidExtension( const char *ext ); static ImageWriter* Get( const char* fileName , unsigned int width , unsigned int height , unsigned int channels , ImageWriterParams params=ImageWriterParams() ); virtual ~ImageWriter( void ){ } unsigned int width( void ) const { return _width; } unsigned int height( void ) const { return _height; } unsigned int channels( void ) const { return _channels; } protected: unsigned int _width , _height , _channels; }; #ifdef SUPPORT_TILES struct TiledImageReader : public ImageReader { unsigned int nextRow( unsigned char* row ); TiledImageReader( const char* fileName , unsigned int& width , unsigned int& height , unsigned int& channels ); ~TiledImageReader( void ); static bool GetInfo( const char* fileName , unsigned int& width , unsigned int& height , unsigned int& channels ); protected: ImageReader** _tileReaders; char** _tileNames; unsigned int _tileRows , _tileColumns , _currentPixelRow , _currentTileRow , *_tileWidths , *_tileHeights; }; struct TiledImageWriter : public ImageWriter { unsigned int nextRow( const unsigned char* row ); TiledImageWriter( const char* fileName , unsigned int width , unsigned int height , unsigned int channels , ImageWriterParams params ); ~TiledImageWriter( void ); protected: ImageWriter** _tileWriters; char** _tileNames; unsigned int _tileWidth , _tileHeight , _tileRows , _tileColumns , _currentPixelRow; ImageWriterParams _params; }; #endif // SUPPORT_TILES // [WARNING] Need to include "png.h" before "jpeg.h" so that "setjmp.h" is not already included (?) #include "PNG.h" #include "JPEG.h" struct FileNameParser { #if defined( _WIN32 ) || defined( _WIN64 ) static const char Separator = (char)'\\'; #else // !_WIN static const char Separator = (char)'/'; #endif // _WIN static inline char* Extension ( const char* fileName ){ return __Split( fileName , '.' , false , false ); } static inline char* Header ( const char* fileName ){ return __Split( fileName , '.' , true , false ); } static inline char* Local ( const char* fileName ){ return __Split( fileName , Separator , false , false ); } static inline char* Dir ( const char* fileName ){ return __Split( fileName , Separator , true , false ); } static inline char* LocalHeader( const char* fileName ) { char* localFileName = Local( fileName ); if( !localFileName ) ERROR_OUT( "Couldn't get local file name: " , fileName ); char* localFileHeader = Header( localFileName ); delete[] localFileName; return localFileHeader; } protected: static inline char* __Split( const char* fileName , char splitChar , bool front , bool first ) { int position; char* out; if( first ){ for( position=0 ; position<strlen(fileName) ; position++ ) if( fileName[position]==splitChar ) break; } else { for( position=(int)strlen(fileName)-1 ; position>=0 ; position-- ) if( fileName[position]==splitChar ) break; } if( front ) { if( position==-1 ) out = NULL; else { out = new char[ strlen(fileName)+1 ]; strcpy( out , fileName ); out[ position ] = 0; } } else { if( position==strlen(fileName) ) out = NULL; else { out = new char[ strlen(fileName)-position ]; strcpy( out , fileName+position+1 ); } } return out; } }; inline bool ImageReader::ValidExtension( const char *ext ) { #ifdef WIN32 if ( !_stricmp( ext , "jpeg" ) || !_stricmp( ext , "jpg" ) ) return true; else if( !_stricmp( ext , "png" ) ) return true; else if( !_stricmp( ext , "iGrid" ) ) return true; #else // !WIN32 if( !strcasecmp( ext , "jpeg" ) || !strcasecmp( ext , "jpg" ) ) return true; else if( !strcasecmp( ext , "png" ) ) return true; else if( !strcasecmp( ext , "iGrid" ) ) return true; #endif // WIN32 return false; } inline ImageReader* ImageReader::Get( const char* fileName ) { unsigned int width , height , channels; ImageReader* reader = NULL; char* ext = FileNameParser::Extension( fileName ); #ifdef WIN32 if ( !_stricmp( ext , "jpeg" ) || !_stricmp( ext , "jpg" ) ) reader = new JPEGReader( fileName , width , height , channels ); else if( !_stricmp( ext , "png" ) ) reader = new PNGReader( fileName , width , height , channels ); else if( !_stricmp( ext , "iGrid" ) ) reader = new TiledImageReader( fileName , width , height , channels ); #else // !WIN32 if( !strcasecmp( ext , "jpeg" ) || !strcasecmp( ext , "jpg" ) ) reader = new JPEGReader( fileName , width , height , channels ); else if( !strcasecmp( ext , "png" ) ) reader = new PNGReader( fileName , width , height , channels ); else if( !strcasecmp( ext , "iGrid" ) ) reader = new TiledImageReader( fileName , width , height , channels ); #endif // WIN32 else { delete[] ext; THROW( "failed to get image reader for: " , fileName ); } reader->_width = width; reader->_height = height; reader->_channels = channels; delete[] ext; return reader; } inline void ImageReader::GetInfo( const char* fileName , unsigned int& width , unsigned int& height , unsigned int& channels ) { char* ext = FileNameParser::Extension( fileName ); #ifdef WIN32 if( !_stricmp( ext , "jpeg" ) || !_stricmp( ext , "jpg" ) ) JPEGReader::GetInfo( fileName , width , height , channels ); else if( !_stricmp( ext , "png" ) ) PNGReader::GetInfo( fileName , width , height , channels ); else if( !_stricmp( ext , "iGrid" ) ) TiledImageReader::GetInfo( fileName , width , height , channels ); #else // !WIN32 if( !strcasecmp( ext , "jpeg" ) || !strcasecmp( ext , "jpg" ) ) JPEGReader::GetInfo( fileName , width , height , channels ); else if( !strcasecmp( ext , "png" ) ) PNGReader::GetInfo( fileName , width , height , channels ); else if( !strcasecmp( ext , "iGrid" ) ) TiledImageReader::GetInfo( fileName , width , height , channels ); #endif // WIN32 delete[] ext; } inline bool ImageWriter::ValidExtension( const char *ext ) { #ifdef WIN32 if( !_stricmp( ext , "jpeg" ) || !_stricmp( ext , "jpg" ) ) return true; else if( !_stricmp( ext , "png" ) ) return true; #ifdef SUPPORT_TILES else if( !_stricmp( ext , "iGrid" ) ) return true; #endif // SUPPORT_TILES #else // !WIN32 if( !strcasecmp( ext , "jpeg" ) || !strcasecmp( ext , "jpg" ) ) return true; else if( !strcasecmp( ext , "png" ) ) return true; #ifdef SUPPORT_TILES else if( !strcasecmp( ext , "iGrid" ) ) return true; #endif // SUPPORT_TILES #endif // WIN32 return false; } inline ImageWriter* ImageWriter::Get( const char* fileName , unsigned int width , unsigned int height , unsigned int channels , ImageWriterParams params ) { ImageWriter* writer = NULL; char* ext = FileNameParser::Extension( fileName ); #ifdef WIN32 if( !_stricmp( ext , "jpeg" ) || !_stricmp( ext , "jpg" ) ) writer = new JPEGWriter( fileName , width , height , channels , params.quality ); else if( !_stricmp( ext , "png" ) ) writer = new PNGWriter( fileName , width , height , channels , params.quality ); #ifdef SUPPORT_TILES else if( !_stricmp( ext , "iGrid" ) ) writer = new TiledImageWriter( fileName , width , height , channels , params ); #endif // SUPPORT_TILES #else // !WIN32 if( !strcasecmp( ext , "jpeg" ) || !strcasecmp( ext , "jpg" ) ) writer = new JPEGWriter( fileName , width , height , channels , params.quality ); else if( !strcasecmp( ext , "png" ) ) writer = new PNGWriter( fileName , width , height , channels , params.quality ); #ifdef SUPPORT_TILES else if( !strcasecmp( ext , "iGrid" ) ) writer = new TiledImageWriter( fileName , width , height , channels , params ); #endif // SUPPORT_TILES #endif // WIN32 else { delete[] ext; THROW( "failed to get image writer for: " , fileName ); } writer->_width = width; writer->_height = height; writer->_channels = channels; delete[] ext; return writer; } #ifdef SUPPORT_TILES bool TiledImageReader::GetInfo( const char* fileName , unsigned int& width , unsigned int& height , unsigned int& channels ) { char* fileDir = FileNameParser::Dir( fileName ); unsigned int *_tileHeights , *_tileWidths; unsigned int _tileRows , _tileColumns , _channels; FILE* fp = fopen( fileName , "r" ); if( !fp ){ WARN( "Couldn't open file for reading: " , fileName ) ; return false; } { char line[1024]; if( !fgets( line , 1024 , fp ) ) ERROR_OUT( "Failed to read column line from: " , fileName ); line[strlen(line)-1] = 0; if( sscanf( line , "Columns: %d" , &_tileColumns )!=1 ) ERROR_OUT( "Failed to read column count from: " , fileName , " (" , line , ")" ); if( !fgets( line , 1024 , fp ) ) ERROR_OUT( "Failed to read row line from: " , fileName ); line[strlen(line)-1] = 0; if( sscanf( line , "Rows: %d" , &_tileRows )!=1 ) ERROR_OUT( "Failed to read row count from: " , fileName , " (" , line , ")" ); _tileHeights = new unsigned int[ _tileRows+1 ]; _tileWidths = new unsigned int[ _tileColumns+1 ]; char tileName[1024]; for( unsigned int r=0 ; r<_tileRows ; r++ ) for( unsigned int c=0 ; c<_tileColumns ; c++ ) { if( !fgets( line , 1024 , fp ) ) ERROR_OUT( "Failed to read tile name from: " , fileName ); line[strlen(line)-1] = 0; if( fileDir ) sprintf( tileName , "%s%c%s" , fileDir , FileNameParser::Separator , line ); else sprintf( tileName , "%s" , line ); unsigned int _w , _h , _c; ImageReader::GetInfo( tileName , _w , _h , _c ); if( !r && !c ) _channels = _c; else if( _channels!=_c ) ERROR_OUT( "Number of color channels don't match: " , _channels , " != " , _c ); if( !r ) _tileWidths[c+1] = _w; else if( _tileWidths[c+1]!=_w ) ERROR_OUT( "Images in the same column must have the same width: " , _tileWidths[c+1] , " != " , _w ); if( !c ) _tileHeights[r+1] = _h; else if( _tileHeights[r+1]!=_h ) ERROR_OUT( "Images in the same row must have the same heights: " , _tileHeights[r+1] ," != " , _h ); } } fclose( fp ); if( fileDir ) delete[] fileDir; _tileWidths[0] = _tileHeights[0] = 0; for( unsigned int c=0 ; c<_tileColumns ; c++ ) _tileWidths[c+1] += _tileWidths[c]; for( unsigned int r=0 ; r<_tileRows ; r++ ) _tileHeights[r+1] += _tileHeights[r]; width = _tileWidths[_tileColumns] , height = _tileHeights[_tileRows] , channels = _channels; return true; } TiledImageReader::TiledImageReader( const char* fileName , unsigned int& width , unsigned int& height , unsigned int& channels ) { char* fileDir = FileNameParser::Dir( fileName ); FILE* fp = fopen( fileName , "r" ); if( !fp ) ERROR_OUT( "Couldn't open file for reading: " , fileName ); { char line[1024]; if( !fgets( line , 1024 , fp ) ) ERROR_OUT( "Failed read column line from: " , fileName ); line[strlen(line)-1] = 0; if( sscanf( line , "Columns: %d" , &_tileColumns )!=1 ) ERROR_OUT( "Failed to read column count from: " , fileName , " (" , line , ")" ); if( !fgets( line , 1024 , fp ) ) ERROR_OUT( "Failed read row line from: " , fileName ); line[strlen(line)-1] = 0; if( sscanf( line , "Rows: %d" , &_tileRows )!=1 ) ERROR_OUT( "Failed to read row count from: " , fileName , " (" , line , ")" ); _tileReaders = new ImageReader*[ _tileColumns ]; _tileHeights = new unsigned int[ _tileRows+1 ]; _tileWidths = new unsigned int[ _tileColumns+1 ]; _tileNames = new char*[ _tileColumns * _tileRows ]; char tileName[1024]; for( unsigned int r=0 ; r<_tileRows ; r++ ) for( unsigned int c=0 ; c<_tileColumns ; c++ ) { if( !fgets( line , 1024 , fp ) ) ERROR_OUT( "Failed to read tile name from: " , fileName ); line[strlen(line)-1] = 0; if( fileDir ) sprintf( tileName , "%s%c%s" , fileDir , FileNameParser::Separator , line ); else sprintf( tileName , "%s" , line ); _tileNames[r*_tileColumns+c] = new char[ strlen(tileName)+1 ]; strcpy( _tileNames[r*_tileColumns+c] , tileName ); } } fclose( fp ); if( fileDir ) delete[] fileDir; for( unsigned int r=0 ; r<_tileRows ; r++ ) for( unsigned int c=0 ; c<_tileColumns ; c++ ) { unsigned int _w , _h , _c; ImageReader::GetInfo( _tileNames[r*_tileColumns+c] , _w , _h , _c ); if( !r && !c ) _channels = _c; else if( _channels!=_c ) ERROR_OUT( "Number of color channels don't match: " , _channels , " != " , _c ); if( !r ) _tileWidths[c+1] = _w; else if( _tileWidths[c+1]!=_w ) ERROR_OUT( "Images in the same column must have the same width: " , _tileWidths[c+1] , " != " , _w ); if( !c ) _tileHeights[r+1] = _h; else if( _tileHeights[r+1]!=_h ) ERROR_OUT( "Images in the same row must have the same heights: " , _tileHeights[r+1] , " != " , _h ); } _tileWidths[0] = _tileHeights[0] = 0; for( unsigned int c=0 ; c<_tileColumns ; c++ ) _tileWidths[c+1] += _tileWidths[c]; for( unsigned int r=0 ; r<_tileRows ; r++ ) _tileHeights[r+1] += _tileHeights[r]; width = _width = _tileWidths[_tileColumns] , height = _height = _tileHeights[_tileRows] , channels = _channels; _currentPixelRow = _currentTileRow = 0; } TiledImageReader::~TiledImageReader( void ) { delete[] _tileReaders; for( unsigned int i=0 ; i<_tileColumns*_tileRows ; i++ ) delete[] _tileNames[i]; delete[] _tileNames; delete[] _tileWidths; delete[] _tileHeights; } unsigned TiledImageReader::nextRow( unsigned char* row ) { // If it's the first row, set up the readers if( _currentPixelRow==_tileHeights[ _currentTileRow ] ) for( unsigned int c=0 ; c<_tileColumns ; c++ ) _tileReaders[c] = ImageReader::Get( _tileNames[ _currentTileRow * _tileColumns + c ] ); // Read the row fragments for( unsigned int c=0 ; c<_tileColumns ; c++ ) _tileReaders[c]->nextRow( row + c * _tileWidths[c] * _channels ); // If it's the last row of the tile, free up the readers if( _currentPixelRow==_tileHeights[_currentTileRow+1]-1 ) { for( unsigned int c=0 ; c<_tileColumns ; c++ ) delete _tileReaders[c]; _currentTileRow++; } return _currentPixelRow++; } TiledImageWriter::TiledImageWriter( const char* fileName , unsigned int width , unsigned int height , unsigned int channels , ImageWriterParams params ) { _width = width , _height = height , _channels = channels , _tileWidth = params.tileWidth , _tileHeight = params.tileHeight; _tileColumns = ( _width + ( _tileWidth-1 ) ) / _tileWidth , _tileRows = ( _height + ( _tileHeight-1 ) ) / _tileHeight; _tileWriters = new ImageWriter*[ _tileColumns ]; _tileNames = new char*[ _tileColumns * _tileRows ]; if( params.tileParams ) _params = *params.tileParams; char tileName[1024]; char* tileHeader = FileNameParser::Header( fileName ); for( unsigned int r=0 ; r<_tileRows ; r++ ) for( unsigned int c=0 ; c<_tileColumns ; c++ ) { sprintf( tileName , "%s.%d.%d.%s" , tileHeader , c , r , params.tileExtension ); _tileNames[r*_tileColumns+c] = new char[ strlen(tileName)+1 ]; strcpy( _tileNames[r*_tileColumns+c] , tileName ); } delete[] tileHeader; FILE* fp = fopen( fileName , "w" ); if( !fp ) ERROR_OUT( "Failed to open file for writing: " , fileName ); fprintf( fp , "Columns: %d\n" , _tileColumns ); fprintf( fp , "Rows: %d\n" , _tileRows ); for( unsigned int i=0 ; i<_tileRows*_tileColumns ; i++ ) { char* localTileName = FileNameParser::Local( _tileNames[i] ); fprintf( fp , "%s\n" , localTileName ); delete[] localTileName; } fclose( fp ); _currentPixelRow = 0; } TiledImageWriter::~TiledImageWriter( void ) { delete[] _tileWriters; for( unsigned int i=0 ; i<_tileColumns*_tileRows ; i++ ) delete[] _tileNames[i]; delete[] _tileNames; } unsigned int TiledImageWriter::nextRow( const unsigned char* row ) { unsigned int r = _currentPixelRow / _tileHeight; if( ( _currentPixelRow % _tileHeight )==0 ) { for( unsigned int c=0 ; c<_tileColumns ; c++ ) _tileWriters[c] = ImageWriter::Get( _tileNames[ r * _tileColumns + c ] , std::min< unsigned int >( _tileWidth , _width - _tileWidth*c ) , std::min< unsigned int >( _tileHeight , _height - _tileHeight*r ) , _channels , _params ); } for( int c=0 ; c<(int)_tileColumns ; c++ ) _tileWriters[c]->nextRow( row + c * _tileWidth * _channels ); if( ( _currentPixelRow % _tileHeight )==( _tileHeight-1 ) || _currentPixelRow==(_height-1) ) for( unsigned int c=0 ; c<_tileColumns ; c++ ) delete _tileWriters[c]; return _currentPixelRow++; } #endif // SUPPORT_TILES #endif // IMAGE_INCLUDED
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "- <html xmlns="http: <head> <!-- template designed by Marco Von Ballmoos --> <title>Docs For Class Smarty_Variable</title> <link rel="stylesheet" href="../../media/stylesheet.css" /> <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/> </head> <body> <div class="page-body"> <h2 class="class-name">Class Smarty_Variable</h2> <a name="sec-description"></a> <div class="info-box"> <div class="info-box-title">Description</div> <div class="nav-bar"> <span class="disabled">Description</span> | <a href="#sec-var-summary">Vars</a> (<a href="#sec-vars">details</a>) | <a href="#sec-method-summary">Methods</a> (<a href="#sec-methods">details</a>) </div> <div class="info-box-body"> <p class="short-description">class for the Smarty variable object</p> <p class="description"><p>This class defines the Smarty variable object</p></p> <p class="notes"> Located in <a class="field" href="<API key>.php.html">/libs/sysplugins/<API key>.php</a> (line <span class="field">453</span>) </p> <pre></pre> </div> </div> <a name="sec-var-summary"></a> <div class="info-box"> <div class="info-box-title">Variable Summary</span></div> <div class="nav-bar"> <a href="#sec-description">Description</a> | <span class="disabled">Vars</span> (<a href="#sec-vars">details</a>) | <a href="#sec-method-summary">Methods</a> (<a href="#sec-methods">details</a>) </div> <div class="info-box-body"> <div class="var-summary"> <div class="var-title"> <span class="var-type">boolean</span> <a href="#$nocache" title="details" class="var-name">$nocache</a> </div> <div class="var-title"> <span class="var-type">int</span> <a href="#$scope" title="details" class="var-name">$scope</a> </div> <div class="var-title"> <span class="var-type">mixed</span> <a href="#$value" title="details" class="var-name">$value</a> </div> </div> </div> </div> <a name="sec-method-summary"></a> <div class="info-box"> <div class="info-box-title">Method Summary</span></div> <div class="nav-bar"> <a href="#sec-description">Description</a> | <a href="#sec-var-summary">Vars</a> (<a href="#sec-vars">details</a>) | <span class="disabled">Methods</span> (<a href="#sec-methods">details</a>) </div> <div class="info-box-body"> <div class="method-summary"> <div class="method-definition"> <span class="method-result">Smarty_Variable</span> <a href="#__construct" title="details" class="method-name">__construct</a> ([<span class="var-type">mixed</span>&nbsp;<span class="var-name">$value</span> = <span class="var-default">null</span>], [<span class="var-type">boolean</span>&nbsp;<span class="var-name">$nocache</span> = <span class="var-default">false</span>], [<span class="var-type">int</span>&nbsp;<span class="var-name">$scope</span> = <span class="var-default">Smarty::SCOPE_LOCAL</span>]) </div> <div class="method-definition"> <span class="method-result">string</span> <a href="#__toString" title="details" class="method-name">__toString</a> () </div> </div> </div> </div> <a name="sec-vars"></a> <div class="info-box"> <div class="info-box-title">Variables</div> <div class="nav-bar"> <a href="#sec-description">Description</a> | <a href="#sec-var-summary">Vars</a> (<span class="disabled">details</span>) | <a href="#sec-method-summary">Methods</a> (<a href="#sec-methods">details</a>) </div> <div class="info-box-body"> <a name="var$nocache" id="$nocache"></A> <div class="evenrow"> <div class="var-header"> <span class="var-title"> <span class="var-type">boolean</span> <span class="var-name">$nocache</span> = <span class="var-default"> false</span> (line <span class="line-number">466</span>) </span> </div> <p class="short-description">if true any output of this variable will be not cached</p> <ul class="tags"> <li><span class="field">access:</span> public</li> </ul> </div> <a name="var$scope" id="$scope"></A> <div class="oddrow"> <div class="var-header"> <span class="var-title"> <span class="var-type">int</span> <span class="var-name">$scope</span> = <span class="var-default"> Smarty::SCOPE_LOCAL</span> (line <span class="line-number">472</span>) </span> </div> <p class="short-description">the scope the variable will have (local,parent or root)</p> <ul class="tags"> <li><span class="field">access:</span> public</li> </ul> </div> <a name="var$value" id="$value"></A> <div class="evenrow"> <div class="var-header"> <span class="var-title"> <span class="var-type">mixed</span> <span class="var-name">$value</span> = <span class="var-default"> null</span> (line <span class="line-number">460</span>) </span> </div> <p class="short-description">template variable</p> <ul class="tags"> <li><span class="field">access:</span> public</li> </ul> </div> </div> </div> <a name="sec-methods"></a> <div class="info-box"> <div class="info-box-title">Methods</div> <div class="nav-bar"> <a href="#sec-description">Description</a> | <a href="#sec-var-summary">Vars</a> (<a href="#sec-vars">details</a>) <a href="#sec-method-summary">Methods</a> (<span class="disabled">details</span>) </div> <div class="info-box-body"> <A NAME='method_detail'></A> <a name="method__construct" id="__construct"></a> <div class="oddrow"> <div class="method-header"> <span class="method-title">Constructor __construct</span> (line <span class="line-number">481</span>) </div> <p class="short-description">create Smarty variable object</p> <ul class="tags"> <li><span class="field">access:</span> public</li> </ul> <div class="method-signature"> <span class="method-result">Smarty_Variable</span> <span class="method-name"> __construct </span> ([<span class="var-type">mixed</span>&nbsp;<span class="var-name">$value</span> = <span class="var-default">null</span>], [<span class="var-type">boolean</span>&nbsp;<span class="var-name">$nocache</span> = <span class="var-default">false</span>], [<span class="var-type">int</span>&nbsp;<span class="var-name">$scope</span> = <span class="var-default">Smarty::SCOPE_LOCAL</span>]) </div> <ul class="parameters"> <li> <span class="var-type">mixed</span> <span class="var-name">$value</span><span class="var-description">: the value to assign</span> </li> <li> <span class="var-type">boolean</span> <span class="var-name">$nocache</span><span class="var-description">: if true any output of this variable will be not cached</span> </li> <li> <span class="var-type">int</span> <span class="var-name">$scope</span><span class="var-description">: the scope the variable will have (local,parent or root)</span> </li> </ul> </div> <a name="method__toString" id="__toString"></a> <div class="evenrow"> <div class="method-header"> <span class="method-title">__toString</span> (line <span class="line-number">493</span>) </div> <p class="short-description">magic&gt;&gt; String conversion</p> <ul class="tags"> <li><span class="field">access:</span> public</li> </ul> <div class="method-signature"> <span class="method-result">string</span> <span class="method-name"> __toString </span> () </div> </div> </div> </div> <p class="notes" id="credit"> Documentation generated on Sat, 24 Sep 2011 20:23:53 +0200 by <a href="http: </p> </div></body> </html>
<!DOCTYPE HTML PUBLIC "- <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Sun Nov 03 15:35:44 CET 2013 --> <title>Timer.Task (libgdx API)</title> <meta name="date" content="2013-11-03"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><! if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Timer.Task (libgdx API)"; } </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <div class="topNav"><a name="navbar_top"> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Timer.Task.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> libgdx API <style> body, td, th { font-family:Helvetica, Tahoma, Arial, sans-serif; font-size:10pt } pre, code, tt { font-size:9pt; font-family:Lucida Console, Courier New, sans-serif } h1, h2, h3, .FrameTitleFont, .FrameHeadingFont, .TableHeadingColor font { font-size:105%; font-weight:bold } .TableHeadingColor { background:#EEEEFF; } a { text-decoration:none } a:hover { text-decoration:underline } a:link, a:visited { color:blue } table { border:0px } .TableRowColor td:first-child { border-left:1px solid black } .TableRowColor td { border:0px; border-bottom:1px solid black; border-right:1px solid black } hr { border:0px; border-bottom:1px solid #333366; } </style> </em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/badlogic/gdx/utils/Timer.html" title="class in com.badlogic.gdx.utils"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../com/badlogic/gdx/utils/TimeUtils.html" title="class in com.badlogic.gdx.utils"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/badlogic/gdx/utils/Timer.Task.html" target="_top">Frames</a></li> <li><a href="Timer.Task.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> </a></div> <div class="header"> <div class="subTitle">com.badlogic.gdx.utils</div> <h2 title="Class Timer.Task" class="title">Class Timer.Task</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>com.badlogic.gdx.utils.Timer.Task</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.lang.Runnable</dd> </dl> <dl> <dt>Enclosing class:</dt> <dd><a href="../../../../com/badlogic/gdx/utils/Timer.html" title="class in com.badlogic.gdx.utils">Timer</a></dd> </dl> <hr> <br> <pre>public abstract static class <span class="strong">Timer.Task</span> extends java.lang.Object implements java.lang.Runnable</pre> <div class="block">Runnable with a cancel method.</div> <dl><dt><span class="strong">Author:</span></dt> <dd>Nathan Sweet</dd> <dt><span class="strong">See Also:</span></dt><dd><a href="../../../../com/badlogic/gdx/utils/Timer.html" title="class in com.badlogic.gdx.utils"><code>Timer</code></a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../com/badlogic/gdx/utils/Timer.Task.html#Timer.Task()">Timer.Task</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_summary"> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../com/badlogic/gdx/utils/Timer.Task.html#cancel()">cancel</a></strong>()</code> <div class="block">Cancels the task.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><strong><a href="../../../../com/badlogic/gdx/utils/Timer.Task.html#isScheduled()">isScheduled</a></strong>()</code> <div class="block">Returns true if this task is scheduled to be executed in the future by a timer.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>abstract void</code></td> <td class="colLast"><code><strong><a href="../../../../com/badlogic/gdx/utils/Timer.Task.html#run()">run</a></strong>()</code> <div class="block">If this is the last time the task will be ran or the task is first cancelled, it may be scheduled again in this method.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="<API key>.lang.Object"> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> </a> <h3>Constructor Detail</h3> <a name="Timer.Task()"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>Timer.Task</h4> <pre>public&nbsp;Timer.Task()</pre> </li> </ul> </li> </ul> <ul class="blockList"> <li class="blockList"><a name="method_detail"> </a> <h3>Method Detail</h3> <a name="run()"> </a> <ul class="blockList"> <li class="blockList"> <h4>run</h4> <pre>public abstract&nbsp;void&nbsp;run()</pre> <div class="block">If this is the last time the task will be ran or the task is first cancelled, it may be scheduled again in this method.</div> <dl> <dt><strong>Specified by:</strong></dt> <dd><code>run</code>&nbsp;in interface&nbsp;<code>java.lang.Runnable</code></dd> </dl> </li> </ul> <a name="cancel()"> </a> <ul class="blockList"> <li class="blockList"> <h4>cancel</h4> <pre>public&nbsp;void&nbsp;cancel()</pre> <div class="block">Cancels the task. It will not be executed until it is scheduled again. This method can be called at any time.</div> </li> </ul> <a name="isScheduled()"> </a> <ul class="blockListLast"> <li class="blockList"> <h4>isScheduled</h4> <pre>public&nbsp;boolean&nbsp;isScheduled()</pre> <div class="block">Returns true if this task is scheduled to be executed in the future by a timer.</div> </li> </ul> </li> </ul> </li> </ul> </div> </div> <div class="bottomNav"><a name="navbar_bottom"> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>"> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/Timer.Task.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em>libgdx API</em></div> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../com/badlogic/gdx/utils/Timer.html" title="class in com.badlogic.gdx.utils"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../com/badlogic/gdx/utils/TimeUtils.html" title="class in com.badlogic.gdx.utils"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?com/badlogic/gdx/utils/Timer.Task.html" target="_top">Frames</a></li> <li><a href="Timer.Task.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="<API key>"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><! allClassesLink = document.getElementById("<API key>"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> </a></div> <p class="legalCopy"><small> <div style="font-size:9pt"><i> Copyright &copy; 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com) </i></div> </small></p> </body> </html>
<?php include "../db_config.php"; include "Carshop.php"; $shop = new Carshop($db); $shop->main();
package com.daviancorp.android.ui.list; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.Menu; import com.daviancorp.android.mh4udatabase.R; import com.daviancorp.android.ui.general.GenericActivity; import com.daviancorp.android.ui.list.adapter.MenuSection; public class <API key> extends GenericActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.locations); // Tag as top level activity super.setAsTopLevel(); } @Override protected MenuSection getSelectedSection() { return MenuSection.LOCATIONS; } @Override protected Fragment createFragment() { super.detail = new <API key>(); return super.detail; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); return true; } }
using System; using System.Data.Entity; namespace Todo.Models { // DEMONSTRATION/DEVELOPMENT ONLY public class TodosDbInitializer: <API key><TodosContext> // re-creates every time the server starts //<API key><TodosContext> { protected override void Seed(TodosContext context) { ResetDatabase(context); } public static void ResetDatabase(TodosContext context) { _baseCreatedAtDate = new DateTime(2012, 8, 22, 9, 0, 0); var todos = new[] { // Description, IsDone, IsArchived CreateTodo("Food", true, true), CreateTodo("Water", true, true), CreateTodo("Shelter", true, true), CreateTodo("Bread", false, false), CreateTodo("Cheese", true, false), CreateTodo("Wine", false, false) }; Array.ForEach(todos, t => context.Todos.Add(t)); context.SaveChanges(); // Save 'em } private static TodoItem CreateTodo( string description, bool isDone, bool isArchived) { _baseCreatedAtDate = _baseCreatedAtDate.AddMinutes(1); return new TodoItem { CreatedAt = _baseCreatedAtDate, Description = description, IsDone = isDone, IsArchived = isArchived }; } private static DateTime _baseCreatedAtDate; public static void PurgeDatabase(TodosContext context) { var todos = context.Todos; foreach (var todoItem in todos) { todos.Remove(todoItem); } context.SaveChanges(); } } }
$: << "../.." first = "profile/" second = "some_file" require(first+second)
<?php namespace Spork\Test\Deferred; use Spork\Deferred\Deferred; class DeferredTest extends \<API key> { private $defer; protected function setUp() { $this->defer = new Deferred(); } protected function tearDown() { unset($this->defer); } /** * @dataProvider getMethodAndKey */ public function testCallbackOrder($method, $expected) { $log = array(); $this->defer->always(function() use(& $log) { $log[] = 'always'; $log[] = func_get_args(); })->done(function() use(& $log) { $log[] = 'done'; $log[] = func_get_args(); })->fail(function() use(& $log) { $log[] = 'fail'; $log[] = func_get_args(); }); $this->defer->$method(1, 2, 3); $this->assertEquals(array( 'always', array(1, 2, 3), $expected, array(1, 2, 3), ), $log); } /** * @dataProvider getMethodAndKey */ public function testThen($method, $expected) { $log = array(); $this->defer->then(function() use(& $log) { $log[] = 'done'; }, function() use(& $log) { $log[] = 'fail'; }); $this->defer->$method(); $this->assertEquals(array($expected), $log); } /** * @dataProvider getMethod */ public function testMultipleResolve($method) { $log = array(); $this->defer->always(function() use(& $log) { $log[] = 'always'; }); $this->defer->$method(); $this->defer->$method(); $this->assertEquals(array('always'), $log); } /** * @dataProvider getMethodAndInvalid */ public function testInvalidResolve($method, $invalid) { $this-><API key>('LogicException', 'that has already been'); $this->defer->$method(); $this->defer->$invalid(); } /** * @dataProvider getMethodAndQueue */ public function testAlreadyResolved($resolve, $queue, $expect = true) { // resolve the object $this->defer->$resolve(); $log = array(); $this->defer->$queue(function() use(& $log, $queue) { $log[] = $queue; }); $this->assertEquals($expect ? array($queue) : array(), $log); } /** * @dataProvider <API key> */ public function testInvalidCallback($method, $invalid) { $this-><API key>('Spork\Exception\<API key>', 'callable'); $this->defer->$method($invalid); } // providers public function getMethodAndKey() { return array( array('resolve', 'done'), array('reject', 'fail'), ); } public function getMethodAndInvalid() { return array( array('resolve', 'reject'), array('reject', 'resolve'), ); } public function getMethodAndQueue() { return array( array('resolve', 'always'), array('resolve', 'done'), array('resolve', 'fail', false), array('reject', 'always'), array('reject', 'done', false), array('reject', 'fail'), ); } public function <API key>() { return array( array('always', 'foo!'), array('always', array('foo!')), array('done', 'foo!'), array('done', array('foo!')), array('fail', 'foo!'), array('fail', array('foo!')), ); } public function getMethod() { return array( array('resolve'), array('reject'), ); } }
require "spec_helper" module Challah describe Authorization do describe "#user" do let(:user) { create(:user) } let(:authorization) { Authorization.set(user_id: user.id, provider: :test) } it "references an authorization record's user" do expect(authorization.user).to eq(user) end end describe ".challah_user" do it "includes the Authorizeable module" do Authorization.<API key> expect(Authorization.included_modules).to include(Challah::Authorizeable) end end describe ".del" do it "removes a record" do Authorization.set(user_id: 1, provider: :test, token: "test123") expect { Authorization.del(user_id: 1, provider: :test) }.to change { Authorization.count }.by(-1) end end describe ".get" do let(:user) { create(:user) } let(:authorization) { Authorization.set(user_id: user.id, provider: :test) } before { authorization } it "loads a user provider record" do expect(Authorization.get(user_id: user.id, provider: :test)).to eq(authorization) end end describe ".hashable_attributes" do it "has a list of attributes that are hashable" do expected_columns = %w( id uid token expires_at ).sort expect(Authorization.hashable_attributes.sort).to eq(expected_columns) end end describe ".set" do it "adds a record" do expect { Authorization.set(user_id: 1, provider: :test, token: "test123") }.to change { Authorization.count }.by(1) end it "removes existing provider records" do Authorization.set(user_id: 1, provider: :test, <API key>) expect { Authorization.set(user_id: 1, provider: :test, token: "test123") }.to_not change { Authorization.count } end end describe ".user_model" do it "references the user model" do expect(Authorization.user_model).to eq(User) expect(Authorization.users_table_name).to eq("users") end end describe ".users_table_name" do it "references the users table" do expect(Authorization.users_table_name).to eq("users") end end end end
""" A mechanize browser that redirects specified HTTP connections to a WSGI object. """ from httplib import HTTP from mechanize import Browser as MechanizeBrowser from wsgi_intercept.urllib2_intercept import install_opener, uninstall_opener try: from mechanize import HTTPHandler except ImportError: # pre mechanize 0.1.0 it was a separate package # (this will break if it is combined with a newer mechanize) from ClientCookie import HTTPHandler import sys, os.path from wsgi_intercept.urllib2_intercept import WSGI_HTTPHandler, WSGI_HTTPSHandler class Browser(MechanizeBrowser): """ A version of the mechanize browser class that installs the WSGI intercept handler """ handler_classes = MechanizeBrowser.handler_classes.copy() handler_classes['http'] = WSGI_HTTPHandler handler_classes['https'] = WSGI_HTTPSHandler def __init__(self, *args, **kwargs): # install WSGI intercept handler. install(self) MechanizeBrowser.__init__(self, *args, **kwargs) def install(browser): install_opener()
// Use of this source code is governed by a BSD-style // +build arm64,linux package unix //sys EpollWait(epfd int, events []EpollEvent, msec int) (n int, err error) = SYS_EPOLL_PWAIT //sys Fchown(fd int, uid int, gid int) (err error) //sys Fstat(fd int, stat *Stat_t) (err error) //sys Fstatat(fd int, path string, stat *Stat_t, flags int) (err error) //sys Fstatfs(fd int, buf *Statfs_t) (err error) //sys Ftruncate(fd int, length int64) (err error) //sysnb Getegid() (egid int) //sysnb Geteuid() (euid int) //sysnb Getgid() (gid int) //sysnb Getrlimit(resource int, rlim *Rlimit) (err error) //sysnb Getuid() (uid int) //sys Listen(s int, n int) (err error) //sys Pread(fd int, p []byte, offset int64) (n int, err error) = SYS_PREAD64 //sys Pwrite(fd int, p []byte, offset int64) (n int, err error) = SYS_PWRITE64 //sys Seek(fd int, offset int64, whence int) (off int64, err error) = SYS_LSEEK func Select(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timeval) (n int, err error) { ts := Timespec{Sec: timeout.Sec, Nsec: timeout.Usec * 1000} return Pselect(nfd, r, w, e, &ts, nil) } //sys sendfile(outfd int, infd int, offset *int64, count int) (written int, err error) //sys Setfsgid(gid int) (err error) //sys Setfsuid(uid int) (err error) //sysnb Setregid(rgid int, egid int) (err error) //sysnb Setresgid(rgid int, egid int, sgid int) (err error) //sysnb Setresuid(ruid int, euid int, suid int) (err error) //sysnb Setrlimit(resource int, rlim *Rlimit) (err error) //sysnb Setreuid(ruid int, euid int) (err error) //sys Shutdown(fd int, how int) (err error) //sys Splice(rfd int, roff *int64, wfd int, woff *int64, len int, flags int) (n int64, err error) func Stat(path string, stat *Stat_t) (err error) { return Fstatat(AT_FDCWD, path, stat, 0) } func Lchown(path string, uid int, gid int) (err error) { return Fchownat(AT_FDCWD, path, uid, gid, AT_SYMLINK_NOFOLLOW) } func Lstat(path string, stat *Stat_t) (err error) { return Fstatat(AT_FDCWD, path, stat, AT_SYMLINK_NOFOLLOW) } //sys Statfs(path string, buf *Statfs_t) (err error) //sys SyncFileRange(fd int, off int64, n int64, flags int) (err error) //sys Truncate(path string, length int64) (err error) //sys accept(s int, rsa *RawSockaddrAny, addrlen *_Socklen) (fd int, err error) //sys accept4(s int, rsa *RawSockaddrAny, addrlen *_Socklen, flags int) (fd int, err error) //sys bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sys connect(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) //sysnb getgroups(n int, list *_Gid_t) (nn int, err error) //sysnb setgroups(n int, list *_Gid_t) (err error) //sys getsockopt(s int, level int, name int, val unsafe.Pointer, vallen *_Socklen) (err error) //sys setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) //sysnb socket(domain int, typ int, proto int) (fd int, err error) //sysnb socketpair(domain int, typ int, proto int, fd *[2]int32) (err error) //sysnb getpeername(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sysnb getsockname(fd int, rsa *RawSockaddrAny, addrlen *_Socklen) (err error) //sys recvfrom(fd int, p []byte, flags int, from *RawSockaddrAny, fromlen *_Socklen) (n int, err error) //sys sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen _Socklen) (err error) //sys recvmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys sendmsg(s int, msg *Msghdr, flags int) (n int, err error) //sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error) //sysnb Gettimeofday(tv *Timeval) (err error) func NsecToTimespec(nsec int64) (ts Timespec) { ts.Sec = nsec / 1e9 ts.Nsec = nsec % 1e9 return } func NsecToTimeval(nsec int64) (tv Timeval) { nsec += 999 // round up to microsecond tv.Sec = nsec / 1e9 tv.Usec = nsec % 1e9 / 1e3 return } func Time(t *Time_t) (Time_t, error) { var tv Timeval err := Gettimeofday(&tv) if err != nil { return 0, err } if t != nil { *t = Time_t(tv.Sec) } return Time_t(tv.Sec), nil } func Utime(path string, buf *Utimbuf) error { tv := []Timeval{ {Sec: buf.Actime}, {Sec: buf.Modtime}, } return Utimes(path, tv) } func Pipe(p []int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, 0) p[0] = int(pp[0]) p[1] = int(pp[1]) return } //sysnb pipe2(p *[2]_C_int, flags int) (err error) func Pipe2(p []int, flags int) (err error) { if len(p) != 2 { return EINVAL } var pp [2]_C_int err = pipe2(&pp, flags) p[0] = int(pp[0]) p[1] = int(pp[1]) return } func (r *PtraceRegs) PC() uint64 { return r.Pc } func (r *PtraceRegs) SetPC(pc uint64) { r.Pc = pc } func (iov *Iovec) SetLen(length int) { iov.Len = uint64(length) } func (msghdr *Msghdr) SetControllen(length int) { msghdr.Controllen = uint64(length) } func (cmsg *Cmsghdr) SetLen(length int) { cmsg.Len = uint64(length) } func InotifyInit() (fd int, err error) { return InotifyInit1(0) } func Dup2(oldfd int, newfd int) (err error) { return Dup3(oldfd, newfd, 0) } func Pause() (err error) { _, _, e1 := Syscall6(SYS_PPOLL, 0, 0, 0, 0, 0, 0) if e1 != 0 { err = errnoErr(e1) } return } // TODO(dfc): constants that should be in zsysnum_linux_arm64.go, remove // these when the deprecated syscalls that the syscall package relies on // are removed. const ( SYS_GETPGRP = 1060 SYS_UTIMES = 1037 SYS_FUTIMESAT = 1066 SYS_PAUSE = 1061 SYS_USTAT = 1070 SYS_UTIME = 1063 SYS_LCHOWN = 1032 SYS_TIME = 1062 SYS_EPOLL_CREATE = 1042 SYS_EPOLL_WAIT = 1069 ) func Poll(fds []PollFd, timeout int) (n int, err error) { var ts *Timespec if timeout >= 0 { ts = new(Timespec) *ts = NsecToTimespec(int64(timeout) * 1e6) } if len(fds) == 0 { return ppoll(nil, 0, ts, nil) } return ppoll(&fds[0], len(fds), ts, nil) }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1"> <!-- Use Chrome Frame in IE --> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"> <meta name="description" content="A simple CZML example showing four satellites in orbit around the Earth, and some ground objects."> <meta name="<API key>" content="Showcases, DataSources"> <title>Cesium Demo</title> <script type="text/javascript" src="../Sandcastle-header.js"></script> <script type="text/javascript" src="../../../ThirdParty/requirejs-2.1.9/require.js"></script> <script type="text/javascript"> require.config({ baseUrl : '../../../Source', waitSeconds : 60 }); </script> </head> <body class="sandcastle-loading" <API key>="bucket-requirejs.html"> <style> @import url(../templates/bucket.css); </style> <div id="cesiumContainer" class="fullSize"></div> <div id="loadingOverlay"><h1>Loading...</h1></div> <div id="toolbar"></div> <script id="<API key>"> function startup(Cesium) { "use strict"; //Sandcastle_Begin var gallery = '../../SampleData/'; var viewer = new Cesium.Viewer('cesiumContainer'); Sandcastle.<API key>('Satellites', function() { var czmlDataSource = new Cesium.CzmlDataSource(); czmlDataSource.loadUrl(gallery + 'simple.czml'); viewer.dataSources.add(czmlDataSource); }); Sandcastle.addToolbarButton('Vehicle', function() { var czmlDataSource = new Cesium.CzmlDataSource(); czmlDataSource.loadUrl(gallery + 'Vehicle.czml'); viewer.dataSources.add(czmlDataSource); }); Sandcastle.reset = function() { viewer.dataSources.removeAll(); viewer.homeButton.viewModel.command(); }; //Sandcastle_End Sandcastle.finishedLoading(); } if (typeof Cesium !== "undefined") { startup(Cesium); } else if (typeof require === "function") { require(["Cesium"], startup); } </script> </body> </html>
from __future__ import absolute_import, print_function, division from io import BytesIO import textwrap from mock import Mock from netlib.exceptions import HttpException, HttpSyntaxException, HttpReadDisconnect, TcpDisconnect from netlib.http import Headers from netlib.http.http1.read import ( read_request, read_response, read_request_head, read_response_head, read_body, connection_close, <API key>, _get_first_line, _read_request_line, <API key>, _read_response_line, _check_http_version, _read_headers, _read_chunked ) from netlib.tutils import treq, tresp, raises def test_read_request(): rfile = BytesIO(b"GET / HTTP/1.1\r\n\r\nskip") r = read_request(rfile) assert r.method == "GET" assert r.content == b"" assert r.timestamp_end assert rfile.read() == b"skip" def <API key>(): rfile = BytesIO( b"GET / HTTP/1.1\r\n" b"Content-Length: 4\r\n" b"\r\n" b"skip" ) rfile.reset_timestamps = Mock() rfile.<API key> = 42 r = read_request_head(rfile) assert r.method == "GET" assert r.headers["Content-Length"] == "4" assert r.content is None assert rfile.reset_timestamps.called assert r.timestamp_start == 42 assert rfile.read() == b"skip" def test_read_response(): req = treq() rfile = BytesIO(b"HTTP/1.1 418 I'm a teapot\r\n\r\nbody") r = read_response(rfile, req) assert r.status_code == 418 assert r.content == b"body" assert r.timestamp_end def <API key>(): rfile = BytesIO( b"HTTP/1.1 418 I'm a teapot\r\n" b"Content-Length: 4\r\n" b"\r\n" b"skip" ) rfile.reset_timestamps = Mock() rfile.<API key> = 42 r = read_response_head(rfile) assert r.status_code == 418 assert r.headers["Content-Length"] == "4" assert r.content is None assert rfile.reset_timestamps.called assert r.timestamp_start == 42 assert rfile.read() == b"skip" class TestReadBody(object): def test_chunked(self): rfile = BytesIO(b"3\r\nfoo\r\n0\r\n\r\nbar") body = b"".join(read_body(rfile, None)) assert body == b"foo" assert rfile.read() == b"bar" def test_known_size(self): rfile = BytesIO(b"foobar") body = b"".join(read_body(rfile, 3)) assert body == b"foo" assert rfile.read() == b"bar" def <API key>(self): rfile = BytesIO(b"foobar") with raises(HttpException): b"".join(read_body(rfile, 3, 2)) def <API key>(self): rfile = BytesIO(b"foo") with raises(HttpException): b"".join(read_body(rfile, 6)) def test_unknown_size(self): rfile = BytesIO(b"foobar") body = b"".join(read_body(rfile, -1)) assert body == b"foobar" def <API key>(self): rfile = BytesIO(b"foobar") with raises(HttpException): b"".join(read_body(rfile, -1, 3)) def test_max_chunk_size(self): rfile = BytesIO(b"123456") assert list(read_body(rfile, -1, max_chunk_size=None)) == [b"123456"] rfile = BytesIO(b"123456") assert list(read_body(rfile, -1, max_chunk_size=1)) == [b"1", b"2", b"3", b"4", b"5", b"6"] def <API key>(): headers = Headers() assert connection_close(b"HTTP/1.0", headers) assert not connection_close(b"HTTP/1.1", headers) headers["connection"] = "keep-alive" assert not connection_close(b"HTTP/1.1", headers) headers["connection"] = "close" assert connection_close(b"HTTP/1.1", headers) headers["connection"] = "foobar" assert connection_close(b"HTTP/1.0", headers) assert not connection_close(b"HTTP/1.1", headers) def <API key>(): # Expect: 100-continue assert <API key>( treq(headers=Headers(expect="100-continue", content_length="42")) ) == 0 assert <API key>( treq(method=b"HEAD"), tresp(headers=Headers(content_length="42")) ) == 0 assert <API key>( treq(method=b"CONNECT"), tresp() ) == 0 for code in (100, 204, 304): assert <API key>( treq(), tresp(status_code=code) ) == 0 # chunked assert <API key>( treq(headers=Headers(transfer_encoding="chunked")), ) is None # explicit length for val in (b"foo", b"-7"): with raises(HttpSyntaxException): <API key>( treq(headers=Headers(content_length=val)) ) assert <API key>( treq(headers=Headers(content_length="42")) ) == 42 # no length assert <API key>( treq(headers=Headers()) ) == 0 assert <API key>( treq(headers=Headers()), tresp(headers=Headers()) ) == -1 def test_get_first_line(): rfile = BytesIO(b"foo\r\nbar") assert _get_first_line(rfile) == b"foo" rfile = BytesIO(b"\r\nfoo\r\nbar") assert _get_first_line(rfile) == b"foo" with raises(HttpReadDisconnect): rfile = BytesIO(b"") _get_first_line(rfile) with raises(HttpReadDisconnect): rfile = Mock() rfile.readline.side_effect = TcpDisconnect _get_first_line(rfile) def <API key>(): def t(b): return _read_request_line(BytesIO(b)) assert (t(b"GET / HTTP/1.1") == ("relative", b"GET", None, None, None, b"/", b"HTTP/1.1")) assert (t(b"OPTIONS * HTTP/1.1") == ("relative", b"OPTIONS", None, None, None, b"*", b"HTTP/1.1")) assert (t(b"CONNECT foo:42 HTTP/1.1") == ("authority", b"CONNECT", None, b"foo", 42, None, b"HTTP/1.1")) assert (t(b"GET http://foo:42/bar HTTP/1.1") == ("absolute", b"GET", b"http", b"foo", 42, b"/bar", b"HTTP/1.1")) with raises(HttpSyntaxException): t(b"GET / WTF/1.1") with raises(HttpSyntaxException): t(b"this is not http") with raises(HttpReadDisconnect): t(b"") def <API key>(): assert <API key>(b"foo:42") == (b"foo", 42) with raises(HttpSyntaxException): <API key>(b"foo") with raises(HttpSyntaxException): <API key>(b"foo:bar") with raises(HttpSyntaxException): <API key>(b"foo:99999999") with raises(HttpSyntaxException): <API key>(b"f\x00oo:80") def <API key>(): def t(b): return _read_response_line(BytesIO(b)) assert t(b"HTTP/1.1 200 OK") == (b"HTTP/1.1", 200, b"OK") assert t(b"HTTP/1.1 200") == (b"HTTP/1.1", 200, b"") assert t(b"HTTP/1.1 200 Non-Autoris\xc3\xa9") == (b"HTTP/1.1", 200, b"Non-Autoris\xc3\xa9") with raises(HttpSyntaxException): assert t(b"HTTP/1.1") with raises(HttpSyntaxException): t(b"HTTP/1.1 OK OK") with raises(HttpSyntaxException): t(b"WTF/1.1 200 OK") with raises(HttpReadDisconnect): t(b"") def <API key>(): _check_http_version(b"HTTP/0.9") _check_http_version(b"HTTP/1.0") _check_http_version(b"HTTP/1.1") _check_http_version(b"HTTP/2.0") with raises(HttpSyntaxException): _check_http_version(b"WTF/1.0") with raises(HttpSyntaxException): _check_http_version(b"HTTP/1.10") with raises(HttpSyntaxException): _check_http_version(b"HTTP/1.b") class TestReadHeaders(object): @staticmethod def _read(data): return _read_headers(BytesIO(data)) def test_read_simple(self): data = ( b"Header: one\r\n" b"Header2: two\r\n" b"\r\n" ) headers = self._read(data) assert headers.fields == [[b"Header", b"one"], [b"Header2", b"two"]] def test_read_multi(self): data = ( b"Header: one\r\n" b"Header: two\r\n" b"\r\n" ) headers = self._read(data) assert headers.fields == [[b"Header", b"one"], [b"Header", b"two"]] def test_read_continued(self): data = ( b"Header: one\r\n" b"\ttwo\r\n" b"Header2: three\r\n" b"\r\n" ) headers = self._read(data) assert headers.fields == [[b"Header", b"one\r\n two"], [b"Header2", b"three"]] def <API key>(self): data = b"\tfoo: bar\r\n" with raises(HttpSyntaxException): self._read(data) def test_read_err(self): data = b"foo" with raises(HttpSyntaxException): self._read(data) def <API key>(self): data = b":foo" with raises(HttpSyntaxException): self._read(data) def <API key>(self): data = b"bar:" headers = self._read(data) assert headers.fields == [[b"bar", b""]] def test_read_chunked(): req = treq(content=None) req.headers["Transfer-Encoding"] = "chunked" data = b"1\r\na\r\n0\r\n" with raises(HttpSyntaxException): b"".join(_read_chunked(BytesIO(data))) data = b"1\r\na\r\n0\r\n\r\n" assert b"".join(_read_chunked(BytesIO(data))) == b"a" data = b"\r\n\r\n1\r\na\r\n1\r\nb\r\n0\r\n\r\n" assert b"".join(_read_chunked(BytesIO(data))) == b"ab" data = b"\r\n" with raises("closed prematurely"): b"".join(_read_chunked(BytesIO(data))) data = b"1\r\nfoo" with raises("malformed chunked body"): b"".join(_read_chunked(BytesIO(data))) data = b"foo\r\nfoo" with raises(HttpSyntaxException): b"".join(_read_chunked(BytesIO(data))) data = b"5\r\naaaaa\r\n0\r\n\r\n" with raises("too large"): b"".join(_read_chunked(BytesIO(data), limit=2))
import { insertMarkdownText } from '~/lib/utils/text_markdown'; describe('init markdown', () => { let textArea; beforeAll(() => { textArea = document.createElement('textarea'); document.querySelector('body').appendChild(textArea); textArea.focus(); }); afterAll(() => { textArea.parentNode.removeChild(textArea); }); describe('textArea', () => { describe('without selection', () => { it('inserts the tag on an empty line', () => { const initialValue = ''; textArea.value = initialValue; textArea.selectionStart = 0; textArea.selectionEnd = 0; insertMarkdownText({ textArea, text: textArea.value, tag: '*', blockTag: null, selected: '', wrap: false, }); expect(textArea.value).toEqual(`${initialValue}* `); }); it('inserts the tag on a new line if the current one is not empty', () => { const initialValue = 'some text'; textArea.value = initialValue; textArea.setSelectionRange(initialValue.length, initialValue.length); insertMarkdownText({ textArea, text: textArea.value, tag: '*', blockTag: null, selected: '', wrap: false, }); expect(textArea.value).toEqual(`${initialValue}\n* `); }); it('inserts the tag on the same line if the current line only contains spaces', () => { const initialValue = ' '; textArea.value = initialValue; textArea.setSelectionRange(initialValue.length, initialValue.length); insertMarkdownText({ textArea, text: textArea.value, tag: '*', blockTag: null, selected: '', wrap: false, }); expect(textArea.value).toEqual(`${initialValue}* `); }); it('inserts the tag on the same line if the current line only contains tabs', () => { const initialValue = '\t\t\t'; textArea.value = initialValue; textArea.setSelectionRange(initialValue.length, initialValue.length); insertMarkdownText({ textArea, text: textArea.value, tag: '*', blockTag: null, selected: '', wrap: false, }); expect(textArea.value).toEqual(`${initialValue}* `); }); it('places the cursor inside the tags', () => { const start = 'lorem '; const end = ' ipsum'; const tag = '*'; textArea.value = `${start}${end}`; textArea.setSelectionRange(start.length, start.length); insertMarkdownText({ textArea, text: textArea.value, tag, blockTag: null, selected: '', wrap: true, }); expect(textArea.value).toEqual(`${start}**${end}`); // cursor placement should be between tags expect(textArea.selectionStart).toBe(start.length + tag.length); }); }); describe('with selection', () => { const text = 'initial selected value'; const selected = 'selected'; beforeEach(() => { textArea.value = text; const selectedIndex = text.indexOf(selected); textArea.setSelectionRange(selectedIndex, selectedIndex + selected.length); }); it('applies the tag to the selected value', () => { const selectedIndex = text.indexOf(selected); const tag = '*'; insertMarkdownText({ textArea, text: textArea.value, tag, blockTag: null, selected, wrap: true, }); expect(textArea.value).toEqual(text.replace(selected, `*${selected}*`)); // cursor placement should be after selection + 2 tag lengths expect(textArea.selectionStart).toBe(selectedIndex + selected.length + 2 * tag.length); }); it('replaces the placeholder in the tag', () => { insertMarkdownText({ textArea, text: textArea.value, tag: '[{text}](url)', blockTag: null, selected, wrap: false, }); expect(textArea.value).toEqual(text.replace(selected, `[${selected}](url)`)); }); describe('and text to be selected', () => { const tag = '[{text}](url)'; const select = 'url'; it('selects the text', () => { insertMarkdownText({ textArea, text: textArea.value, tag, blockTag: null, selected, wrap: false, select, }); const expectedText = text.replace(selected, `[${selected}](url)`); expect(textArea.value).toEqual(expectedText); expect(textArea.selectionStart).toEqual(expectedText.indexOf(select)); expect(textArea.selectionEnd).toEqual(expectedText.indexOf(select) + select.length); }); it('selects the right text when multiple tags are present', () => { const initialValue = `${tag} ${tag} ${selected}`; textArea.value = initialValue; const selectedIndex = initialValue.indexOf(selected); textArea.setSelectionRange(selectedIndex, selectedIndex + selected.length); insertMarkdownText({ textArea, text: textArea.value, tag, blockTag: null, selected, wrap: false, select, }); const expectedText = initialValue.replace(selected, `[${selected}](url)`); expect(textArea.value).toEqual(expectedText); expect(textArea.selectionStart).toEqual(expectedText.lastIndexOf(select)); expect(textArea.selectionEnd).toEqual(expectedText.lastIndexOf(select) + select.length); }); it('should support selected urls', () => { const expectedUrl = 'http: const <API key> = 'text'; const expectedText = `text [${<API key>}](${expectedUrl}) text`; const initialValue = `text ${expectedUrl} text`; textArea.value = initialValue; const selectedIndex = initialValue.indexOf(expectedUrl); textArea.setSelectionRange(selectedIndex, selectedIndex + expectedUrl.length); insertMarkdownText({ textArea, text: textArea.value, tag, blockTag: null, selected: expectedUrl, wrap: false, select, }); expect(textArea.value).toEqual(expectedText); expect(textArea.selectionStart).toEqual(expectedText.indexOf(<API key>, 1)); expect(textArea.selectionEnd).toEqual( expectedText.indexOf(<API key>, 1) + <API key>.length, ); }); }); }); }); describe('Ace Editor', () => { let editor; beforeEach(() => { editor = { getSelectionRange: () => ({ start: 0, end: 0, }), getValue: () => 'this is text \n in two lines', insert: () => {}, navigateLeft: () => {}, }; }); it('uses ace editor insert text when editor is passed in', () => { spyOn(editor, 'insert'); insertMarkdownText({ text: editor.getValue, tag: '*', blockTag: null, selected: '', wrap: false, editor, }); expect(editor.insert).toHaveBeenCalled(); }); it('adds block tags on line above and below selection', () => { spyOn(editor, 'insert'); const selected = 'this text \n is multiple \n lines'; const text = `before \n ${selected} \n after`; insertMarkdownText({ text, tag: '', blockTag: '***', selected, wrap: true, editor, }); expect(editor.insert).<API key>(`***\n${selected}\n***`); }); it('uses ace editor to navigate back tag length when nothing is selected', () => { spyOn(editor, 'navigateLeft'); insertMarkdownText({ text: editor.getValue, tag: '*', blockTag: null, selected: '', wrap: true, editor, }); expect(editor.navigateLeft).<API key>(1); }); it('ace editor does not navigate back when there is selected text', () => { spyOn(editor, 'navigateLeft'); insertMarkdownText({ text: editor.getValue, tag: '*', blockTag: null, selected: 'foobar', wrap: true, editor, }); expect(editor.navigateLeft).not.toHaveBeenCalled(); }); }); });
# of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # copies or substantial portions of the Software. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. # 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. from netforce.model import Model, fields class BomLine(Model): _name = "bom.line" _fields = { "bom_id": fields.Many2One("bom", "BoM", required=True, on_delete="cascade"), "product_id": fields.Many2One("product", "Product", required=True), "qty": fields.Decimal("Qty", required=True, scale=6), "uom_id": fields.Many2One("uom", "UoM", required=True), "location_id": fields.Many2One("stock.location", "RM Warehouse"), "container": fields.Selection([["sale", "From Sales Order"]], "RM Container"), "lot": fields.Selection([["production", "From Production Order"]], "RM Lot"), "issue_method": fields.Selection([["manual", "Manual"], ["backflush", "Backflush"]], "Issue Method"), "qty2": fields.Decimal("Qty2", scale=6), "notes": fields.Text("Notes"), } BomLine.register()
<!DOCTYPE html> <html xmlns="http: <head> <title>Left Frame</title> </head> <body> <h1>Examples</h1> <ul> <li><a href="../1. Form-input-fields.html" target="mainFrame">Form Example</a></li> <li><a href="../2. Sliders-spinboxes.html" target="mainFrame">Slider Example</a></li> <li><a href="../3. Forms-validation.html" target="mainFrame">Validation Example</a></li> </ul> <h1>Search Engines</h1> <ul> <li><a href="http: <li><a href="http: <li><a href="http: </ul> </body> </html>
package lastfm import "encoding/xml" //library.addAlbum (emptry) //library.addArtist (empty) //library.addTrack (empty) //library.getAlbums type LibraryGetAlbums struct { XMLName xml.Name `xml:"albums"` User string `xml:"user,attr"` Total int `xml:"total,attr"` Page int `xml:"page,attr"` PerPage int `xml:"perPage,attr"` TotalPages int `xml:"totalPages,attr"` Albums []struct { Name string `xml:"name"` PlayCount string `xml:"playcount"` TagCount string `xml:"tagcount"` Mbid string `xml:"mbid"` Url string `xml:"url"` Artist struct { Name string `xml:"name"` Mbid string `xml:"mbid"` Url string `xml:"url"` } `xml:"artist"` Images []struct { Size string `xml:"size,attr"` Url string `xml:",chardata"` } `xml:"image"` } `xml:"album"` } //library.getArtists type LibraryGetArtists struct { XMLName xml.Name `xml:"artists"` User string `xml:"user,attr"` Total int `xml:"total,attr"` Page int `xml:"page,attr"` PerPage int `xml:"perPage,attr"` TotalPages int `xml:"totalPages,attr"` Artists []struct { Name string `xml:"name"` PlayCount string `xml:"playcount"` TagCount string `xml:"tagcount"` Mbid string `xml:"mbid"` Url string `xml:"url"` Streamable string `xml:"streamable"` Images []struct { Size string `xml:"size,attr"` Url string `xml:",chardata"` } `xml:"image"` } `xml:"artist"` } //library.getTracks type LibraryGetTracks struct { XMLName xml.Name `xml:"tracks"` User string `xml:"user,attr"` Total int `xml:"total,attr"` Page int `xml:"page,attr"` PerPage int `xml:"perPage,attr"` TotalPages int `xml:"totalPages,attr"` Tracks []struct { Name string `xml:"name"` Duration string `xml:"duration"` PlayCount string `xml:"playcount"` TagCount string `xml:"tagcount"` Mbid string `xml:"mbid"` Url string `xml:"url"` Streamable struct { FullTrack string `xml:"fulltrack,attr"` Streamable string `xml:"streamable"` } `xml:"streamable"` Artist struct { Name string `xml:"name"` Mbid string `xml:"mbid"` Url string `xml:"url"` } `xml:"artist"` Album struct { Name string `xml:"name"` Position string `xml:"position"` } `xml:"album"` Images []struct { Size string `xml:"size,attr"` Url string `xml:",chardata"` } `xml:"image"` } `xml:"track"` } //library.removeAlbum (empty) //library.removeArtist (empty) //library.removeScrobble (empty) //library.removeTrack (empty)
Imports NETGeographicLib Module example_GARS Sub Main() Try ' Sample forward calculation Dim lat As Double = 57.64911, lon = 10.40744 Dim garstring As String For prec As Integer = 0 To 2 GARS.Forward(lat, lon, prec, garstring) Console.WriteLine(String.Format("Precision: {0} GARS: {1}", prec, garstring)) Next ' Sample reverse calculation garstring = "381NH45" For len As Integer = 5 To garstring.Length Dim prec As Integer GARS.Reverse(garstring.Substring(0, len), lat, lon, prec, True) Console.WriteLine(String.Format("Precision: {0} Latitude: {1} Longitude {2}", prec, lat, lon)) Next Catch ex As GeographicErr Console.WriteLine(String.Format("Caught Exception {0}", ex.Message)) End Try End Sub End Module
layout: post title: "Hello World" date: 2016-01-30 22:45:15 -0500 categories: blog The Clusternator now has a blog. This blog is part of the documentation project. This site will also serve to host the documentation for The Clusternator. There is primitive [API Documentation][api] that is auto generated on prepublish. [api]: {{ site.baseurl }}/api/ "Clusternator API"
<?php /** * Smarty PHPunit tests compiler plugin * * @package PHPunit * @author Uwe Tews */ /** * class for compiler plugin tests */ class CompilerPluginTests extends <API key> { public function setUp() { $this->smarty = SmartyTests::$smarty; SmartyTests::init(); } public static function isRunnable() { return true; } /** * test compiler plugin */ public function testCompilerPlugin() { $this->smarty->addPluginsDir(dirname(__FILE__)."/PHPunitplugins/"); $this->assertEquals('test output', $this->smarty->fetch('eval:{test data="test output"}{/test}')); } } ?>
class Import::GitlabController < Import::BaseController before_filter :<API key> before_filter :gitlab_auth, except: :callback rescue_from OAuth2::Error, with: :gitlab_unauthorized def callback token = client.get_token(params[:code], <API key>) current_user.gitlab_access_token = token current_user.save redirect_to <API key> end def status @repos = client.projects @<API key> = current_user.created_projects.where(import_type: "gitlab") <API key> = @<API key>.pluck(:import_source) @repos = @repos.to_a.reject{ |repo| <API key>.include? repo["path_with_namespace"] } end def jobs jobs = current_user.created_projects.where(import_type: "gitlab").to_json(only: [:id, :import_status]) render json: jobs end def create @repo_id = params[:repo_id].to_i repo = client.project(@repo_id) @target_namespace = params[:new_namespace].presence || repo["namespace"]["path"] @project_name = repo["name"] namespace = <API key> || (render and return) @project = Gitlab::GitlabImport::ProjectCreator.new(repo, namespace, current_user).execute end private def client @client ||= Gitlab::GitlabImport::Client.new(current_user.gitlab_access_token) end def <API key> not_found! unless <API key>? end def gitlab_auth if current_user.gitlab_access_token.blank? <API key> end end def <API key> redirect_to client.authorize_url(<API key>) end def gitlab_unauthorized <API key> end end
body { font-family: "Lucida Grande", "Lucida Sans Unicode", "Lucida Sans", Geneva, Verdana, sans-serif; text-align: center; letter-spacing: 2px; cursor: none; } #container { /*padding-bottom: 36px;*/ } h1 { font-size: 28px; line-height: 30px; margin-bottom: 25px; } h2 { font-size: 16px; line-height: 30px; color: #a3b9d6; } a { color: #1fe30d; text-decoration: none; } .info { position: relative; width: 500px; margin: auto; padding: 20px; border-radius: 0 0 10px 10px; background-color: rgba(0,0,0,0.7); z-index: 10; } .modal { position: absolute; top: 200px; left: 0; right: 0; color: #a3b9d6; z-index: 20; } .inner_modal { position: relative; width: 500px; margin: auto; padding: 30px; border-radius: 10px; background-color: rgba(0,0,0,0.7); cursor: auto; } .game_over { display: none; } canvas { position: absolute; top: 0; left: 0; right: 0; bottom: 0; } footer { position: absolute; bottom: 0; right: 0; height: 36px; } #links_container { text-align: right; padding: 10px 20px; } #links_container a { text-decoration: none; color: #6b50c7; margin-left: 15px; } #links_container a:visited { color: #6b50c7; } #links_container a:hover { color: #d92e42; }
require_relative '../../spec_helper.rb' describe "ExcelFunctions: ROUNDDOWN(number,decimal places)" do it "should round numbers down" do FunctionTest.rounddown(1.0,0).should == 1.0 FunctionTest.rounddown(1.1,0).should == 1.0 FunctionTest.rounddown(1.5,0).should == 1.0 FunctionTest.rounddown(1.53,1).should == 1.5 FunctionTest.rounddown(-1.53,1).should == -1.5 end it "should return an error when given inappropriate arguments" do FunctionTest.rounddown("Asdasddf","asdfas").should == :value end it "should treat nil as zero" do FunctionTest.rounddown(1.1,nil).should == 1.0 FunctionTest.rounddown(nil,1).should == 0 end it "should return an error if an argument is an error" do FunctionTest.rounddown(1,:error).should == :error FunctionTest.rounddown(:error,1).should == :error FunctionTest.rounddown(:error,:error).should == :error end it "should be in the list of functions that can be mapped to ruby" do MapFormulaeToRuby::FUNCTIONS[:'ROUNDDOWN'].should == 'rounddown' end end
<?php class <API key> { /** * This function parses the calendar-query report request body * * The body is quite complicated, so we're turning it into a PHP * array. * * The resulting associative array has xpath expressions as keys. * By default the xpath expressions should simply be checked for existance * The xpath expressions can point to elements or attributes. * * The array values can contain a number of items, which alters the query * filter. * * * time-range. Must also check if the todo or event falls within the * specified timerange. How this is interpreted depends on * the type of object (VTODO, VEVENT, VJOURNAL, etc) * * is-not-defined * Instead of checking if the attribute or element exist, * we must check if it doesn't. * * text-match * Checks if the value of the attribute or element matches * the specified value. This is actually another array with * the 'collation', 'value' and 'negate-condition' items. * * Refer to the CalDAV spec for more information. * * @param DOMNode $domNode * @param string $basePath used for recursive calls. * @param array $filters used for recursive calls. * @return array */ static public function <API key>($domNode,$basePath = '/c:iCalendar', &$filters = array()) { foreach($domNode->childNodes as $child) { switch(Sabre_DAV_XMLUtil::toClarkNotation($child)) { case '{urn:ietf:params:xml:ns:caldav}comp-filter' : case '{urn:ietf:params:xml:ns:caldav}prop-filter' : $filterName = $basePath . '/' . 'c:' . strtolower($child->getAttribute('name')); $filters[$filterName] = array(); self::<API key>($child, $filterName,$filters); break; case '{urn:ietf:params:xml:ns:caldav}time-range' : if ($start = $child->getAttribute('start')) { $start = self::<API key>($start); } else { $start = null; } if ($end = $child->getAttribute('end')) { $end = self::<API key>($end); } else { $end = null; } if (!is_null($start) && !is_null($end) && $end <= $start) { throw new <API key>('The end-date must be larger than the start-date in the time-range filter'); } $filters[$basePath]['time-range'] = array( 'start' => $start, 'end' => $end ); break; case '{urn:ietf:params:xml:ns:caldav}is-not-defined' : $filters[$basePath]['is-not-defined'] = true; break; case '{urn:ietf:params:xml:ns:caldav}param-filter' : $filterName = $basePath . '/@' . strtolower($child->getAttribute('name')); $filters[$filterName] = array(); self::<API key>($child, $filterName, $filters); break; case '{urn:ietf:params:xml:ns:caldav}text-match' : $collation = $child->getAttribute('collation'); if (!$collation) $collation = 'i;ascii-casemap'; $filters[$basePath]['text-match'] = array( 'collation' => ($collation == 'default'?'i;ascii-casemap':$collation), 'negate-condition' => $child->getAttribute('negate-condition')==='yes', 'value' => $child->nodeValue, ); break; } } return $filters; } /** * Parses an iCalendar (rfc5545) formatted datetime and returns a DateTime object * * Specifying a reference timezone is optional. It will only be used * if the non-UTC format is used. The argument is used as a reference, the * returned DateTime object will still be in the UTC timezone. * * @param string $dt * @param DateTimeZone $tz * @return DateTime */ static public function <API key>($dt,DateTimeZone $tz = null) { // Format is YYYYMMDD + "T" + hhmmss $result = preg_match('/^([1-3][0-9]{3})([0-1][0-9])([0-3][0-9])T([0-2][0-9])([0-5][0-9])([0-5][0-9])([Z]?)$/',$dt,$matches); if (!$result) { throw new <API key>('The supplied iCalendar datetime value is incorrect: ' . $dt); } if ($matches[7]==='Z' || is_null($tz)) { $tz = new DateTimeZone('UTC'); } $date = new DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3] . ' ' . $matches[4] . ':' . $matches[5] .':' . $matches[6], $tz); // Still resetting the timezone, to normalize everything to UTC $date->setTimeZone(new DateTimeZone('UTC')); return $date; } /** * Parses an iCalendar (rfc5545) formatted datetime and returns a DateTime object * * @param string $date * @param DateTimeZone $tz * @return DateTime */ static public function parseICalendarDate($date) { // Format is YYYYMMDD $result = preg_match('/^([1-3][0-9]{3})([0-1][0-9])([0-3][0-9])$/',$date,$matches); if (!$result) { throw new <API key>('The supplied iCalendar date value is incorrect: ' . $date); } $date = new DateTime($matches[1] . '-' . $matches[2] . '-' . $matches[3], new DateTimeZone('UTC')); return $date; } /** * Parses an iCalendar (RFC5545) formatted duration and returns a string suitable * for strtotime or DateTime::modify. * * NOTE: When we require PHP 5.3 this can be replaced by the DateTimeInterval object, which * supports ISO 8601 Intervals, which is a superset of ICalendar durations. * * For now though, we're just gonna live with this messy system * * @param string $duration * @return string */ static public function <API key>($duration) { $result = preg_match('/^(?P<plusminus>\+|-)?P((?P<week>\d+)W)?((?P<day>\d+)D)?(T((?P<hour>\d+)H)?((?P<minute>\d+)M)?((?P<second>\d+)S)?)?$/', $duration, $matches); if (!$result) { throw new <API key>('The supplied iCalendar duration value is incorrect: ' . $duration); } $parts = array( 'week', 'day', 'hour', 'minute', 'second', ); $newDur = ''; foreach($parts as $part) { if (isset($matches[$part]) && $matches[$part]) { $newDur.=' '.$matches[$part] . ' ' . $part . 's'; } } $newDur = ($matches['plusminus']==='-'?'-':'+') . trim($newDur); return $newDur; } }
# Microsoft Azure Container Service Engine The Azure Container Service Engine (`acs-engine`) generates ARM (Azure Resource Manager) templates for Docker enabled clusters on Microsoft Azure with your choice of DCOS, [Kubernetes](kubernetes/deploy.md), or Swarm orchestrators. The input to acs-engine is a cluster definition file which describes the desired cluster, including orchestrator, features, and agents. The structure of the input files is very similar to the public API for Azure Container Service. <a href="#install-acs-engine"></a> ## Install Binary downloads for the latest version of acs-engine for are available [here](https://github.com/Azure/acs-engine/releases/latest). Download `acs-engine` for your operating system. Extract the binary and copy it to your `$PATH`. If would prefer to build `acs-engine` from source or are you are interested in contributing to `acs-engine` see [building from source](#<API key>) below. ## Usage `acs-engine` reads a JSON [cluster definition](./clusterdefinition.md) and generates a number of files that may be submitted to Azure Resource Manager (ARM). The generated files include: 1. **apimodel.json**: is an expanded version of the cluster definition provided to the generate command. All default or computed values will be expanded during the generate phase. 2. **azuredeploy.json**: represents a complete description of all Azure resources required to fulfill the cluster definition from `apimodel.json`. 3. **azuredeploy.parameters.json**: the parameters file holds a series of custom variables which are used in various locations throughout `azuredeploy.json`. 4. **certificate and access config files**: orchestrators like Kubernetes require certificates and additional configuration files (e.g. Kubernetes apiserver certificates and kubeconfig). Generate Templates ACS Engine consumes a cluster definition which outlines the desired shape, size, and configuration of Kubernetes. There are a number of features that can be enabled through the cluster definition. See [ACS Engine The Long Way](kubernetes/deploy.md#<API key>) for an example on generating templates by hand. <a href="#deployment-usage"></a> Deploy Templates Generated templates can be deployed using [the Azure CLI 2.0](https: # Deploying with Azure CLI 2.0 Azure CLI 2.0 is the latest CLI maintained and supported by Microsoft. For installation instructions see [the Azure CLI GitHub repository](https://github.com/Azure/azure-cli#installation) for the latest release. bash $ az login $ az account set --subscription "<SUBSCRIPTION NAME OR ID>" $ az group create \ --name "<RESOURCE_GROUP_NAME>" \ --location "<LOCATION>" $ az group deployment create \ --name "<DEPLOYMENT NAME>" \ --resource-group "<RESOURCE_GROUP_NAME>" \ --template-file "./_output/<INSTANCE>/azuredeploy.json" \ --parameters "./_output/<INSTANCE>/azuredeploy.parameters.json" # Deploying with Powershell powershell Add-AzureRmAccount <API key> -SubscriptionID <SUBSCRIPTION_ID> <API key> ` -Name <RESOURCE_GROUP_NAME> ` -Location <LOCATION> <API key> ` -Name <DEPLOYMENT_NAME> ` -ResourceGroupName <RESOURCE_GROUP_NAME> ` -TemplateFile _output\<INSTANCE>\azuredeploy.json ` -<API key> _output\<INSTANCE>\azuredeploy.parameters.json <a href="#build-from-source"></a> ## Build ACS Engine from Source Docker Development Environment The easiest way to start hacking on `acs-engine` is to use a Docker-based environment. If you already have Docker installed then you can get started with a few commands. * Windows (PowerShell): `.\scripts\devenv.ps1` * Linux/OSX (bash): `./scripts/devenv.sh` This script mounts the `acs-engine` source directory as a volume into the Docker container, which means you can edit your source code in your favorite editor on your machine, while still being able to compile and test inside of the Docker container. This environment mirrors the environment used in the acs-engine continuous integration (CI) system. When the script `devenv.ps1` or `devenv.sh` completes, you will be left at a command prompt. Run the following commands to pull the latest dependencies and build the `acs-engine` tool. # install and download build dependencies make bootstrap # build the `acs-engine` binary make build The build process leaves the compiled `acs-engine` binary in the `bin` directory. Make sure everything completed successfully by running `bin/acs-engine` without any arguments: # ./bin/acs-engine ACS-Engine deploys and manages Kubernetes, Swarm Mode, and DC/OS clusters in Azure Usage: acs-engine [command] Available Commands: deploy deploy an Azure Resource Manager template generate Generate an Azure Resource Manager template help Help about any command orchestrators provide info about supported orchestrators scale scale a deployed cluster upgrade upgrades an existing Kubernetes cluster version Print the version of ACS-Engine Flags: --debug enable verbose debug logs -h, --help help for acs-engine Use "acs-engine [command] --help" for more information about a command. [Here is a reference to the information on Kubernetes cluster upgrade.](https://github.com/Azure/acs-engine/blob/master/examples/k8s-upgrade/README.md) [Here's a quick demo video showing the dev/build/test cycle with this setup.](https: ## Building on Windows, OSX, and Linux Building ACS Engine from source has a few requirements for each of the platforms. Download and install the pre-reqs for your platform, Windows, Linux, or Mac: Prerequisite 1. Go version 1.8 [installation instructions](https://golang.org/doc/install) 2. Git Version Control [installation instructions](https://git-scm.com/download/) Windows Setup steps: 1. Setup your go workspace. This guide assumes you are using `c:\gopath` as your Go workspace: 1. Type Windows key-R to open the run prompt 2. Type `rundll32 sysdm.cpl,<API key>` to open the system variables 3. Add `c:\go\bin` and `c:\gopath\bin` to your PATH variables 4. Click "new" and add new environment variable named `GOPATH` and set the value to `c:\gopath` Build acs-engine: 1. Type Windows key-R to open the run prompt 2. Type `cmd` to open a command prompt 3. Type `mkdir %GOPATH%` to create your gopath 4. Type `cd %GOPATH%` 5. Type `go get -d github.com/Azure/acs-engine` to download acs-engine from GitHub 6. Type `go get all` to get the supporting components 7. Type `go get -u github.com/jteeuwen/go-bindata/...` 8. Type `cd %GOPATH%\src\github.com\Azure\acs-engine\pkg\acsengine` 9. Type `go generate` 10. Type `cd %GOPATH%\src\github.com\Azure\acs-engine\pkg\i18n` 11. Type `go generate` 12. Type `cd %GOPATH%\src\github.com\Azure\acs-engine` 13. Type `go build` to build the project 14. Type `go install` to install the project 15. Run `acs-engine.exe` to see the command line parameters OS X and Linux Setup steps: 1. Open a command prompt to setup your gopath: 2. `mkdir $HOME/go` 3. edit `$HOME/.bash_profile` and add the following lines to setup your go path export GOPATH=$HOME/go export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin 4. `source $HOME/.bash_profile` Build acs-engine: 1. Type `go get github.com/Azure/acs-engine` to get the acs-engine Github project 2. Type `cd $GOPATH/src/github.com/Azure/acs-engine` to change to the source directory 3. Type `make bootstrap` to install supporting components 4. Type `make build` to build the project 5. Type `./bin/acs-engine` to see the command line parameters
(function(d3, fc) { 'use strict'; var dataGenerator = fc.data.random.financial() .startDate(new Date(2014, 1, 1)); var data = dataGenerator(50); // Calculate the scale domain var day = 8.64e7, // One day in milliseconds dateFrom = new Date(d3.min(data, function(d) { return d.date; }).getTime() - day), dateTo = new Date(d3.max(data, function(d) { return d.date; }).getTime() + day), priceFrom = d3.min(data, function(d) { return d.low; }), priceTo = d3.max(data, function(d) { return d.high; }); var chart = fc.chart.linearTimeSeries() .xDomain([dateFrom, dateTo]) .xNice() .xTicks(5) .yDomain([priceFrom, priceTo]) .yNice() .yTicks(5); // Create the gridlines var gridlines = fc.annotation.gridline(); // Create the line series var line = fc.series.line() .yValue(function(d) { return d.open; }); // Create the area series var area = fc.series.area() .y0Value(function(d) { return d.low; }) .y1Value(function(d) { return d.high; }); // Create the point series var point = fc.series.point() .yValue(function(d) { return d.close; }); // add a bollinger - which results in a nested mutli-series var bollingerComputer = fc.indicator.algorithm.bollingerBands(); bollingerComputer(data); var bollingerRenderer = fc.indicator.renderer.bollingerBands(); // Create the multi series var multi = fc.series.multi() .series([gridlines, bollingerRenderer, line, area, point]); chart.plotArea(multi); var svg = d3.select('#multi') .append('svg') .style({ height: '240px', width: '320px' }); function render() { svg.datum(data) .call(chart); } // issues with nested multi-series only manifest themselves when // the data-join is evaluated a second time, hence we render // twice in this test render(); render(); })(d3, fc);
/* * ImageCache2::Viewer */ // {{{ GLOBALS var last_checked_box = null, last_unchecked_box = null; // {{{ showToolbarExtra() function showToolbarExtra() { var ext = document.getElementById('toolbarExtra'); var swa = document.getElementById('toolbarSwitchA'); var swb = document.getElementById('toolbarSwitchB'); ext.style.visibility = 'visible'; swa.style.display = 'none'; swb.style.display = 'inline'; return false; } // {{{ hideToolbarExtra() function hideToolbarExtra() { var ext = document.getElementById('toolbarExtra'); var swa = document.getElementById('toolbarSwitchA'); var swb = document.getElementById('toolbarSwitchB'); ext.style.visibility = 'hidden'; swa.style.display = 'inline'; swb.style.display = 'none'; return false; } // {{{ iv2_checkAll() function iv2_checkAll(mode) { var cboxes = document.getElementsByName('change[]'); for (var i = 0; i < cboxes.length; i++) { switch (mode) { case 'on': cboxes[i].checked = true; break; case 'off': cboxes[i].checked = false; break; case 'reverse': cboxes[i].checked = !cboxes[i].checked; break; } } } // {{{ iv2_checked() function iv2_checked(cbox, evt) { var evt = (evt) ? evt : ((window.event) ? window.event : null); var chk = cbox.checked; if (evt && evt.shiftKey) { var tgt = null; if (last_checked_box) { tgt = last_checked_box; chk = true; } else if (last_unchecked_box) { tgt = last_unchecked_box; chk = false; } if (tgt) { var cboxes = document.getElementsByName('change[]'); var i = 0, j = -1, k = -1, l = cboxes.length; while (i < l) { if (cboxes[i] == cbox) { j = i; if (k != -1) break; } else if (cboxes[i] == tgt) { k = i; if (j != -1) break; } i++; } if (i < l) { if (j > k) { while (j >= k) cboxes[j--].checked = chk; } else { while (j <= k) cboxes[j++].checked = chk; } } } } if (chk) { last_checked_box = cbox; last_unchecked_box = null; } else { last_checked_box = null; last_unchecked_box = cbox; } return true; } // {{{ pageJump() function pageJump(page) { location.href = document.getElementById('current_page').value.replace(/page=[0-9]*/, 'page='+page); } // {{{ rankDown() function rankDown(itemId) { itemId = itemId.toString(); var rank = getRank(itemId); if (rank > -1) { rank return setRank(itemId, rank); } return false; } // {{{ rankUp() function rankUp(itemId) { itemId = itemId.toString(); var rank = getRank(itemId); if (rank < 5) { rank++; return setRank(itemId, rank); } return false; } // {{{ getRank() function getRank(itemId) { var value = document.getElementById('rank'+itemId).innerHTML; if (value == '‚ ‚ځ[‚ñ') { return -1; } return parseInt(value, 10); } // {{{ setRank() function setRank(itemId, rank) { var objHTTP = new XMLHttpRequest(); if (!objHTTP) { alert("Error: XMLHTTP ’ʐMƒIƒuƒWƒFƒNƒg‚̍쐬‚ÉŽ¸”s‚µ‚Ü‚µ‚½B") ; } var url = 'ic2_setrank.php?id=' + itemId + '&rank=' + rank.toString(); var res = getResponseTextHttp(objHTTP, url, 'nc'); if (res == '1') { document.getElementById('rank'+itemId).innerHTML = rank.toString(); return true; } return false; } // {{{ p2BindReady() p2BindReady(function(){ var toolbar = document.getElementById('toolbar'); var toolbarHeight = getCurrentStyle(toolbar).height; if (toolbarHeight == 'auto') { toolbarHeight = toolbar.clientHeight; } else { toolbarHeight = parsePixels(toolbarHeight); } document.getElementById('header').style.height = toolbarHeight + 'px'; }, null); /* * Local Variables: * mode: javascript * coding: cp932 * tab-width: 4 * c-basic-offset: 4 * indent-tabs-mode: t * End: */ /* vim: set syn=javascript fenc=cp932 ai noet ts=4 sw=4 sts=4 fdm=marker: */
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta content="text/html; charset=UTF-8" http-equiv="Content-Type"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>About the Theme – JBlog</title> <meta name="description" content="JBlog is a minimal, one column and blue jekyll theme for your blog."> <meta name="keywords" content="about, Jekyll, theme, JBlog"> <link rel="canonical" href="http://localhost:4000/about/"> <!-- Twitter Cards --> <meta name="twitter:title" content="About the Theme"> <meta name="twitter:site" content="@username"> <meta name="twitter:creator" content="@username"> <meta name="twitter:card" content="summary"> <meta name="twitter:image" content="http://localhost:4000/assets/img/profile.png"> <!-- Open Graph --> <meta property="og:locale" content="en_US"> <meta property="og:type" content="article"> <meta property="og:title" content="About the Theme"> <meta property="og:url" content="http://localhost:4000/about/"> <meta property="og:site_name" content="JBlog"> <meta property="og:image" content="http://localhost:4000/assets/img/profile.png"> <!-- Handheld --> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Favicons --> <link rel="<API key>" sizes="57x57" href="http://localhost:4000/assets/img/favicon/<API key>.png"> <link rel="<API key>" sizes="114x114" href="http://localhost:4000/assets/img/favicon/<API key>.png"> <link rel="<API key>" sizes="72x72" href="http://localhost:4000/assets/img/favicon/<API key>.png"> <link rel="<API key>" sizes="144x144" href="http://localhost:4000/assets/img/favicon/<API key>.png"> <link rel="icon" type="image/png" href="http://localhost:4000/assets/img/favicon/favicon.png"> <link rel="shortcut icon" href="http://localhost:4000/assets/img/favicon/favicon.ico"> <!-- Feed --> <link rel="alternate" type="application/rss+xml" title="JBlog" href="http://localhost:4000/feed.xml"> <!-- CSS --> <link rel="stylesheet" type="text/css" href="http://localhost:4000/assets/css/main.css"> </head> <body> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript"> $(function() { i = 0; $('.menuAc').css({ 'color': 'rgba(52, 152, 219, 1)' }); $('.menuAc').click(function(){ $(this).next('.menuMobil').animate({width:'toggle'},350); if (i%2==0) { $('.footer').css({ 'filter' : 'blur(5px)' }); $('.yazilar').css({ 'filter' : 'blur(5px)' }); $('.ust').css({ 'filter' : 'blur(5px)' }); $('ul.menu').css({ 'animation-duration': '0.1s' }); i++; } else { $('.footer').css({ 'filter' : 'blur(0px)' }); $('.yazilar').css({ 'filter' : 'blur(0px)' }); $('.ust').css({ 'filter' : 'blur(0px)' }); i++; } }); }); </script> <div class="menuAc"> <i class="fa fa-bars" aria-hidden="true"></i> </div> <div class="menuMobil"> <nav class="nav-home"> <ul class="menu"> <li><a class="link" href="http://localhost:4000/">Home</a></li> <li><a class="link" href="http://localhost:4000/blog/">Blog</a></li> <li><a class="link" href="http://localhost:4000/projects/">Projects</a></li> <li><a class="link" href="http://localhost:4000/about/">About</a></li> </ul> </nav> </div> <div class="ust"> <div class="ortalaAna"> <div class="baslikAna"> JBlog </div> <div class="pc"> <nav class="nav"> <ul class="menuAna"> <li class="item"><a class="link" href="http://localhost:4000/">Home</a></li> <li class="item"><a class="link" href="http://localhost:4000/blog/">Blog</a></li> <li class="item"><a class="link" href="http://localhost:4000/projects/">Projects</a></li> <li class="item"><a class="link" href="http://localhost:4000/about/">About</a></li> </ul> </nav> </div> </div> </div> <div class="ortalaAna"> <div class="yazilar"> <div class="yazi"> <div class="ustr"> <h2>About the Theme</h2> </div> <hr> <div class="content"> <p class="image-pull-right"><img src="http://dab1nmslvvntp.cloudfront.net/wp-content/uploads/2015/02/1424055625jekyll.png" alt="jekyll Image"></p> <center> <b>JBlog</b> is a simple jekyll theme.</center> <h2 id="about">About</h2> <p>I have used this theme in my own php and ruby blogs. And there are some shortcomings. If something looks extremely ugly and you can’t resist to fix it, just send me a PR. I will be grateful.</p> <p>If you like this theme or using it, please give a <strong>star</strong> for motivation.</p> <p>You want to <strong>use it?</strong></p> <p><a href="https://github.com/alperenbozkurt/JBlog" class="btn btn-info">Install JBlog</a></p> </div> </div> <script src="http://localhost:4000/assets/js/jquery-1.12.2.min.js"></script> <script src="http://localhost:4000/assets/js/jquery.goup.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $.goup({ trigger: 500, bottomOffset: 10, locationOffset: 20, containerRadius: 0, containerColor: '#fff', arrowColor: '#000', goupSpeed: 'normal' }); }); </script> <div id="disqus_thread" class="yazi"> </div> <script> /* var disqus_config = function () { this.page.url = PAGE_URL; // Replace PAGE_URL with your page's canonical URL variable this.page.identifier = PAGE_IDENTIFIER; // Replace PAGE_IDENTIFIER with your page's unique identifier variable }; */ (function() { // DON'T EDIT BELOW THIS LINE var d = document, s = d.createElement('script'); s.src = 'https://alperenbozkurt-net.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> <noscript>Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a> </noscript> <script id="dsq-count-scr" src="//alperenbozkurt-net.disqus.com/count.js" async></script> </div> </div> <div class="footer"> <div class="ortalaAna"> <div class="copy"> JBlog © 2017 </div> <div class="sosyal"> <div class="social-links"> <a href="http://twitter.com/username" class="author-social" target="_blank"><i class="fa fa-2x fa-twitter-square"></i></a> <a href="http://facebook.com/username" class="author-social" target="_blank"><i class="fa fa-2x fa-facebook-square"></i></a> <a href="http://linkedin.com/in/username" class="author-social" target="_blank"><i class="fa fa-2x fa-linkedin-square"></i></a> <a href="http://instagram.com/username" class="author-social" target="_blank"><i class="fa fa-2x fa-instagram"></i></a> <a href="http://username.tumblr.com" class="author-social" target="_blank"><i class="fa fa-2x fa-tumblr-square"></i></a> <a href="http://github.com/username" class="author-social" target="_blank"><i class="fa fa-2x fa-github"></i></a> <a href="http://lastfm.com/user/username" class="author-social" target="_blank"><i class="fa fa-2x fa-music"></i></a> <a href="http://steamcommunity.com/id/username" class="author-social" target="_blank"><i class="fa fa-2x fa-steam-square"></i></a> <a href="https://youtube.com/user/username" class="author-social" target="_blank"><i class="fa fa-2x fa-youtube-square"></i></a> </div> </div> </div> </div> </body> </html>
from __future__ import unicode_literals import frappe import HTMLParser import urllib from frappe import msgprint, throw, _ from frappe.email.smtp import SMTPServer, <API key> from frappe.email.email_body import get_email, get_formatted_html from html2text import html2text from frappe.utils import cint, get_url, nowdate class <API key>(frappe.ValidationError): pass def send(recipients=None, sender=None, doctype='User', email_field='email', subject='[No Subject]', message='[No Content]', ref_doctype=None, ref_docname=None, <API key>=True, attachments=None, reply_to=None): def is_unsubscribed(rdata): if not rdata: return 1 return cint(rdata.unsubscribed) def check_bulk_limit(new_mails): this_month = frappe.db.sql("""select count(*) from `tabBulk Email` where month(creation)=month(%s)""" % nowdate())[0][0] # No limit for own email settings smtp_server = SMTPServer() if smtp_server.email_account and not getattr(smtp_server.email_account, "from_site_config", False): <API key> = frappe.conf.get('<API key>') or 500 if (this_month + len(recipients)) > <API key>: throw(_("Bulk email limit {0} crossed").format(<API key>), <API key>) def update_message(formatted, doc, <API key>): updated = formatted if <API key>: unsubscribe_link = """<div style="padding: 7px; border-top: 1px solid #aaa; margin-top: 17px;"> <small><a href="%s/?%s"> Unsubscribe</a> from this list.</small></div>""" % (get_url(), urllib.urlencode({ "cmd": "frappe.email.bulk.unsubscribe", "email": doc.get(email_field), "type": doctype, "email_field": email_field })) updated = updated.replace("<!--unsubscribe link here-->", unsubscribe_link) return updated if not recipients: recipients = [] if not sender or sender == "Administrator": email_account = <API key>() sender = email_account.get("sender") or email_account.email_id check_bulk_limit(len(recipients)) formatted = get_formatted_html(subject, message) for r in filter(None, list(set(recipients))): rdata = frappe.db.sql("""select * from `tab%s` where %s=%s""" % (doctype, email_field, '%s'), (r,), as_dict=1) doc = rdata and rdata[0] or {} if (not <API key>) or (not is_unsubscribed(doc)): # add to queue updated = update_message(formatted, doc, <API key>) try: text_content = html2text(updated) except HTMLParser.HTMLParseError: text_content = "[See html attachment]" add(r, sender, subject, updated, text_content, ref_doctype, ref_docname, attachments, reply_to) def add(email, sender, subject, formatted, text_content=None, ref_doctype=None, ref_docname=None, attachments=None, reply_to=None): """add to bulk mail queue""" e = frappe.new_doc('Bulk Email') e.sender = sender e.recipient = email try: e.message = get_email(email, sender=e.sender, formatted=formatted, subject=subject, text_content=text_content, attachments=attachments, reply_to=reply_to).as_string() except frappe.<API key>: # bad email id - don't add to queue return e.ref_doctype = ref_doctype e.ref_docname = ref_docname e.insert(ignore_permissions=True) @frappe.whitelist(allow_guest=True) def unsubscribe(): doctype = frappe.form_dict.get('type') field = frappe.form_dict.get('email_field') email = frappe.form_dict.get('email') frappe.db.sql("""update `tab%s` set unsubscribed=1 where `%s`=%s""" % (doctype, field, '%s'), (email,)) if not frappe.form_dict.get("from_test"): frappe.db.commit() frappe.local.message_title = "Unsubscribe" frappe.local.message = "<h3>Unsubscribed</h3><p>%s has been successfully unsubscribed.</p>" % email frappe.response['type'] = 'page' frappe.response['page_name'] = 'message.html' def flush(from_test=False): """flush email queue, every time: called from scheduler""" smtpserver = SMTPServer() auto_commit = not from_test if frappe.flags.mute_emails or frappe.conf.get("mute_emails") or False: msgprint(_("Emails are muted")) from_test = True for i in xrange(500): email = frappe.db.sql("""select * from `tabBulk Email` where status='Not Sent' limit 1 for update""", as_dict=1) if email: email = email[0] else: break frappe.db.sql("""update `tabBulk Email` set status='Sending' where name=%s""", (email["name"],), auto_commit=auto_commit) try: if not from_test: smtpserver.sess.sendmail(email["sender"], email["recipient"], email["message"]) frappe.db.sql("""update `tabBulk Email` set status='Sent' where name=%s""", (email["name"],), auto_commit=auto_commit) except Exception, e: frappe.db.sql("""update `tabBulk Email` set status='Error', error=%s where name=%s""", (unicode(e), email["name"]), auto_commit=auto_commit) def clear_outbox(): """remove mails older than 30 days in Outbox""" frappe.db.sql("""delete from `tabBulk Email` where datediff(now(), creation) > 30""")
<html><head><link rel="canonical" href="/2013/10/24/<API key>"><meta http-equiv="refresh" content="0; url=/2013/10/24/<API key>"></head><body></body></html>
(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.0 -wrap,-event-alias,-ajax,-ajax/script,-ajax/jsonp,-ajax/xhr,-effects,-offset,-deprecated", // 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 = /^(?:(<[\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 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: $( } 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| 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 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.<API key>( "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); (function( window, undefined ) { var i, 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, support = {}, 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, // Array methods 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#<API key> 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" ), "boolean": 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 = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // 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; } }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var cache, keys = []; return (cache = function( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); }); } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle(" 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.<API key>( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.<API key> && context.<API key> ) { push.apply( results, context.<API key>( 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 ); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Check if <API key>("*") returns only elements support.<API key> = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.<API key>("*").length; }); // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); // Check if <API key> can be trusted support.<API key> = 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.<API key>("i").length === 2; }); // 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.<API key>( document.createElement("div") ) & 1; }); // Support: IE<10 // Check if getElementById returns elements by name // Support: Windows 8 Native Apps // Assigning innerHTML with "name" attributes throws uncatchable exceptions // and 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 { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.<API key> ? function( tag, context ) { if ( typeof context.<API key> !== strundefined ) { return context.<API key>( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.<API key>( 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.<API key> && function( className, context ) { if ( typeof context.<API key> !== strundefined && documentIsHTML ) { return context.<API key>( className ); } }; // 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 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 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/<API key>/#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 = document.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.<API key> || 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("|") ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.<API key> ? 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.<API key> && a.<API key>( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; // Document order sorting sortOrder = docElem.<API key> ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.<API key> && a.<API key> && a.<API key>( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.<API key>( 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.<API key> ? -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 document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyQSA always contains :focus, so no need for an existence check if ( support.matchesSelector && 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() ], val = fn && fn( elem, name, !documentIsHTML ); 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 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; }; /** * 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 && ( ~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; } // Fetches boolean attributes by node function boolHandler( elem, name, isXML ) { var val; return isXML ? undefined : (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } // Fetches attributes without interpolation function <API key>( elem, name, isXML ) { var val; return isXML ? undefined : (val = elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 )); } // 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 <API key>( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, 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[4] ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( 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/<API key>/#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 " 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 ); }, // <API key> "first": <API key>(function() { return [ 0 ]; }), "last": <API key>(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": <API key>(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": <API key>(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": <API key>(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": <API key>(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": <API key>(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function <API key>( 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, <API key>( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && 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; // Support: IE<8 // Prevent attribute/property "interpolation" assert(function( div ) { div.innerHTML = "<a href=' if ( div.firstChild.getAttribute("href") !== " var attrs = "type|href|height|width".split("|"), i = attrs.length; while ( i Expr.attrHandle[ attrs[i] ] = <API key>; } } }); // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies assert(function( div ) { if ( div.getAttribute("disabled") != null ) { var attrs = booleans.split("|"), i = attrs.length; while ( i Expr.attrHandle[ attrs[i] ] = boolHandler; } } }); 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, 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.<API key>(), 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 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.<API key>("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 { // Support an expectation from the old data system where plain // objects used to initialize would be set to the cache by // reference, instead of having properties and values copied. // Note, this will kill the connection between // "this.cache[ unlock ]" and "cache" if ( jQuery.isEmptyObject( cache ) ) { this.cache[ unlock ] = data; // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } }, 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, 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 { // Try the string as a key before any manipulation if ( key in cache ) { name = [ key ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = jQuery.camelCase( key ); 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 ) { delete this.cache[ this.key( owner ) ]; } }; // 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.substring(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 ); }); }, 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]/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, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // 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.boolean.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.boolean.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.boolean.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.<API key>() ) { 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.<API key>() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.<API key>() ) { // 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 ); } // 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: 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 jQuery.Event.prototype = { isDefaultPrevented: returnFalse, <API key>: returnFalse, <API key>: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.<API key> = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, <API key>: function() { this.<API key> = 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 = /^.[^: 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 self, matched, i, l = this.length; if ( typeof selector !== "string" ) { self = this; return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < l; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } matched = []; for ( i = 0; i < l; i++ ) { jQuery.find( selector, this[ i ], matched ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) matched = this.pushStack( l > 1 ? jQuery.unique( matched ) : matched ); matched.selector = ( this.selector ? this.selector + " " : "" ) + selector; return matched; }, 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 !!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, 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* if ( name[ 0 ] === "p" ) { 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 = /<|& rnoInnerhtml = /<(?:script|style|link)/i, <API key> = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[| // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</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.col = 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 ) { 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 ) ) { 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.<API key>(), 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, type, l = elems.length, i = 0, special = jQuery.event.special; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( jQuery.acceptData( elem ) ) { data = data_priv.access( elem ); if ( data ) { 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 ); } } } } // Discard any remaining `private` and `user` data // One day we'll replace the dual arrays with a WeakMap and this won't be an issue. // (Splices the data objects out of the internal cache arrays) data_user.discard( elem ); data_priv.discard( elem ); } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "text", async: false, global: false, success: jQuery.globalEval }); } }); // 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.<API key>("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 = jQuery.extend( {}, pdataOld ); events = pdataOld.events; data_priv.set( dest, pdataCur ); 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.<API key> ? context.<API key>( 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" && <API key>.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; } } var curCSS, iframe, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" 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; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "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 <API key>( 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 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 + <API key>( 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 ? <API key>( 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" ] ); } } }; } // 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 || !<API key>.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 ); } } // 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: 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 ); }; }); }); if ( typeof module === "object" && 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 );
# <API key>: true require "isolation/abstract_unit" require "env_helpers" module ApplicationTests class RakeTest < ActiveSupport::TestCase include ActiveSupport::Testing::Isolation, EnvHelpers def setup build_app end def teardown teardown_app end def <API key> app_file "lib/tasks/app.rake", <<-RUBY $task_loaded = Rake::Task.task_defined?("db:create:all") RUBY require "#{app_path}/config/environment" ::Rails.application.load_tasks assert $task_loaded end test "task is protected when previous migration was production" do with_rails_env "production" do rails "generate", "model", "product", "name:string" rails "db:create", "db:migrate" output = rails("db:test:prepare", allow_failure: true) assert_match(/ActiveRecord::<API key>/, output) end end def <API key> with_rails_env "test" do rails "generate", "model", "product", "name:string" rails "db:create", "db:migrate" output = rails("db:test:prepare", "test") assert_no_match(/ActiveRecord::<API key>/, output) end end def <API key> app_file "config/environment.rb", <<-RUBY SuperMiddleware = Struct.new(:app) Rails.application.configure do config.middleware.use SuperMiddleware end Rails.application.initialize! RUBY assert_match("SuperMiddleware", rails("middleware")) end def <API key> add_to_config <<-RUBY initializer "do_something" do puts "Doing something..." end rake_tasks do task do_nothing: :environment do end end RUBY output = rails("do_nothing") assert_match "Doing something...", output end def <API key> add_to_config <<-RUBY rake_tasks do task do_nothing: :environment do Hello.new.world end end RUBY app_file "app/models/hello.rb", <<-RUBY class Hello def world puts 'Hello world' end end RUBY output = rails("do_nothing") assert_match "Hello world", output end def <API key> add_to_config <<-RUBY rake_tasks do task do_nothing: :environment do puts 'There is nothing' end end RUBY add_to_env_config "production", <<-RUBY config.eager_load = true RUBY app_file "app/models/hello.rb", <<-RUBY raise 'should not be pre-required for rake even eager_load=true' RUBY output = rails("do_nothing", "RAILS_ENV=production") assert_match "There is nothing", output end def <API key> assert_match "Code LOC: 32 Test LOC: 0 Code to Test Ratio: 1:0.0", rails("stats") end def <API key> add_to_config <<-RUBY rake_tasks do task log_something: :environment do Rails.logger.error("Sample log message") end end RUBY rails "log_something", "RAILS_ENV=production" assert_match "Sample log message", File.read("#{app_path}/log/production.log") end def <API key> rails "generate", "model", "user", "username:string", "password:string" rails "generate", "model", "product", "name:string" rails "db:migrate" require "#{rails_root}/config/environment" # loading a specific fixture rails "db:fixtures:load", "FIXTURES=products" assert_equal 2, ::AppTemplate::Application::Product.count assert_equal 0, ::AppTemplate::Application::User.count end def <API key> rails "db:migrate" app_file "test/fixtures/products.csv", "" require "#{rails_root}/config/environment" rails "db:fixtures:load" end def <API key> rails "generate", "scaffold", "user", "username:string", "password:string" with_rails_env("test") { rails("db:migrate") } output = rails("test") assert_match(/7 runs, 9 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end def <API key> add_to_config <<-RUBY config.api_only = true RUBY app_file "app/controllers/<API key>.rb", <<-RUBY class <API key> < ActionController::API end RUBY rails "generate", "scaffold", "user", "username:string", "password:string" with_rails_env("test") { rails("db:migrate") } output = rails("test") assert_match(/5 runs, 7 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end def <API key> rails "generate", "model", "Product" rails "generate", "model", "Cart" rails "generate", "scaffold", "LineItems", "product:references", "cart:belongs_to" with_rails_env("test") { rails("db:migrate") } rails("webpacker:compile") output = rails("test") assert_match(/7 runs, 9 assertions, 0 failures, 0 errors/, output) assert_no_match(/Errors running/, output) end def <API key> add_to_config "config.active_record.schema_format = :sql" rails "generate", "scaffold", "user", "username:string" rails "db:migrate" output = rails("db:test:prepare", "--trace") assert_match(/Execute db:test:load_structure/, output) end def <API key> # ensure we have a schema_migrations table to dump rails "db:migrate", "db:structure:dump", "SCHEMA=db/my_structure.sql" assert File.exist?(File.join(app_path, "db", "my_structure.sql")) end def <API key> add_to_config "config.active_record.schema_format = :sql" rails "g", "model", "post", "title:string" output = rails("db:migrate:redo", "--trace") # expect only Invoke db:structure:dump (first_time) assert_no_match(/^\*\* Invoke db:structure:dump\s+$/, output) end def <API key> rails "generate", "model", "post", "title:string" rails "generate", "model", "product", "name:string" rails "db:migrate", "db:schema:cache:dump" assert File.exist?(File.join(app_path, "db", "schema_cache.yml")) end def <API key> rails "db:schema:cache:dump", "db:schema:cache:clear" assert_not File.exist?(File.join(app_path, "db", "schema_cache.yml")) end def test_copy_templates rails "app:templates:copy" %w(controller mailer scaffold).each do |dir| assert File.exist?(File.join(app_path, "lib", "templates", "erb", dir)) end %w(controller helper scaffold_controller assets).each do |dir| assert File.exist?(File.join(app_path, "lib", "templates", "rails", dir)) end end def <API key> app_file "config/initializers/dummy.rb", "puts 'Hello, World!'" app_file "template.rb", "" output = rails("app:template", "LOCATION=template.rb") assert_match(/Hello, World!/, output) end end end
$(function() { $('#field-project').combobox(); });
// Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsLro.Models { using Fixtures.Azure; using Fixtures.Azure.AcceptanceTestsLro; using Newtonsoft.Json; using System.Linq; <summary> Defines headers for <API key> operation. </summary> public partial class <API key> { <summary> Initializes a new instance of the <API key> class. </summary> public <API key>() { } <summary> Initializes a new instance of the <API key> class. </summary> <param name="azureAsyncOperation">Location to poll for result status: will be set to /lro/putasync/retry/failed/operationResults/200</param> <param name="location">Location to poll for result status: will be set to /lro/putasync/retry/failed/operationResults/200</param> <param name="retryAfter">Number of milliseconds until the next poll should be sent, will be set to zero</param> public <API key>(string azureAsyncOperation = default(string), string location = default(string), int? retryAfter = default(int?)) { AzureAsyncOperation = azureAsyncOperation; Location = location; RetryAfter = retryAfter; } <summary> Gets or sets location to poll for result status: will be set to /lro/putasync/retry/failed/operationResults/200 </summary> [JsonProperty(PropertyName = "<API key>")] public string AzureAsyncOperation { get; set; } <summary> Gets or sets location to poll for result status: will be set to /lro/putasync/retry/failed/operationResults/200 </summary> [JsonProperty(PropertyName = "Location")] public string Location { get; set; } <summary> Gets or sets number of milliseconds until the next poll should be sent, will be set to zero </summary> [JsonProperty(PropertyName = "Retry-After")] public int? RetryAfter { get; set; } } }
"use strict"; const jsdom = require("../.."); exports["cookieEnabled should be true on the navigator object"] = t => { const window = jsdom.jsdom().defaultView; t.strictEqual(window.navigator.cookieEnabled, true, "cookie enabled"); t.done(); }; exports["navigator properties should be read-only from the site"] = t => { t.expect(5); jsdom.env({ html: "<!doctype html><html><head><script>navigator.userAgent = 'test'; navigator.platform = 'test';" + "navigator.appName = 'test';navigator.appVersion = 'test';</script></head><body></body></html>", done(err, window) { t.ifError(err); t.notEqual(window.navigator.userAgent, "test", "navigator.userAgent shouldn't be modifiable"); t.notEqual(window.navigator.platform, "test", "navigator.platform shouldn't be modifiable"); t.notEqual(window.navigator.appName, "test", "navigator.appName shouldn't be modifiable"); t.notEqual(window.navigator.appVersion, "test", "navigator.appVersion shouldn't be modifiable"); t.done(); }, features: { <API key>: ["script"], <API key>: ["script"] } }); };
package org.spongepowered.common.text; import net.minecraft.util.ChatComponentStyle; import net.minecraft.util.IChatComponent; import java.util.List; public class <API key> extends ChatComponentStyle { private final String placeholderKey; private IChatComponent fallback; public <API key>(String placeholderKey) { this(placeholderKey, null); } public <API key>(String placeholderKey, IChatComponent fallback) { this.placeholderKey = placeholderKey; this.fallback = fallback; } public String getPlaceholderKey() { return this.placeholderKey; } @Override public String <API key>() { return this.fallback == null ? "{" + this.placeholderKey + "}" : this.fallback.<API key>(); } public IChatComponent getFallback() { return this.fallback; } public void setFallback(IChatComponent fallback) { this.fallback = fallback; } @Override public <API key> createCopy() { <API key> copy = new <API key>(this.placeholderKey, this.fallback == null ? null : this.fallback.createCopy()); copy.setChatStyle(this.getChatStyle().createShallowCopy()); @SuppressWarnings("unchecked") List<IChatComponent> siblings = this.getSiblings(); for (IChatComponent sibling : siblings) { copy.appendSibling(sibling.createCopy()); } return copy; } @Override public boolean equals(Object obj) { if (obj == this) { return true; } else if (!(obj instanceof <API key>)) { return false; } else { <API key> other = (<API key>) obj; return placeholderKey.equals(other.placeholderKey) && super.equals(obj); } } @Override public String toString() { return "<API key>{component=\'" + this.placeholderKey + "\', fallback=\'" + this.fallback + "\', siblings=" + this.siblings + ", style=" + this.getChatStyle() + '}'; } }
- order: 6 `jsx import { QueueAnim, Button } from 'antd'; const Test = React.createClass({ getInitialState() { return { show: true }; }, onClick() { this.setState({ show: !this.state.show }); }, render() { return ( <div> <p className="buttons"> <Button type="primary" onClick={this.onClick}></Button> </p> <QueueAnim type={['right', 'left']}> {this.state.show ? [ <div className="demo-header" key="header"> <div className="logo"> <img width="30" src="https://t.alipayobjects.com/images/rmsweb/T1B9hfXcdvXXXXXXXX.svg" /> <span>logo</span> </div> <QueueAnim component="ul"> <li key="0"></li> <li key="1"></li> <li key="2"></li> <li key="3"></li> <li key="4"></li> </QueueAnim> </div>, <QueueAnim className="demo-content" key="content" delay={300}> <div className="demo-title" key="title"></div> <div className="demo-kp" key="b"> <QueueAnim component="ul"> <li key="0"></li> <li key="1"></li> <li key="2"></li> </QueueAnim> </div> <div className="demo-title" key="title2"></div> <div className="demo-listBox"> <QueueAnim className="demo-list" delay={500}> <div className="title" key="title3"></div> <QueueAnim component="ul" type="bottom" key="li"> <li key="0"></li> <li key="1"></li> <li key="2"></li> <li key="3"></li> <li key="4"></li> </QueueAnim> </QueueAnim> </div> </QueueAnim>, <QueueAnim delay={1000} type="bottom" key="footerBox"> <div className="demo-footer" key="footer"></div> </QueueAnim> ] : null} </QueueAnim> </div> ); } }); ReactDOM.render(<Test />, mountNode); `
class Solution(object): def checkPossibility(self, nums): """ :type nums: List[int] :rtype: bool """ is_modified = False for i in xrange(len(nums) - 1): if nums[i] > nums[i+1]: if is_modified: return False else: if i == 0 or nums[i-1] <= nums[i+1]: nums[i] = nums[i+1] else: nums[i+1] = nums[i] is_modified = True return True
using System; using Cake.Common.Build.Bitrise.Data; using Cake.Core; using Cake.Core.IO; namespace Cake.Common.Build.Bitrise { <summary> Responsible for communicating with Bitrise. </summary> public sealed class BitriseProvider : IBitriseProvider { private readonly ICakeEnvironment _environment; private readonly IProcessRunner _processRunner; <inheritdoc/> public bool IsRunningOnBitrise => !string.IsNullOrWhiteSpace(_environment.<API key>("BITRISE_BUILD_URL")); <inheritdoc/> public <API key> Environment { get; } <summary> Initializes a new instance of the <see cref="BitriseProvider"/> class. </summary> <param name="environment">The environment.</param> <param name="processRunner">The process runner.</param> public BitriseProvider(ICakeEnvironment environment, IProcessRunner processRunner) { _environment = environment ?? throw new <API key>(nameof(environment)); _processRunner = processRunner ?? throw new <API key>(nameof(processRunner)); Environment = new <API key>(_environment); } <inheritdoc/> public void <API key>(string variable, string value) { var arguments = new <API key>() .Append("add") .Append("--key") .Append(variable) .Append("--value") .AppendQuoted(value); var process = _processRunner.Start("envman", new ProcessSettings { Arguments = arguments }); process.WaitForExit(); var exitCode = process.GetExitCode(); if (exitCode != 0) { throw new CakeException($"BitriseProvider <API key> failed ({exitCode})."); } } } }
<?php defined('BX_DOL') or die('hack attempt'); /** * @see BxDolCmts */ class BxDolCmtsQuery extends BxDolDb { protected $_oMain; protected $_sTable; protected $_sTriggerTable; protected $_sTriggerFieldId; protected $_sTriggerFieldTitle; protected $<API key>; protected $_sTableImages; protected $<API key>; protected $_sTableIds; function __construct(&$oMain) { $this->_oMain = $oMain; $aSystem = $this->_oMain->getSystemInfo(); $this->_sTable = $aSystem['table']; $this->_sTriggerTable = $aSystem['trigger_table']; $this->_sTriggerFieldId = $aSystem['trigger_field_id']; $this->_sTriggerFieldTitle = $aSystem['trigger_field_title']; $this-><API key> = $aSystem['<API key>']; $this->_sTableImages = $aSystem['table_images']; $this-><API key> = $aSystem['<API key>']; $this->_sTableIds = $aSystem['table_ids']; parent::__construct(); } function getTableName () { return $this->_sTable; } function getCommentsCountAll ($iId) { $sQuery = $this->prepare("SELECT `{$this-><API key>}` FROM `{$this->_sTriggerTable}` WHERE `{$this->_sTriggerFieldId}` = ?", $iId); return (int)$this->getOne($sQuery); } function getCommentsCount ($iId, $iCmtVParentId = -1, $iAuthorId = 0, $sFilter = '') { $sWhereClause = ''; if((int)$iCmtVParentId >= 0) $sWhereClause .= $this->prepare(" AND `{$this->_sTable}`.`cmt_vparent_id` = ?", $iCmtVParentId); $sJoinClause = ''; switch($sFilter) { case <API key>: case <API key>: $oConnection = BxDolConnection::getObjectInstance($this->_oMain->getConnectionObject($sFilter)); $aQueryParts = $oConnection-><API key>($this->_sTable, 'cmt_author_id', $iAuthorId); $sJoinClause .= ' ' . $aQueryParts['join']; break; case <API key>: $sWhereClause .= $this->prepare(" AND `{$this->_sTable}`.`cmt_author_id` <> ?", $iAuthorId); break; } $sQuery = $this->prepare("SELECT COUNT(*) FROM `{$this->_sTable}` $sJoinClause WHERE `{$this->_sTable}`.`cmt_object_id` = ?" . $sWhereClause, $iId); return (int)$this->getOne($sQuery); } function getComments ($iId, $iCmtVParentId = 0, $iAuthorId = 0, $sFilter = '', $aOrder = array(), $iStart = 0, $iCount = -1) { $sFields = $sJoin = ""; $oVote = $this->_oMain->getVoteObject(0); if($oVote !== false) { $aSql = $oVote->getSqlParts($this->_sTable, 'cmt_id'); $sFields .= $aSql['fields']; $sJoin .= $aSql['join']; } $sWhereParent = ''; if((int)$iCmtVParentId >= 0) $sWhereParent = $this->prepare(" AND `{$this->_sTable}`.`cmt_vparent_id` = ?", $iCmtVParentId); if(in_array($sFilter, array(<API key>, <API key>))) { $oConnection = BxDolConnection::getObjectInstance($this->_oMain->getConnectionObject($sFilter)); $aQueryParts = $oConnection-><API key>($this->_sTable, 'cmt_author_id', $iAuthorId); $sJoin .= ' ' . $aQueryParts['join']; } $sOder = " ORDER BY `{$this->_sTable}`.`cmt_time` ASC"; if(isset($aOrder['by']) && isset($aOrder['way'])) { $aOrder['way'] = strtoupper(in_array($aOrder['way'], array(<API key>, <API key>)) ? $aOrder['way'] : <API key>); switch($aOrder['by']) { case <API key>: $sOder = " ORDER BY `{$this->_sTable}`.`cmt_time` " . $aOrder['way']; break; case <API key>: $sOder = " ORDER BY `{$this->_sTable}`.`cmt_rate` " . $aOrder['way']; break; } } $sLimit = $iCount != -1 ? $this->prepare(" LIMIT ?, ?", (int)$iStart, (int)$iCount) : ''; $sQuery = $this->prepare("SELECT `{$this->_sTable}`.`cmt_id`, `{$this->_sTable}`.`cmt_parent_id`, `{$this->_sTable}`.`cmt_vparent_id`, `{$this->_sTable}`.`cmt_object_id`, `{$this->_sTable}`.`cmt_author_id`, `{$this->_sTable}`.`cmt_level`, `{$this->_sTable}`.`cmt_text`, `{$this->_sTable}`.`cmt_replies`, `{$this->_sTable}`.`cmt_time` $sFields FROM `{$this->_sTable}` $sJoin WHERE `{$this->_sTable}`.`cmt_object_id` = ?" . $sWhereParent . $sOder . $sLimit, $iId); return $this->getAll($sQuery); } function getCommentsBy($aParams = array()) { $aMethod = array('name' => 'getAll', 'params' => array(0 => 'query')); $sSelectClause = $sJoinClause = $sWhereClause = $sOrderClause = $sLimitClause = ""; $sSelectClause = " `{$this->_sTable}`.`cmt_id`, `{$this->_sTable}`.`cmt_parent_id`, `{$this->_sTable}`.`cmt_vparent_id`, `{$this->_sTable}`.`cmt_object_id`, `{$this->_sTable}`.`cmt_author_id`, `{$this->_sTable}`.`cmt_level`, `{$this->_sTable}`.`cmt_text`, `{$this->_sTable}`.`cmt_replies`, `{$this->_sTable}`.`cmt_time`"; if(isset($aParams['object_id'])) $sWhereClause .= $this->prepare(" AND `{$this->_sTable}`.`cmt_object_id` = ?" , (int)$aParams['object_id']); switch($aParams['type']) { case 'latest': if(!empty($aParams['author'])) $sWhereClause .= $this->prepare(" AND `{$this->_sTable}`.`cmt_author_id` " . (isset($aParams['others']) && (int)$aParams['others'] == 1 ? "<>" : "=") . " ?", (int)$aParams['author']); $sOrderClause = "ORDER BY `{$this->_sTable}`.`cmt_time` DESC"; $sLimitClause = isset($aParams['per_page']) ? "LIMIT " . $aParams['start'] . ", " . $aParams['per_page'] : ""; break; } $aMethod['params'][0] = "SELECT " . $sSelectClause . " FROM `{$this->_sTable}` " . $sJoinClause . " WHERE 1 " . $sWhereClause . " " . $sOrderClause . " " . $sLimitClause; return <API key>(array($this, $aMethod['name']), $aMethod['params']); } function getComment ($iId, $iCmtId) { $sFields = $sJoin = ""; $oVote = $this->_oMain->getVoteObject($iCmtId); if($oVote !== false) { $aSql = $oVote->getSqlParts($this->_sTableIds, 'id'); $sFields .= $aSql['fields']; $sJoin .= $aSql['join']; } $sQuery = $this->prepare("SELECT `{$this->_sTable}`.`cmt_id`, `{$this->_sTableIds}`.`id` AS `cmt_unique_id`, `{$this->_sTable}`.`cmt_parent_id`, `{$this->_sTable}`.`cmt_vparent_id`, `{$this->_sTable}`.`cmt_object_id`, `{$this->_sTable}`.`cmt_author_id`, `{$this->_sTable}`.`cmt_level`, `{$this->_sTable}`.`cmt_text`, `{$this->_sTable}`.`cmt_replies`, `{$this->_sTable}`.`cmt_time` $sFields FROM `{$this->_sTable}` LEFT JOIN `{$this->_sTableIds}` ON (`{$this->_sTable}`.`cmt_id` = `{$this->_sTableIds}`.`cmt_id` AND `{$this->_sTableIds}`.`system_id` = ?) $sJoin WHERE `{$this->_sTable}`.`cmt_object_id` = ? AND `{$this->_sTable}`.`cmt_id` = ? LIMIT 1", $this->_oMain->getSystemId(), $iId, $iCmtId); return $this->getRow($sQuery); } function getCommentSimple ($iId, $iCmtId) { $sQuery = $this->prepare("SELECT * FROM {$this->_sTable} AS `c` WHERE `cmt_object_id` = ? AND `cmt_id` = ? LIMIT 1", $iId, $iCmtId); return $this->getRow($sQuery); } function removeComment ($iId, $iCmtId, $iCmtParentId) { $sQuery = $this->prepare("DELETE FROM {$this->_sTable} WHERE `cmt_object_id` = ? AND `cmt_id` = ? LIMIT 1", $iId, $iCmtId); if (!$this->query($sQuery)) return false; if($iCmtParentId) $this->updateRepliesCount($iCmtParentId, -1); return true; } function saveImages($iSystemId, $iCmtId, $iImageId) { $sQuery = $this->prepare("INSERT IGNORE INTO `{$this-><API key>}` SET `system_id`=?, `cmt_id`=?, `image_id`=?", $iSystemId, $iCmtId, $iImageId); return (int)$this->query($sQuery) > 0; } function getImages($iSystemId, $iCmtId, $iId = false) { $sJoin = ''; $sWhere = $this->prepare(" AND `i`.`system_id` = ? ", $iSystemId); if (false !== $iCmtId) { $sWhere .= $this->prepare(" AND `i`.`cmt_id` = ? ", $iCmtId); } if (false !== $iId) { $sWhere .= $this->prepare(" AND `c`.`cmt_object_id` = ?", $iId); $sJoin .= " INNER JOIN `{$this->_sTable}` AS `c` ON (`i`.`cmt_id` = `c`.`cmt_id`) "; } return $this->getAll("SELECT * FROM `{$this-><API key>}` AS `i` " . $sJoin . " WHERE 1 " . $sWhere); } function deleteImages($iSystemId, $iCmtId) { $sWhereAddon = ''; if (false !== $iCmtId) $sWhereAddon = $this->prepare(" AND `cmt_id` = ? ", $iCmtId); $sQuery = $this->prepare("DELETE FROM `{$this-><API key>}` WHERE `system_id` = ?", $iSystemId); $sQuery .= $sWhereAddon; return $this->query($sQuery); } function updateRepliesCount($iCmtId, $iCount) { $sQuery = $this->prepare("UPDATE `{$this->_sTable}` SET `cmt_replies`=`cmt_replies`+? WHERE `cmt_id`=? LIMIT 1", $iCount, $iCmtId); return $this->query($sQuery); } function <API key> ($iAuthorId, &$aFiles = null, &$aCmtIds = null) { $aSystem = $this->_oMain->getSystemInfo(); $isDelOccured = 0; $sQuery = $this->prepare("SELECT `cmt_id`, `cmt_parent_id` FROM {$this->_sTable} WHERE `cmt_author_id` = ? AND `cmt_replies` = 0", $iAuthorId); $a = $this->getAll ($sQuery); for ( reset($a) ; list (, $r) = each ($a) ; ) { $sQuery = $this->prepare("DELETE FROM {$this->_sTable} WHERE `cmt_id` = ?", $r['cmt_id']); $this->query ($sQuery); $sQuery = $this->prepare("UPDATE {$this->_sTable} SET `cmt_replies` = `cmt_replies` - 1 WHERE `cmt_id` = ?", $r['cmt_parent_id']); $this->query ($sQuery); $aFilesMore = $this->convertImagesArray($this->getImages($aSystem['system_id'], $r['cmt_id'])); $this->deleteImages($aSystem['system_id'], $r['cmt_id']); if ($aFilesMore && null !== $aFiles) $aFiles = array_merge($aFiles, $aFilesMore); if (null !== $aCmtIds) $aCmtIds[] = $r['cmt_id']; $isDelOccured = 1; } $sQuery = $this->prepare("UPDATE {$this->_sTable} SET `cmt_author_id` = 0 WHERE `cmt_author_id` = ? AND `cmt_replies` != 0", $iAuthorId); $this->query ($sQuery); if ($isDelOccured) $this->query ("OPTIMIZE TABLE {$this->_sTable}"); } function <API key> ($iObjectId, &$aFilesReturn = null, &$aCmtIds = null) { $aSystem = $this->_oMain->getSystemInfo(); $aFiles = $this->convertImagesArray($this->getImages($aSystem['system_id'], false, $iObjectId)); if ($aFiles) { $sQuery = $this->prepare("DELETE FROM {$this-><API key>} WHERE `system_id` = ? ", $aSystem['system_id']); $sQuery .= " AND `image_id` IN(" . $this->implode_escape($aFiles) . ") "; $this->query ($sQuery); } if (null !== $aCmtIds) { $sQuery = $this->prepare("SELECT `cmt_id` FROM {$this->_sTable} WHERE `cmt_object_id` = ?", $iObjectId); $aCmtIds = $this->getColumn ($sQuery); } $sQuery = $this->prepare("DELETE FROM {$this->_sTable} WHERE `cmt_object_id` = ?", $iObjectId); $this->query ($sQuery); $this->query ("OPTIMIZE TABLE {$this->_sTable}"); if (null !== $aFilesReturn) $aFilesReturn = $aFiles; } function deleteAll ($iSystemId, &$aFiles = null, &$aCmtIds = null) { // get files if (null !== $aFiles) $aFiles = $this->convertImagesArray($this->getImages($iSystemId, false)); // delete files $this->deleteImages($iSystemId, false); if (null !== $aCmtIds) $aCmtIds = $this->getColumn ("SELECT `cmt_id` FROM {$this->_sTable}"); // delete comments $sQuery = $this->prepare("TRUNCATE TABLE {$this->_sTable}"); $this->query ($sQuery); } function deleteCmtIds ($iSystemId, $iCmtId) { $sQuery = $this->prepare("DELETE FROM {$this->_sTableIds} WHERE `system_id` = ? AND `cmt_id` = ?", $iSystemId, $iCmtId); return $this->query ($sQuery); } function getObjectTitle($iId) { $sQuery = $this->prepare("SELECT `{$this->_sTriggerFieldTitle}` FROM `{$this->_sTriggerTable}` WHERE `{$this->_sTriggerFieldId}` = ? LIMIT 1", $iId); return $this->getOne($sQuery); } function updateTriggerTable($iId, $iCount) { $sQuery = $this->prepare("UPDATE `{$this->_sTriggerTable}` SET `{$this-><API key>}` = ? WHERE `{$this->_sTriggerFieldId}` = ? LIMIT 1", $iCount, $iId); return $this->query($sQuery); } function getUniqId($iSystemId, $iCmtId) { $sQuery = $this->prepare("SELECT `id` FROM `{$this->_sTableIds}` WHERE `system_id` = ? AND `cmt_id` = ?", $iSystemId, $iCmtId); if ($iUniqId = $this->getOne($sQuery)) return $iUniqId; $sQuery = $this->prepare("INSERT INTO `{$this->_sTableIds}` SET `system_id` = ?, `cmt_id` = ?", $iSystemId, $iCmtId); if (!$this->query($sQuery)) return false; return $this->lastId(); } protected function convertImagesArray($a) { if (!$a || !is_array($a)) return array(); $aFiles = array (); foreach ($a as $aFile) $aFiles[] = $aFile['image_id']; return $aFiles; } }
cc.CustomRenderCmd = function (target, func) { this._needDraw = true; this._target = target; this._callback = func; this.rendering = function (ctx, scaleX, scaleY) { if (!this._callback) return; this._callback.call(this._target, ctx, scaleX, scaleY); } }; cc.Node._dirtyFlags = {transformDirty: 1 << 0, visibleDirty: 1 << 1, colorDirty: 1 << 2, opacityDirty: 1 << 3, cacheDirty: 1 << 4, orderDirty: 1 << 5, textDirty: 1 << 6, gradientDirty:1 << 7, all: (1 << 8) - 1}; cc.Node.RenderCmd = function(renderable){ this._dirtyFlag = 1; //need update the transform at first. this._node = renderable; this._needDraw = false; this.<API key> = new cc.Point(0,0); this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; this._inverse = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; this._displayedOpacity = 255; this._displayedColor = cc.color(255, 255, 255, 255); this.<API key> = false; this.<API key> = false; this._curLevel = -1; }; cc.Node.RenderCmd.prototype = { constructor: cc.Node.RenderCmd, <API key>: function(){ return cc.p(this.<API key>); }, getDisplayedColor: function(){ var tmpColor = this._displayedColor; return cc.color(tmpColor.r, tmpColor.g, tmpColor.b, tmpColor.a); }, getDisplayedOpacity: function(){ return this._displayedOpacity; }, <API key>: function(){ this.<API key> = true; this.setDirtyFlag(cc.Node._dirtyFlags.colorDirty); }, <API key>:function(){ this.<API key> = true; this.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty); }, <API key>: function(){ if(this._dirtyFlag & cc.Node._dirtyFlags.transformDirty) this._inverse = cc.<API key>(this.<API key>()); return this._inverse; }, detachFromParent: function(){}, <API key>: function() { var locAPP = this.<API key>, locSize = this._node._contentSize, locAnchorPoint = this._node._anchorPoint; locAPP.x = locSize.width * locAnchorPoint.x; locAPP.y = locSize.height * locAnchorPoint.y; this.setDirtyFlag(cc.Node._dirtyFlags.transformDirty); }, setDirtyFlag: function(dirtyFlag){ if (this._dirtyFlag === 0 && dirtyFlag !== 0) cc.renderer.pushDirtyNode(this); this._dirtyFlag |= dirtyFlag; }, getParentRenderCmd: function(){ if(this._node && this._node._parent && this._node._parent._renderCmd) return this._node._parent._renderCmd; return null; }, _updateDisplayColor: function (parentColor) { var node = this._node; var locDispColor = this._displayedColor, locRealColor = node._realColor; var i, len, selChildren, item; if (this.<API key> && !node.<API key>) { locDispColor.r = locRealColor.r; locDispColor.g = locRealColor.g; locDispColor.b = locRealColor.b; var whiteColor = new cc.Color(255, 255, 255, 255); selChildren = node._children; for (i = 0, len = selChildren.length; i < len; i++) { item = selChildren[i]; if (item && item._renderCmd) item._renderCmd._updateDisplayColor(whiteColor); } this.<API key> = false; } else { if (parentColor === undefined) { var locParent = node._parent; if (locParent && locParent.<API key>) parentColor = locParent.getDisplayedColor(); else parentColor = cc.color.WHITE; } locDispColor.r = 0 | (locRealColor.r * parentColor.r / 255.0); locDispColor.g = 0 | (locRealColor.g * parentColor.g / 255.0); locDispColor.b = 0 | (locRealColor.b * parentColor.b / 255.0); if (node.<API key>) { selChildren = node._children; for (i = 0, len = selChildren.length; i < len; i++) { item = selChildren[i]; if (item && item._renderCmd){ item._renderCmd._updateDisplayColor(locDispColor); item._renderCmd._updateColor(); } } } } this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.colorDirty ^ this._dirtyFlag; }, <API key>: function (parentOpacity) { var node = this._node; var i, len, selChildren, item; if (this.<API key> && !node.<API key>) { this._displayedOpacity = node._realOpacity; selChildren = node._children; for (i = 0, len = selChildren.length; i < len; i++) { item = selChildren[i]; if (item && item._renderCmd) item._renderCmd.<API key>(255); } this.<API key> = false; } else { if (parentOpacity === undefined) { var locParent = node._parent; parentOpacity = 255; if (locParent && locParent.<API key>) parentOpacity = locParent.getDisplayedOpacity(); } this._displayedOpacity = node._realOpacity * parentOpacity / 255.0; if (node.<API key>) { selChildren = node._children; for (i = 0, len = selChildren.length; i < len; i++) { item = selChildren[i]; if (item && item._renderCmd){ item._renderCmd.<API key>(this._displayedOpacity); item._renderCmd._updateColor(); } } } } this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.opacityDirty ^ this._dirtyFlag; }, _syncDisplayColor : function (parentColor) { var node = this._node, locDispColor = this._displayedColor, locRealColor = node._realColor; if (parentColor === undefined) { var locParent = node._parent; if (locParent && locParent.<API key>) parentColor = locParent.getDisplayedColor(); else parentColor = cc.color.WHITE; } locDispColor.r = 0 | (locRealColor.r * parentColor.r / 255.0); locDispColor.g = 0 | (locRealColor.g * parentColor.g / 255.0); locDispColor.b = 0 | (locRealColor.b * parentColor.b / 255.0); }, _syncDisplayOpacity : function (parentOpacity) { var node = this._node; if (parentOpacity === undefined) { var locParent = node._parent; parentOpacity = 255; if (locParent && locParent.<API key>) parentOpacity = locParent.getDisplayedOpacity(); } this._displayedOpacity = node._realOpacity * parentOpacity / 255.0; }, _updateColor: function(){}, updateStatus: function () { var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; var colorDirty = locFlag & flags.colorDirty, opacityDirty = locFlag & flags.opacityDirty; if(colorDirty) this._updateDisplayColor(); if(opacityDirty) this.<API key>(); if(colorDirty || opacityDirty) this._updateColor(); if(locFlag & flags.transformDirty){ //update the transform this.transform(this.getParentRenderCmd(), true); this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.transformDirty ^ this._dirtyFlag; } } }; (function() { //The cc.Node's render command for Canvas cc.Node.CanvasRenderCmd = function (renderable) { cc.Node.RenderCmd.call(this, renderable); this._cachedParent = null; this._cacheDirty = false; }; var proto = cc.Node.CanvasRenderCmd.prototype = Object.create(cc.Node.RenderCmd.prototype); proto.constructor = cc.Node.CanvasRenderCmd; proto.transform = function (parentCmd, recursive) { // transform for canvas var t = this.<API key>(), worldT = this._worldTransform; //get the world transform this._cacheDirty = true; if (parentCmd) { var pt = parentCmd._worldTransform; // cc.<API key> is incorrect at get world transform worldT.a = t.a * pt.a + t.b * pt.c; worldT.b = t.a * pt.b + t.b * pt.d; worldT.c = t.c * pt.a + t.d * pt.c; worldT.d = t.c * pt.b + t.d * pt.d; worldT.tx = pt.a * t.tx + pt.c * t.ty + pt.tx; worldT.ty = pt.d * t.ty + pt.ty + pt.b * t.tx; } else { worldT.a = t.a; worldT.b = t.b; worldT.c = t.c; worldT.d = t.d; worldT.tx = t.tx; worldT.ty = t.ty; } if (recursive) { var locChildren = this._node._children; if (!locChildren || locChildren.length === 0) return; var i, len; for (i = 0, len = locChildren.length; i < len; i++) { locChildren[i]._renderCmd.transform(this, recursive); } } }; proto.<API key> = function () { var node = this._node, normalizeDirty = false; if (node.<API key> && node._parent) { //TODO need refactor var conSize = node._parent._contentSize; node._position.x = node._normalizedPosition.x * conSize.width; node._position.y = node._normalizedPosition.y * conSize.height; node.<API key> = false; normalizeDirty = true; } if (normalizeDirty || (this._dirtyFlag & cc.Node._dirtyFlags.transformDirty)) { var t = this._transform;// quick reference // base position t.tx = node._position.x; t.ty = node._position.y; // rotation Cos and Sin var a = 1, b = 0, c = 0, d = 1; if (node._rotationX) { var rotationRadiansX = node._rotationX * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance c = Math.sin(rotationRadiansX); d = Math.cos(rotationRadiansX); } if (node._rotationY) { var rotationRadiansY = node._rotationY * 0.017453292519943295; //0.017453292519943295 = (Math.PI / 180); for performance a = Math.cos(rotationRadiansY); b = -Math.sin(rotationRadiansY); } t.a = a; t.b = b; t.c = c; t.d = d; var lScaleX = node._scaleX, lScaleY = node._scaleY; var appX = this.<API key>.x, appY = this.<API key>.y; // Firefox on Vista and XP crashes // GPU thread in case of scale(0.0, 0.0) var sx = (lScaleX < 0.000001 && lScaleX > -0.000001) ? 0.000001 : lScaleX, sy = (lScaleY < 0.000001 && lScaleY > -0.000001) ? 0.000001 : lScaleY; // scale if (lScaleX !== 1 || lScaleY !== 1) { a = t.a *= sx; b = t.b *= sx; c = t.c *= sy; d = t.d *= sy; } // skew if (node._skewX || node._skewY) { // offset the anchorpoint var skx = Math.tan(-node._skewX * Math.PI / 180); var sky = Math.tan(-node._skewY * Math.PI / 180); if (skx === Infinity) skx = 99999999; if (sky === Infinity) sky = 99999999; var xx = appY * skx; var yy = appX * sky; t.a = a - c * sky; t.b = b - d * sky; t.c = c - a * skx; t.d = d - b * skx; t.tx += a * xx + c * yy; t.ty += b * xx + d * yy; } // adjust anchorPoint t.tx -= a * appX + c * appY; t.ty -= b * appX + d * appY; // if ignore anchorPoint if (node.<API key>) { t.tx += appX; t.ty += appY; } if (node.<API key>) this._transform = cc.<API key>(t, node.<API key>); } return this._transform; }; proto.visit = function (parentCmd) { var node = this._node; // quick return if not visible if (!node._visible) return; parentCmd = parentCmd || this.getParentRenderCmd(); if (parentCmd) this._curLevel = parentCmd._curLevel + 1; //visit for canvas var i, children = node._children, child; this._syncStatus(parentCmd); var len = children.length; if (len > 0) { node.sortAllChildren(); // draw children zOrder < 0 for (i = 0; i < len; i++) { child = children[i]; if (child._localZOrder < 0) child._renderCmd.visit(this); else break; } cc.renderer.pushRenderCommand(this); for (; i < len; i++) children[i]._renderCmd.visit(this); } else { cc.renderer.pushRenderCommand(this); } this._dirtyFlag = 0; }; proto._syncStatus = function (parentCmd) { // In the visit logic does not restore the _dirtyFlag // Because child elements need parent's _dirtyFlag to change himself var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag; var parentNode = parentCmd ? parentCmd._node : null; // There is a possibility: // The parent element changed color, child element not change // This will cause the parent element changed color // But while the child element does not enter the circulation // Here will be reset state in last // In order the child elements get the parent state if(parentNode && parentNode.<API key> && (parentCmd._dirtyFlag & flags.colorDirty)) locFlag |= flags.colorDirty; if(parentNode && parentNode.<API key> && (parentCmd._dirtyFlag & flags.opacityDirty)) locFlag |= flags.opacityDirty; if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty)) locFlag |= flags.transformDirty; var colorDirty = locFlag & flags.colorDirty, opacityDirty = locFlag & flags.opacityDirty, transformDirty = locFlag & flags.transformDirty; this._dirtyFlag = locFlag; if (colorDirty) //update the color this._syncDisplayColor(); if (opacityDirty) //update the opacity this._syncDisplayOpacity(); if(colorDirty) this._updateColor(); if (transformDirty){ //update the transform this.transform(parentCmd); } }; proto.setDirtyFlag = function (dirtyFlag) { cc.Node.RenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag); this._setCacheDirty(); //TODO it should remove from here. if(this._cachedParent) this._cachedParent.setDirtyFlag(dirtyFlag); }; proto._setCacheDirty = function () { if (this._cacheDirty === false) { this._cacheDirty = true; var cachedP = this._cachedParent; cachedP && cachedP !== this && cachedP.<API key> && cachedP.<API key>(); } }; proto._setCachedParent = function (cachedParent) { if (this._cachedParent === cachedParent) return; this._cachedParent = cachedParent; var children = this._node._children; for (var i = 0, len = children.length; i < len; i++) children[i]._renderCmd._setCachedParent(cachedParent); }; proto.detachFromParent = function () { this._cachedParent = null; var selChildren = this._node._children, item; for (var i = 0, len = selChildren.length; i < len; i++) { item = selChildren[i]; if (item && item._renderCmd) item._renderCmd.detachFromParent(); } }; proto.setShaderProgram = function (shaderProgram) { //do nothing. }; proto.getShaderProgram = function () { return null; }; //util functions cc.Node.CanvasRenderCmd.<API key> = function (blendFunc) { if (!blendFunc) return "source-over"; else { if (( blendFunc.src === cc.SRC_ALPHA && blendFunc.dst === cc.ONE) || (blendFunc.src === cc.ONE && blendFunc.dst === cc.ONE)) return "lighter"; else if (blendFunc.src === cc.ZERO && blendFunc.dst === cc.SRC_ALPHA) return "destination-in"; else if (blendFunc.src === cc.ZERO && blendFunc.dst === cc.ONE_MINUS_SRC_ALPHA) return "destination-out"; else return "source-over"; } }; })();
// <auto-generated/> #nullable disable using System; using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; using Azure.Core; namespace Azure.Analytics.Synapse.Artifacts.Models { [JsonConverter(typeof(<API key>))] public partial class CopyActivity : <API key> { void <API key>.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsCollectionDefined(Inputs)) { writer.WritePropertyName("inputs"); writer.WriteStartArray(); foreach (var item in Inputs) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Optional.IsCollectionDefined(Outputs)) { writer.WritePropertyName("outputs"); writer.WriteStartArray(); foreach (var item in Outputs) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Optional.IsDefined(LinkedServiceName)) { writer.WritePropertyName("linkedServiceName"); writer.WriteObjectValue(LinkedServiceName); } if (Optional.IsDefined(Policy)) { writer.WritePropertyName("policy"); writer.WriteObjectValue(Policy); } writer.WritePropertyName("name"); writer.WriteStringValue(Name); writer.WritePropertyName("type"); writer.WriteStringValue(Type); if (Optional.IsDefined(Description)) { writer.WritePropertyName("description"); writer.WriteStringValue(Description); } if (Optional.IsCollectionDefined(DependsOn)) { writer.WritePropertyName("dependsOn"); writer.WriteStartArray(); foreach (var item in DependsOn) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Optional.IsCollectionDefined(UserProperties)) { writer.WritePropertyName("userProperties"); writer.WriteStartArray(); foreach (var item in UserProperties) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } writer.WritePropertyName("typeProperties"); writer.WriteStartObject(); writer.WritePropertyName("source"); writer.WriteObjectValue(Source); writer.WritePropertyName("sink"); writer.WriteObjectValue(Sink); if (Optional.IsDefined(Translator)) { writer.WritePropertyName("translator"); writer.WriteObjectValue(Translator); } if (Optional.IsDefined(EnableStaging)) { writer.WritePropertyName("enableStaging"); writer.WriteObjectValue(EnableStaging); } if (Optional.IsDefined(StagingSettings)) { writer.WritePropertyName("stagingSettings"); writer.WriteObjectValue(StagingSettings); } if (Optional.IsDefined(ParallelCopies)) { writer.WritePropertyName("parallelCopies"); writer.WriteObjectValue(ParallelCopies); } if (Optional.IsDefined(<API key>)) { writer.WritePropertyName("<API key>"); writer.WriteObjectValue(<API key>); } if (Optional.IsDefined(<API key>)) { writer.WritePropertyName("<API key>"); writer.WriteObjectValue(<API key>); } if (Optional.IsDefined(<API key>)) { writer.WritePropertyName("<API key>"); writer.WriteObjectValue(<API key>); } if (Optional.IsDefined(LogStorageSettings)) { writer.WritePropertyName("logStorageSettings"); writer.WriteObjectValue(LogStorageSettings); } if (Optional.IsDefined(LogSettings)) { writer.WritePropertyName("logSettings"); writer.WriteObjectValue(LogSettings); } if (Optional.IsCollectionDefined(PreserveRules)) { writer.WritePropertyName("preserveRules"); writer.WriteStartArray(); foreach (var item in PreserveRules) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Optional.IsCollectionDefined(Preserve)) { writer.WritePropertyName("preserve"); writer.WriteStartArray(); foreach (var item in Preserve) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Optional.IsDefined(<API key>)) { writer.WritePropertyName("<API key>"); writer.WriteObjectValue(<API key>); } if (Optional.IsDefined(SkipErrorFile)) { writer.WritePropertyName("skipErrorFile"); writer.WriteObjectValue(SkipErrorFile); } writer.WriteEndObject(); foreach (var item in <API key>) { writer.WritePropertyName(item.Key); writer.WriteObjectValue(item.Value); } writer.WriteEndObject(); } internal static CopyActivity <API key>(JsonElement element) { Optional<IList<DatasetReference>> inputs = default; Optional<IList<DatasetReference>> outputs = default; Optional<<API key>> linkedServiceName = default; Optional<ActivityPolicy> policy = default; string name = default; string type = default; Optional<string> description = default; Optional<IList<ActivityDependency>> dependsOn = default; Optional<IList<UserProperty>> userProperties = default; CopySource source = default; CopySink sink = default; Optional<object> translator = default; Optional<object> enableStaging = default; Optional<StagingSettings> stagingSettings = default; Optional<object> parallelCopies = default; Optional<object> <API key> = default; Optional<object> <API key> = default; Optional<<API key>> <API key> = default; Optional<LogStorageSettings> logStorageSettings = default; Optional<LogSettings> logSettings = default; Optional<IList<object>> preserveRules = default; Optional<IList<object>> preserve = default; Optional<object> <API key> = default; Optional<SkipErrorFile> skipErrorFile = default; IDictionary<string, object> <API key> = default; Dictionary<string, object> <API key> = new Dictionary<string, object>(); foreach (var property in element.EnumerateObject()) { if (property.NameEquals("inputs")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.<API key>(); continue; } List<DatasetReference> array = new List<DatasetReference>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(DatasetReference.<API key>(item)); } inputs = array; continue; } if (property.NameEquals("outputs")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.<API key>(); continue; } List<DatasetReference> array = new List<DatasetReference>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(DatasetReference.<API key>(item)); } outputs = array; continue; } if (property.NameEquals("linkedServiceName")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.<API key>(); continue; } linkedServiceName = <API key>.<API key>(property.Value); continue; } if (property.NameEquals("policy")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.<API key>(); continue; } policy = ActivityPolicy.<API key>(property.Value); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("description")) { description = property.Value.GetString(); continue; } if (property.NameEquals("dependsOn")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.<API key>(); continue; } List<ActivityDependency> array = new List<ActivityDependency>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(ActivityDependency.<API key>(item)); } dependsOn = array; continue; } if (property.NameEquals("userProperties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.<API key>(); continue; } List<UserProperty> array = new List<UserProperty>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(UserProperty.<API key>(item)); } userProperties = array; continue; } if (property.NameEquals("typeProperties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.<API key>(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("source")) { source = CopySource.<API key>(property0.Value); continue; } if (property0.NameEquals("sink")) { sink = CopySink.DeserializeCopySink(property0.Value); continue; } if (property0.NameEquals("translator")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } translator = property0.Value.GetObject(); continue; } if (property0.NameEquals("enableStaging")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } enableStaging = property0.Value.GetObject(); continue; } if (property0.NameEquals("stagingSettings")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } stagingSettings = StagingSettings.<API key>(property0.Value); continue; } if (property0.NameEquals("parallelCopies")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } parallelCopies = property0.Value.GetObject(); continue; } if (property0.NameEquals("<API key>")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } <API key> = property0.Value.GetObject(); continue; } if (property0.NameEquals("<API key>")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } <API key> = property0.Value.GetObject(); continue; } if (property0.NameEquals("<API key>")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } <API key> = <API key>.<API key>(property0.Value); continue; } if (property0.NameEquals("logStorageSettings")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } logStorageSettings = LogStorageSettings.<API key>(property0.Value); continue; } if (property0.NameEquals("logSettings")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } logSettings = LogSettings.<API key>(property0.Value); continue; } if (property0.NameEquals("preserveRules")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } List<object> array = new List<object>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(item.GetObject()); } preserveRules = array; continue; } if (property0.NameEquals("preserve")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } List<object> array = new List<object>(); foreach (var item in property0.Value.EnumerateArray()) { array.Add(item.GetObject()); } preserve = array; continue; } if (property0.NameEquals("<API key>")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } <API key> = property0.Value.GetObject(); continue; } if (property0.NameEquals("skipErrorFile")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.<API key>(); continue; } skipErrorFile = SkipErrorFile.<API key>(property0.Value); continue; } } continue; } <API key>.Add(property.Name, property.Value.GetObject()); } <API key> = <API key>; return new CopyActivity(name, type, description.Value, Optional.ToList(dependsOn), Optional.ToList(userProperties), <API key>, linkedServiceName.Value, policy.Value, Optional.ToList(inputs), Optional.ToList(outputs), source, sink, translator.Value, enableStaging.Value, stagingSettings.Value, parallelCopies.Value, <API key>.Value, <API key>.Value, <API key>.Value, logStorageSettings.Value, logSettings.Value, Optional.ToList(preserveRules), Optional.ToList(preserve), <API key>.Value, skipErrorFile.Value); } internal partial class <API key> : JsonConverter<CopyActivity> { public override void Write(Utf8JsonWriter writer, CopyActivity model, <API key> options) { writer.WriteObjectValue(model); } public override CopyActivity Read(ref Utf8JsonReader reader, Type typeToConvert, <API key> options) { using var document = JsonDocument.ParseValue(ref reader); return <API key>(document.RootElement); } } } }
#!/bin/bash os=linux export scripts_dir=$PWD/scripts/$os function usage() { echo "Option for subcommand 'deploy|start|stop|clean" echo " -s|--source-dir <dir> local source directory for deployment" echo " -t|--target <dir> remote target directory for deployment" echo " -d|--deploy-name <name> deployment name to be deployed, like simple_kv" } CMD=$1 shift while [ $# -gt 0 ];do #TODO: this may cause infinit loop when parameters are invalid key=$1 case $key in -h|--help) usage exit 0 ;; -s|--source-dir) s_dir=$2 shift 2 ;; -t|--target-dir) t_dir=$2 shift 2 ;; -d|--deploy-name) d_unit=$2 shift 2 ;; *) echo "ERROR: unknown option $key" echo usage exit -1 ;; esac done if [ -z $s_dir ] || [ -z $t_dir ]|| [ -z $d_unit ];then usage exit -1 fi if [ ! -d $s_dir ];then echo "$s_dir no such directory" exit -1 fi applist=$(cat ${s_dir}/applist) #$1 machine $2 app function deploy_files(){ echo "deploy $s_dir/$2 to $t_dir at $1" ssh $1 "mkdir -p ${t_dir}/$2"
require 'rails_helper' RSpec.describe Tournament, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
<?php defined('BX_DOL') or die('hack attempt'); /** * @see BxDolVote */ class BxDolVoteLikesQuery extends BxDolVoteQuery { public function __construct(&$oModule) { parent::__construct($oModule); } }
class Gws::Schedule::TodoLimit Base = Struct.new(:id, :name) class OutDated < Base def initialize(threshold) super("out_dated", I18n.t("gws/schedule/todo.header.out_dated")) @threshold = threshold end def collect(items) items.select { |item| item.end_at < @threshold } end end class Today < Base def initialize(threshold) super("today", I18n.t("gws/schedule/todo.header.today")) @threshold_from = threshold @threshold_to = threshold + 1.day end def name "#{super} - #{I18n.l(@threshold_from.to_date)}" end def collect(items) items.select { |item| @threshold_from <= item.end_at && item.end_at < @threshold_to } end end class Tomorrow < Base def initialize(threshold) super("tomorrow", I18n.t("gws/schedule/todo.header.tomorrow")) @threshold_from = threshold + 1.day @threshold_to = @threshold_from + 1.day end def name "#{super} - #{I18n.l(@threshold_from.to_date)}" end def collect(items) items.select { |item| @threshold_from <= item.end_at && item.end_at < @threshold_to } end end class DayAfterTomorrow < Base def initialize(threshold) super("day_after_tomorrow", I18n.t("gws/schedule/todo.header.day_after_tomorrow")) @threshold = threshold + 2.days end def collect(items) items.select { |item| @threshold <= item.end_at } end end class << self def get(type, threshold) case type when :out_dated OutDated.new(threshold) when :today Today.new(threshold) when :tomorrow Tomorrow.new(threshold) when :day_after_tomorrow DayAfterTomorrow.new(threshold) end end end end
#include "coincontroldialog.h" #include "<API key>.h" #include "init.h" #include "bitcoinunits.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "optionsmodel.h" #include "coincontrol.h" #include <QApplication> #include <QCheckBox> #include <QClipboard> #include <QColor> #include <QCursor> #include <QDateTime> #include <QDialogButtonBox> #include <QFlags> #include <QIcon> #include <QString> #include <QTreeWidget> #include <QTreeWidgetItem> using namespace std; QList<std::pair<QString, qint64> > CoinControlDialog::payAddresses; CCoinControl* CoinControlDialog::coinControl = new CCoinControl(); CoinControlDialog::CoinControlDialog(QWidget *parent) : QDialog(parent), ui(new Ui::CoinControlDialog), model(0) { ui->setupUi(this); // context menu actions QAction *copyAddressAction = new QAction(tr("Copy address"), this); QAction *copyLabelAction = new QAction(tr("Copy label"), this); QAction *copyAmountAction = new QAction(tr("Copy amount"), this); <API key> = new QAction(tr("Copy transaction ID"), this); // we need to enable/disable this //lockAction = new QAction(tr("Lock unspent"), this); // we need to enable/disable this //unlockAction = new QAction(tr("Unlock unspent"), this); // we need to enable/disable this // context menu contextMenu = new QMenu(); contextMenu->addAction(copyAddressAction); contextMenu->addAction(copyLabelAction); contextMenu->addAction(copyAmountAction); contextMenu->addAction(<API key>); //contextMenu->addSeparator(); //contextMenu->addAction(lockAction); //contextMenu->addAction(unlockAction); // context menu signals connect(ui->treeWidget, SIGNAL(<API key>(QPoint)), this, SLOT(showMenu(QPoint))); connect(copyAddressAction, SIGNAL(triggered()), this, SLOT(copyAddress())); connect(copyLabelAction, SIGNAL(triggered()), this, SLOT(copyLabel())); connect(copyAmountAction, SIGNAL(triggered()), this, SLOT(copyAmount())); connect(<API key>, SIGNAL(triggered()), this, SLOT(copyTransactionHash())); //connect(lockAction, SIGNAL(triggered()), this, SLOT(lockCoin())); //connect(unlockAction, SIGNAL(triggered()), this, SLOT(unlockCoin())); // clipboard actions QAction *<API key> = new QAction(tr("Copy quantity"), this); QAction *<API key> = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *<API key> = new QAction(tr("Copy after fee"), this); QAction *<API key> = new QAction(tr("Copy bytes"), this); QAction *<API key> = new QAction(tr("Copy priority"), this); QAction *<API key> = new QAction(tr("Copy low output"), this); QAction *<API key> = new QAction(tr("Copy change"), this); connect(<API key>, SIGNAL(triggered()), this, SLOT(clipboardQuantity())); connect(<API key>, SIGNAL(triggered()), this, SLOT(clipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(clipboardFee())); connect(<API key>, SIGNAL(triggered()), this, SLOT(clipboardAfterFee())); connect(<API key>, SIGNAL(triggered()), this, SLOT(clipboardBytes())); connect(<API key>, SIGNAL(triggered()), this, SLOT(clipboardPriority())); connect(<API key>, SIGNAL(triggered()), this, SLOT(clipboardLowOutput())); connect(<API key>, SIGNAL(triggered()), this, SLOT(clipboardChange())); ui-><API key>->addAction(<API key>); ui-><API key>->addAction(<API key>); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui-><API key>->addAction(<API key>); ui-><API key>->addAction(<API key>); ui-><API key>->addAction(<API key>); ui-><API key>->addAction(<API key>); ui-><API key>->addAction(<API key>); // toggle tree/list mode connect(ui->radioTreeMode, SIGNAL(toggled(bool)), this, SLOT(radioTreeMode(bool))); connect(ui->radioListMode, SIGNAL(toggled(bool)), this, SLOT(radioListMode(bool))); // click on checkbox connect(ui->treeWidget, SIGNAL(itemChanged( QTreeWidgetItem*, int)), this, SLOT(viewItemChanged( QTreeWidgetItem*, int))); // click on header ui->treeWidget->header()->setClickable(true); connect(ui->treeWidget->header(), SIGNAL(sectionClicked(int)), this, SLOT(<API key>(int))); // ok button connect(ui->buttonBox, SIGNAL(clicked( QAbstractButton*)), this, SLOT(buttonBoxClicked(QAbstractButton*))); // (un)select all connect(ui->pushButtonSelectAll, SIGNAL(clicked()), this, SLOT(<API key>())); // change coin control first column label due Qt4 bug. ui->treeWidget->headerItem()->setText(COLUMN_CHECKBOX, QString()); ui->treeWidget->setColumnWidth(COLUMN_CHECKBOX, 84); ui->treeWidget->setColumnWidth(COLUMN_AMOUNT, 100); ui->treeWidget->setColumnWidth(COLUMN_LABEL, 170); ui->treeWidget->setColumnWidth(COLUMN_ADDRESS, 290); ui->treeWidget->setColumnWidth(COLUMN_DATE, 110); ui->treeWidget->setColumnWidth(<API key>, 100); ui->treeWidget->setColumnWidth(COLUMN_COINAGE, 100); ui->treeWidget->setColumnWidth(COLUMN_PRIORITY, 100); ui->treeWidget->setColumnHidden(COLUMN_TXHASH, true); // store transacton hash in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_VOUT_INDEX, true); // store vout index in this column, but don't show it ui->treeWidget->setColumnHidden(COLUMN_AMOUNT_INT64, true); // store amount int64 in this column, but don't show it ui->treeWidget->setColumnHidden(<API key>, true); // store priority int64 in this column, but don't show it // default view is sorted by amount desc sortView(COLUMN_AMOUNT_INT64, Qt::DescendingOrder); } CoinControlDialog::~CoinControlDialog() { delete ui; } void CoinControlDialog::setModel(WalletModel *model) { this->model = model; if(model && model->getOptionsModel() && model-><API key>()) { updateView(); //updateLabelLocked(); CoinControlDialog::updateLabels(model, this); } } // helper function str_pad QString CoinControlDialog::strPad(QString s, int nPadLength, QString sPadding) { while (s.length() < nPadLength) s = sPadding + s; return s; } // ok button void CoinControlDialog::buttonBoxClicked(QAbstractButton* button) { if (ui->buttonBox->buttonRole(button) == QDialogButtonBox::AcceptRole) done(QDialog::Accepted); // closes the dialog } // (un)select all void CoinControlDialog::<API key>() { Qt::CheckState state = Qt::Checked; for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) { if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != Qt::Unchecked) { state = Qt::Unchecked; break; } } ui->treeWidget->setEnabled(false); for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) != state) ui->treeWidget->topLevelItem(i)->setCheckState(COLUMN_CHECKBOX, state); ui->treeWidget->setEnabled(true); CoinControlDialog::updateLabels(model, this); } // context menu void CoinControlDialog::showMenu(const QPoint &point) { QTreeWidgetItem *item = ui->treeWidget->itemAt(point); if(item) { contextMenuItem = item; // disable some items (like Copy Transaction ID, lock, unlock) for tree roots in context menu if (item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { <API key>->setEnabled(true); //if (model->isLockedCoin(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt())) // lockAction->setEnabled(false); // unlockAction->setEnabled(true); //else // lockAction->setEnabled(true); // unlockAction->setEnabled(false); } else // this means click on parent node in tree mode -> disable all { <API key>->setEnabled(false); //lockAction->setEnabled(false); //unlockAction->setEnabled(false); } // show context menu contextMenu->exec(QCursor::pos()); } } // context menu action: copy amount void CoinControlDialog::copyAmount() { QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_AMOUNT)); } // context menu action: copy label void CoinControlDialog::copyLabel() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_LABEL).length() == 0 && contextMenuItem->parent()) QApplication::clipboard()->setText(contextMenuItem->parent()->text(COLUMN_LABEL)); else QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_LABEL)); } // context menu action: copy address void CoinControlDialog::copyAddress() { if (ui->radioTreeMode->isChecked() && contextMenuItem->text(COLUMN_ADDRESS).length() == 0 && contextMenuItem->parent()) QApplication::clipboard()->setText(contextMenuItem->parent()->text(COLUMN_ADDRESS)); else QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_ADDRESS)); } // context menu action: copy transaction id void CoinControlDialog::copyTransactionHash() { QApplication::clipboard()->setText(contextMenuItem->text(COLUMN_TXHASH)); } // context menu action: lock coin /*void CoinControlDialog::lockCoin() { if (contextMenuItem->checkState(COLUMN_CHECKBOX) == Qt::Checked) contextMenuItem->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->lockCoin(outpt); contextMenuItem->setDisabled(true); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed")); updateLabelLocked(); }*/ // context menu action: unlock coin /*void CoinControlDialog::unlockCoin() { COutPoint outpt(uint256(contextMenuItem->text(COLUMN_TXHASH).toStdString()), contextMenuItem->text(COLUMN_VOUT_INDEX).toUInt()); model->unlockCoin(outpt); contextMenuItem->setDisabled(false); contextMenuItem->setIcon(COLUMN_CHECKBOX, QIcon()); updateLabelLocked(); }*/ // copy label "Quantity" to clipboard void CoinControlDialog::clipboardQuantity() { QApplication::clipboard()->setText(ui-><API key>->text()); } // copy label "Amount" to clipboard void CoinControlDialog::clipboardAmount() { QApplication::clipboard()->setText(ui-><API key>->text().left(ui-><API key>->text().indexOf(" "))); } // copy label "Fee" to clipboard void CoinControlDialog::clipboardFee() { QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // copy label "After fee" to clipboard void CoinControlDialog::clipboardAfterFee() { QApplication::clipboard()->setText(ui-><API key>->text().left(ui-><API key>->text().indexOf(" "))); } // copy label "Bytes" to clipboard void CoinControlDialog::clipboardBytes() { QApplication::clipboard()->setText(ui-><API key>->text()); } // copy label "Priority" to clipboard void CoinControlDialog::clipboardPriority() { QApplication::clipboard()->setText(ui-><API key>->text()); } // copy label "Low output" to clipboard void CoinControlDialog::clipboardLowOutput() { QApplication::clipboard()->setText(ui-><API key>->text()); } // copy label "Change" to clipboard void CoinControlDialog::clipboardChange() { QApplication::clipboard()->setText(ui-><API key>->text().left(ui-><API key>->text().indexOf(" "))); } // treeview: sort void CoinControlDialog::sortView(int column, Qt::SortOrder order) { sortColumn = column; sortOrder = order; ui->treeWidget->sortItems(column, order); ui->treeWidget->header()->setSortIndicator((sortColumn == COLUMN_AMOUNT_INT64 ? COLUMN_AMOUNT : (sortColumn == <API key> ? COLUMN_PRIORITY : sortColumn)), sortOrder); } // treeview: clicked on header void CoinControlDialog::<API key>(int logicalIndex) { if (logicalIndex == COLUMN_CHECKBOX) // click on most left column -> do nothing { ui->treeWidget->header()->setSortIndicator((sortColumn == COLUMN_AMOUNT_INT64 ? COLUMN_AMOUNT : (sortColumn == <API key> ? COLUMN_PRIORITY : sortColumn)), sortOrder); } else { if (logicalIndex == COLUMN_AMOUNT) // sort by amount logicalIndex = COLUMN_AMOUNT_INT64; if (logicalIndex == COLUMN_PRIORITY) // sort by priority logicalIndex = <API key>; if (sortColumn == logicalIndex) sortOrder = ((sortOrder == Qt::AscendingOrder) ? Qt::DescendingOrder : Qt::AscendingOrder); else { sortColumn = logicalIndex; sortOrder = ((sortColumn == COLUMN_AMOUNT_INT64 || sortColumn == <API key> || sortColumn == COLUMN_DATE || sortColumn == <API key>) ? Qt::DescendingOrder : Qt::AscendingOrder); // if amount,date,conf,priority then default => desc, else default => asc } sortView(sortColumn, sortOrder); } } // toggle tree mode void CoinControlDialog::radioTreeMode(bool checked) { if (checked && model) updateView(); } // toggle list mode void CoinControlDialog::radioListMode(bool checked) { if (checked && model) updateView(); } // checkbox clicked by user void CoinControlDialog::viewItemChanged(QTreeWidgetItem* item, int column) { if (column == COLUMN_CHECKBOX && item->text(COLUMN_TXHASH).length() == 64) // transaction hash is 64 characters (this means its a child node, so its not a parent node in tree mode) { COutPoint outpt(uint256(item->text(COLUMN_TXHASH).toStdString()), item->text(COLUMN_VOUT_INDEX).toUInt()); if (item->checkState(COLUMN_CHECKBOX) == Qt::Unchecked) coinControl->UnSelect(outpt); else if (item->isDisabled()) // locked (this happens if "check all" through parent node) item->setCheckState(COLUMN_CHECKBOX, Qt::Unchecked); else coinControl->Select(outpt); // selection changed -> update labels if (ui->treeWidget->isEnabled()) // do not update on every click for (un)select all CoinControlDialog::updateLabels(model, this); } } // helper function, return human readable label for priority number QString CoinControlDialog::getPriorityLabel(double dPriority) { if (dPriority > 576000ULL) // at least medium, this number is from AllowFree(), the other thresholds are kinda random { if (dPriority > 5760000000ULL) return tr("highest"); else if (dPriority > 576000000ULL) return tr("high"); else if (dPriority > 57600000ULL) return tr("medium-high"); else return tr("medium"); } else { if (dPriority > 5760ULL) return tr("low-medium"); else if (dPriority > 58ULL) return tr("low"); else return tr("lowest"); } } // shows count of locked unspent outputs /*void CoinControlDialog::updateLabelLocked() { vector<COutPoint> vOutpts; model->listLockedCoins(vOutpts); if (vOutpts.size() > 0) { ui->labelLocked->setText(tr("(%1 locked)").arg(vOutpts.size())); ui->labelLocked->setVisible(true); } else ui->labelLocked->setVisible(false); }*/ void CoinControlDialog::updateLabels(WalletModel *model, QDialog* dialog) { if (!model) return; // nPayAmount qint64 nPayAmount = 0; bool fLowOutput = false; bool fDust = false; CTransaction txDummy; BOOST_FOREACH(const PAIRTYPE(QString, qint64) &payee, CoinControlDialog::payAddresses) { qint64 amount = payee.second; nPayAmount += amount; if (amount > 0) { if (amount < CENT) fLowOutput = true; } } QString sPriorityLabel = ""; int64 nAmount = 0; int64 nPayFee = 0; int64 nAfterFee = 0; int64 nChange = 0; unsigned int nBytes = 0; unsigned int nBytesInputs = 0; double dPriority = 0; double dPriorityInputs = 0; unsigned int nQuantity = 0; vector<COutPoint> vCoinControl; vector<COutput> vOutputs; coinControl->ListSelected(vCoinControl); model->getOutputs(vCoinControl, vOutputs); nPayFee = nTransactionFee; for (;;) { txDummy.vin.clear(); txDummy.vout.clear(); nQuantity = 0; nAmount = 0; dPriorityInputs = 0; nBytesInputs = 0; // Inputs BOOST_FOREACH(const COutput& out, vOutputs) { // Quantity nQuantity++; // Amount nAmount += out.tx->vout[out.i].nValue; // Priority dPriorityInputs += (double)out.tx->vout[out.i].nValue * (out.nDepth+1); // Bytes txDummy.vin.push_back(CTxIn(out.tx->vout[out.i].GetHash(), out.tx->vout[out.i].nValue)); nBytesInputs += 73; // Future ECDSA signature in DER format } // Outputs BOOST_FOREACH(const PAIRTYPE(QString, qint64) &payee, CoinControlDialog::payAddresses) { QString address = payee.first; qint64 amount = payee.second; CScript scriptPubKey; scriptPubKey.SetDestination(CBitcoinAddress(address.toStdString()).Get()); CTxOut txout(amount, scriptPubKey); txDummy.vout.push_back(txout); } // calculation if (nQuantity > 0) { nChange = nAmount - nPayAmount - nPayFee; // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE // or until nChange becomes zero // NOTE: this depends on the exact behaviour of GetMinFee if (nPayFee < MIN_TX_FEE && nChange > 0 && nChange < CENT) { int64 nMoveToFee = min(nChange, MIN_TX_FEE - nPayFee); nChange -= nMoveToFee; nPayFee += nMoveToFee; } // paycoin: sub-cent change is moved to fee if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT) { nPayFee += nChange; nChange = 0; } if (nChange > 0) { // Add a change address in the outputs CTxOut txout(0, (CScript)vector<unsigned char>(24, 0)); txDummy.vout.push_back(txout); } // Bytes nBytes = nBytesInputs + GetSerializeSize(*(CTransaction*)&txDummy, SER_NETWORK, PROTOCOL_VERSION); // Priority dPriority = dPriorityInputs / nBytes; sPriorityLabel = CoinControlDialog::getPriorityLabel(dPriority); // Fee int64 nFee = nTransactionFee * (1 + (int64)nBytes / 1000); // Min Fee int64 nMinFee = txDummy.GetMinFee(1, false, GMF_SEND, nBytes); if (nPayFee < max(nFee, nMinFee)) { nPayFee = max(nFee, nMinFee); continue; } // after fee nAfterFee = nAmount - nPayFee; if (nAfterFee < 0) nAfterFee = 0; } break; } // actually update labels int nDisplayUnit = BitcoinUnits::BTC; if (model && model->getOptionsModel()) nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); QLabel *l1 = dialog->findChild<QLabel *>("<API key>"); QLabel *l2 = dialog->findChild<QLabel *>("<API key>"); QLabel *l3 = dialog->findChild<QLabel *>("labelCoinControlFee"); QLabel *l4 = dialog->findChild<QLabel *>("<API key>"); QLabel *l5 = dialog->findChild<QLabel *>("<API key>"); QLabel *l6 = dialog->findChild<QLabel *>("<API key>"); QLabel *l7 = dialog->findChild<QLabel *>("<API key>"); QLabel *l8 = dialog->findChild<QLabel *>("<API key>"); // enable/disable "low output" and "change" dialog->findChild<QLabel *>("<API key>")->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("<API key>") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("<API key>") ->setEnabled(nPayAmount > 0); dialog->findChild<QLabel *>("<API key>") ->setEnabled(nPayAmount > 0); // stats l1->setText(QString::number(nQuantity)); // Quantity l2->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAmount)); // Amount l3->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nPayFee)); // Fee l4->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nAfterFee)); // After Fee l5->setText(((nBytes > 0) ? "~" : "") + QString::number(nBytes)); // Bytes l6->setText(sPriorityLabel); // Priority l7->setText((fLowOutput ? (fDust ? tr("DUST") : tr("yes")) : tr("no"))); // Low Output / Dust l8->setText(BitcoinUnits::formatWithUnit(nDisplayUnit, nChange)); // Change // turn labels "red" l5->setStyleSheet((nBytes >= 10000) ? "color:red;" : ""); // Bytes >= 10000 l6->setStyleSheet((dPriority <= 576000) ? "color:red;" : ""); // Priority < "medium" l7->setStyleSheet((fLowOutput) ? "color:red;" : ""); // Low Output = "yes" l8->setStyleSheet((nChange > 0 && nChange < CENT) ? "color:red;" : ""); // Change < 0.01BTC // tool tips l5->setToolTip(tr("This label turns red if the transaction size is bigger than 10000 bytes.\n\n This means a fee of at least %1 per kb is required.\n\n Can vary +/- 1 Byte per input.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT))); l6->setToolTip(tr("Transactions with higher priority get more likely into a block.\n\nThis label turns red if the priority is smaller than \"medium\".\n\n This means a fee of at least %1 per kb is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT))); l7->setToolTip(tr("This label turns red if any recipient receives an amount smaller than %1.\n\n This means a fee of at least %2 is required. \n\n Amounts below 0.546 times the minimum relay fee are shown as DUST.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)).arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT))); l8->setToolTip(tr("This label turns red if the change is smaller than %1.\n\n This means a fee of at least %2 is required.").arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT)).arg(BitcoinUnits::formatWithUnit(nDisplayUnit, CENT))); dialog->findChild<QLabel *>("<API key>") ->setToolTip(l5->toolTip()); dialog->findChild<QLabel *>("<API key>") ->setToolTip(l6->toolTip()); dialog->findChild<QLabel *>("<API key>")->setToolTip(l7->toolTip()); dialog->findChild<QLabel *>("<API key>") ->setToolTip(l8->toolTip()); // Insufficient funds QLabel *label = dialog->findChild<QLabel *>("<API key>"); if (label) label->setVisible(nChange < 0); } void CoinControlDialog::updateView() { bool treeMode = ui->radioTreeMode->isChecked(); ui->treeWidget->clear(); ui->treeWidget->setEnabled(false); // performance, otherwise updateLabels would be called for every checked checkbox ui->treeWidget-><API key>(!treeMode); QFlags<Qt::ItemFlag> flgCheckbox=Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable; QFlags<Qt::ItemFlag> flgTristate=Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsTristate; int nDisplayUnit = BitcoinUnits::BTC; if (model && model->getOptionsModel()) nDisplayUnit = model->getOptionsModel()->getDisplayUnit(); map<QString, vector<COutput> > mapCoins; model->listCoins(mapCoins); BOOST_FOREACH(PAIRTYPE(QString, vector<COutput>) coins, mapCoins) { QTreeWidgetItem *itemWalletAddress = new QTreeWidgetItem(); QString sWalletAddress = coins.first; QString sWalletLabel = ""; if (model-><API key>()) sWalletLabel = model-><API key>()->labelForAddress(sWalletAddress); if (sWalletLabel.length() == 0) sWalletLabel = tr("(no label)"); if (treeMode) { // wallet address ui->treeWidget->addTopLevelItem(itemWalletAddress); itemWalletAddress->setFlags(flgTristate); itemWalletAddress->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked); for (int i = 0; i < ui->treeWidget->columnCount(); i++) itemWalletAddress->setBackground(i, QColor(248, 247, 246)); // label itemWalletAddress->setText(COLUMN_LABEL, sWalletLabel); // address itemWalletAddress->setText(COLUMN_ADDRESS, sWalletAddress); } int64 nSum = 0; double dPrioritySum = 0; int nChildren = 0; int nInputSum = 0; BOOST_FOREACH(const COutput& out, coins.second) { int nInputSize = 148; // 180 if uncompressed public key nSum += out.tx->vout[out.i].nValue; nChildren++; QTreeWidgetItem *itemOutput; if (treeMode) itemOutput = new QTreeWidgetItem(itemWalletAddress); else itemOutput = new QTreeWidgetItem(ui->treeWidget); itemOutput->setFlags(flgCheckbox); itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Unchecked); // address CTxDestination outputAddress; QString sAddress = ""; if(ExtractDestination(out.tx->vout[out.i].scriptPubKey, outputAddress)) { sAddress = CBitcoinAddress(outputAddress).ToString().c_str(); // if listMode or change => show bitcoin address. In tree mode, address is not shown again for direct wallet address outputs if (!treeMode || (!(sAddress == sWalletAddress))) itemOutput->setText(COLUMN_ADDRESS, sAddress); CPubKey pubkey; CKeyID *keyid = boost::get< CKeyID >(&outputAddress); if (keyid && model->getPubKey(*keyid, pubkey) && !pubkey.IsCompressed()) nInputSize = 180; } // label if (!(sAddress == sWalletAddress)) // change { // tooltip from where the change comes from itemOutput->setToolTip(COLUMN_LABEL, tr("change from %1 (%2)").arg(sWalletLabel).arg(sWalletAddress)); itemOutput->setText(COLUMN_LABEL, tr("(change)")); } else if (!treeMode) { QString sLabel = ""; if (model-><API key>()) sLabel = model-><API key>()->labelForAddress(sAddress); if (sLabel.length() == 0) sLabel = tr("(no label)"); itemOutput->setText(COLUMN_LABEL, sLabel); } // amount itemOutput->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, out.tx->vout[out.i].nValue)); itemOutput->setData(COLUMN_AMOUNT_INT64, Qt::DisplayRole, out.tx->vout[out.i].nValue); // date itemOutput->setText(COLUMN_DATE, QDateTime::fromTime_t(out.tx->GetTxTime()).toUTC().toString("yy-MM-dd hh:mm")); // immature PoS reward if (out.tx->IsCoinStake() && out.tx->GetBlocksToMaturity() > 0 && out.tx->GetDepthInMainChain() > 0) { itemOutput->setBackground(<API key>, Qt::red); itemOutput->setDisabled(true); } // confirmations itemOutput->setData(<API key>, Qt::DisplayRole, out.nDepth); // coin age int nDayWeight = (min((GetAdjustedTime() - out.tx->GetTxTime()), (int64) STAKE_MAX_AGE) - nStakeMinAge) / 86400; uint64 coinAge = max(out.tx->vout[out.i].nValue * nDayWeight / COIN, (int64) 0); itemOutput->setData(COLUMN_COINAGE, Qt::DisplayRole, coinAge); // priority double dPriority = ((double)out.tx->vout[out.i].nValue / (nInputSize + 78)) * (out.nDepth+1); // 78 = 2 * 34 + 10 itemOutput->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPriority)); itemOutput->setData(<API key>, Qt::DisplayRole, (int64)dPriority); dPrioritySum += (double)out.tx->vout[out.i].nValue * (out.nDepth+1); nInputSum += nInputSize; // transaction hash uint256 txhash = out.tx->GetHash(); itemOutput->setText(COLUMN_TXHASH, txhash.GetHex().c_str()); // vout index itemOutput->setText(COLUMN_VOUT_INDEX, QString::number(out.i)); // disable locked coins /*if (model->isLockedCoin(txhash, out.i)) { COutPoint outpt(txhash, out.i); coinControl->UnSelect(outpt); // just to be sure itemOutput->setDisabled(true); itemOutput->setIcon(COLUMN_CHECKBOX, QIcon(":/icons/lock_closed")); }*/ // set checkbox if (coinControl->IsSelected(txhash, out.i)) itemOutput->setCheckState(COLUMN_CHECKBOX,Qt::Checked); } // amount if (treeMode) { dPrioritySum = dPrioritySum / (nInputSum + 78); itemWalletAddress->setText(COLUMN_CHECKBOX, "(" + QString::number(nChildren) + ")"); itemWalletAddress->setText(COLUMN_AMOUNT, BitcoinUnits::format(nDisplayUnit, nSum)); itemWalletAddress->setData(COLUMN_AMOUNT_INT64, Qt::DisplayRole, nSum); itemWalletAddress->setText(COLUMN_PRIORITY, CoinControlDialog::getPriorityLabel(dPrioritySum)); itemWalletAddress->setData(<API key>, Qt::DisplayRole, (int64)dPrioritySum); } } // expand all partially selected if (treeMode) { for (int i = 0; i < ui->treeWidget->topLevelItemCount(); i++) if (ui->treeWidget->topLevelItem(i)->checkState(COLUMN_CHECKBOX) == Qt::PartiallyChecked) ui->treeWidget->topLevelItem(i)->setExpanded(true); } // sort view sortView(sortColumn, sortOrder); ui->treeWidget->setEnabled(true); unselectSpent(); } // Unselect coins that were spent (e.g. to mint a block) void CoinControlDialog::unselectSpent() { map<QString, vector<COutput> > mapCoins; vector<COutPoint> vCoinControl; vector<COutPoint> vDelete; int found; model->listCoins(mapCoins); coinControl->ListSelected(vCoinControl); BOOST_FOREACH(const COutPoint outpt, vCoinControl) { found = 0; BOOST_FOREACH(PAIRTYPE(QString, vector<COutput>) coins, mapCoins) { BOOST_FOREACH(const COutput& out, coins.second) { COutPoint outpt2(out.tx->GetHash(), out.i); if(outpt2 == outpt) { found = 1; break; } } if(found) break; } if(!found) vDelete.push_back(outpt); } BOOST_FOREACH(COutPoint outpt, vDelete) { coinControl->UnSelect(outpt); } }
<?php error_reporting(0); // Set E_ALL for debuging include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderConnector.class.php'; include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinder.class.php'; include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'<API key>.class.php'; include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'<API key>.class.php'; // Required for MySQL storage connector // include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderVolumeMySQL.class.php'; // Required for FTP connector support // include_once dirname(__FILE__).DIRECTORY_SEPARATOR.'elFinderVolumeFTP.class.php'; /** * Simple function to demonstrate how to control file access using "accessControl" callback. * This method will disable accessing files/folders starting from '.' (dot) * * @param string $attr attribute name (read|write|locked|hidden) * @param string $path file path relative to volume root directory started with directory separator * @return bool|null **/ function access($attr, $path, $data, $volume) { return strpos(basename($path), '.') === 0 // if file/folder begins with '.' (dot) ? !($attr == 'read' || $attr == 'write') // set read+write to false, other (locked+hidden) set to true : null; // else elFinder decide it itself } $opts = array( // 'debug' => true, 'roots' => array( array( 'driver' => 'LocalFileSystem', // driver for accessing file system (REQUIRED) 'path' => '../files/', // path to files (REQUIRED) 'URL' => dirname($_SERVER['PHP_SELF']) . '/../files/', // URL to files (REQUIRED) 'accessControl' => 'access' , // disable and hide dot starting files (OPTIONAL) 'defaults' => array( // default permisions 'read' => true, 'write' => true, 'rm' => true ), 'perms' => array( // individual folders/files permisions '/^test_dir\/.*/' => array( 'read' => true, 'write' => true, 'rm' => true ) ), ) ) ); // run elFinder $connector = new elFinderConnector(new elFinder($opts)); $connector->run();
The services directory here is for utilty standalone service classes that are not coupled directly to the rails MVC
from .app import APIClient, APIResource, api, api_app # noqa from .core import ( # noqa authentication, cached, database, format_checker, plugins, schema, server, tasks, user, )
<!DOCTYPE html> <! Copyright (c) 2014-2021 Antony Polukhin antoshkka at gmail dot com Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http: <html> <head> <meta charset="utf-8"> <meta http-equiv="refresh" content="0; url=https: <title>Boost.Stacktrace</title> <style> body { background: #fff; color: #000; } a { color: #00f; text-decoration: none; } </style> </head> <body> <p> Automatic redirection failed, please go to <a href="https: </p> <p> &copy; 2014-2021 Antony Polukhin </p> </body> </html>
namespace BullsAndCows.Web.Api.Controllers { using System.Linq; using System.Web.Http; using AutoMapper.QueryableExtensions; using Services.Data.Contracts; using Models.Games; using Microsoft.AspNet.Identity; using AutoMapper; using System.Net.Http; using Infrastructure.Validation; using Models.Guesses; public class GamesController : ApiController { private readonly IGamesService games; private readonly IGuessService guesses; public GamesController(IGamesService games, IGuessService guesses) { this.games = games; this.guesses = guesses; } public IHttpActionResult Get(string page = "1") { int pageAsNumber; if (!int.TryParse(page, out pageAsNumber)) { pageAsNumber = 1; } var userId = this.User.Identity.GetUserId(); var games = this.games .GetPublicGames(pageAsNumber, userId) .ProjectTo<<API key>>() .ToList(); return this.Ok(games); } [Authorize] public IHttpActionResult Get(int id) { var userId = this.User.Identity.GetUserId(); if (!this.games.UserIsPartOfGame(id, userId)) { return this.BadRequest("You are not part of this game!"); } var gameResult = this.games .GetGameDetails(id) .ProjectTo<<API key>>(new { userId }) .FirstOrDefault(); return this.Ok(gameResult); } [Authorize] [ValidateModel] public IHttpActionResult Post(<API key> model) { var newGame = this.games.CreateGame( model.Name, model.Number, this.User.Identity.GetUserId()); var gameResult = games .GetGameDetails(newGame.Id) .ProjectTo<<API key>>() .FirstOrDefault(); return this.Created( string.Format("/api/Games/{0}", newGame.Id), gameResult); } [Authorize] [ValidateModel] public IHttpActionResult Put(int id, <API key> model) { var userId = this.User.Identity.GetUserId(); if (!this.games.<API key>(id, userId)) { return this.BadRequest("This game is yours! Do you have two personalities?"); } // TODO: add notification var joinedGame = this.games.JoinGame(id, model.Number, userId); return this.Ok(new { result = string.Format("You joined game \"{0}\"", joinedGame) }); } [HttpPost] [Route("api/games/{id}/guess")] [ValidateModel] public IHttpActionResult Guess(int id, <API key> model) { var userId = this.User.Identity.GetUserId(); if (!this.games.CanMakeGuess(id, userId)) { return this.BadRequest("Either you are not part of the game or it is not your turn!"); } var newGuess = this.guesses.MakeGuess(id, model.Number, userId); var guessResult = this.guesses .GetGuessDetails(newGuess.Id) .ProjectTo<<API key>>() .FirstOrDefault(); return this.Ok(guessResult); } } }
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models { using Newtonsoft.Json; using System.Linq; <summary> Identity details. </summary> public partial class IdentityInformation { <summary> Initializes a new instance of the IdentityInformation class. </summary> public IdentityInformation() { CustomInit(); } <summary> Initializes a new instance of the IdentityInformation class. </summary> <param name="<API key>">The identity provider type. Value is the ToString() of a <API key> value. Possible values include: '<API key>'</param> <param name="tenantId">The tenant Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services.</param> <param name="applicationId">The application/client Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services.</param> <param name="objectId">The object Id of the service principal with which the on-premise management/data plane components would communicate with our Azure services.</param> <param name="audience">The intended Audience of the service principal with which the on-premise management/data plane components would communicate with our Azure services.</param> <param name="aadAuthority">The base authority for Azure Active Directory authentication.</param> <param name="<API key>">The certificate thumbprint. Applicable only if <API key> is <API key>.</param> public IdentityInformation(string <API key> = default(string), string tenantId = default(string), string applicationId = default(string), string objectId = default(string), string audience = default(string), string aadAuthority = default(string), string <API key> = default(string)) { <API key> = <API key>; TenantId = tenantId; ApplicationId = applicationId; ObjectId = objectId; Audience = audience; AadAuthority = aadAuthority; <API key> = <API key>; CustomInit(); } <summary> An initialization method that performs custom operations like setting defaults </summary> partial void CustomInit(); <summary> Gets or sets the identity provider type. Value is the ToString() of a <API key> value. Possible values include: '<API key>' </summary> [JsonProperty(PropertyName = "<API key>")] public string <API key> { get; set; } <summary> Gets or sets the tenant Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services. </summary> [JsonProperty(PropertyName = "tenantId")] public string TenantId { get; set; } <summary> Gets or sets the application/client Id for the service principal with which the on-premise management/data plane components would communicate with our Azure services. </summary> [JsonProperty(PropertyName = "applicationId")] public string ApplicationId { get; set; } <summary> Gets or sets the object Id of the service principal with which the on-premise management/data plane components would communicate with our Azure services. </summary> [JsonProperty(PropertyName = "objectId")] public string ObjectId { get; set; } <summary> Gets or sets the intended Audience of the service principal with which the on-premise management/data plane components would communicate with our Azure services. </summary> [JsonProperty(PropertyName = "audience")] public string Audience { get; set; } <summary> Gets or sets the base authority for Azure Active Directory authentication. </summary> [JsonProperty(PropertyName = "aadAuthority")] public string AadAuthority { get; set; } <summary> Gets or sets the certificate thumbprint. Applicable only if <API key> is <API key>. </summary> [JsonProperty(PropertyName = "<API key>")] public string <API key> { get; set; } } }
<?php namespace FACTFinder\Core\Server; use \FACTFinder\Loader as FF; /** * This implementation backs the Request with a <API key>. */ class <API key> implements <API key> { /** * @var \FACTFinder\Util\LoggerInterface */ private $log; private $loggerClass; /** * @var \FACTFinder\Core\<API key> */ protected $configuration; /** * @var <API key> */ private $dataProvider; /** * @var \FACTFinder\Util\Parameters */ private $requestParameters; /** * @param string $loggerClass * @param \FACTFinder\Core\<API key> $configuration * @param \FACTFinder\Util\Parameters $requestParameters * @param \FACTFinder\Util\CurlInterface $curl Optional. If omitted, an * instance of \FACTFinder\Util\Curl will be used. */ public function __construct( $loggerClass, \FACTFinder\Core\<API key> $configuration, \FACTFinder\Util\Parameters $requestParameters, \FACTFinder\Util\CurlInterface $curl = null ) { $this->loggerClass = $loggerClass; $this->log = $loggerClass::getLogger(__CLASS__); $this->configuration = $configuration; $urlBuilder = FF::getInstance('Core\Server\UrlBuilder', $loggerClass, $configuration ); $this->dataProvider = FF::getInstance('Core\Server\<API key>', $loggerClass, $configuration, is_null($curl) ? FF::getInstance('Util\Curl') : $curl, $urlBuilder ); $this->requestParameters = $requestParameters; } /** * Returns a request object all wired up and ready for use. * @return Request */ public function getRequest() { $connectionData = FF::getInstance( 'Core\Server\ConnectionData', clone $this->requestParameters ); return FF::getInstance('Core\Server\Request', $this->loggerClass, $connectionData, $this->dataProvider ); } }
/* * Creates a configured Webpack instance. */ const webpack = require('webpack'); const config = require('../config/webpack'); module.exports = (env = 'development') => webpack(config(env));
require File.expand_path(File.join(File.dirname(__FILE__), 'helper')) require 'webrick' class ::WEBrick::HTTPServer ; def access_log(config, req, res) ; end ; end class ::WEBrick::BasicLog ; def log(level, data) ; end ; end class <API key> < Test::Unit::TestCase def test_bug server = WEBrick::HTTPServer.new( :Port => 9999 ) server.mount_proc("/test") do|req,res| sleep 0.5 res.body = "hi" res['Content-Type'] = "text/html" end thread = Thread.new(server) do|srv| srv.start end threads = [] timer = Time.now 5.times do |i| t = Thread.new do c = Curl::Easy.perform('http://127.0.0.1:9999/test') c.header_str end threads << t end multi_responses = threads.collect do|t| t.value end multi_time = (Time.now - timer) puts "requested in #{multi_time}" timer = Time.now single_responses = [] 5.times do |i| c = Curl::Easy.perform('http://127.0.0.1:9999/test') single_responses << c.header_str end single_time = (Time.now - timer) puts "requested in #{single_time}" assert single_time > multi_time server.shutdown thread.join end end
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "../src/MathGeoLib.h" #include "../src/Math/myassert.h" #include "TestRunner.h" #include "TestData.h" #include "../src/Math/SSEMath.h" #include "../src/Math/quat_simd.h" <API key> using namespace TestData; BENCHMARK(<API key>, "Quat::Transform(float3)") { v2[i].Float3Part() = q[i].Transform(v[i].Float3Part()); } BENCHMARK_END; #ifdef MATH_SSE BENCHMARK(quat_transform_vec4, "quat_transform_vec4") { v2[i] = quat_transform_vec4(q[i].q, v01[i].v); } BENCHMARK_END; #endif BENCHMARK(<API key>, "Quat::Transform(float4)") { v2[i] = q[i].Transform(v01[i]); } BENCHMARK_END; BENCHMARK(<API key>, "Quat::SetFromAxisAngle(float4,float)") { q2[i].SetFromAxisAngle(nv[i], f[i]); } BENCHMARK_END; BENCHMARK(<API key>, "Quat::ToAxisAngle(float3,float)") { q2[i].ToAxisAngle(*(float3*)&v3[i], f[i]); } BENCHMARK_END; BENCHMARK(<API key>, "Quat::ToAxisAngle(float4,float)") { q2[i].ToAxisAngle(v3[i], f[i]); } BENCHMARK_END; BENCHMARK(Quat_Axis, "Quat::Axis()") { ve[i] = q2[i].Axis(); } BENCHMARK_END; BENCHMARK(Quat_to_float4x4, "Quat::ToFloat4x4") { m[i] = q[i].ToFloat4x4(); } BENCHMARK_END; BENCHMARK(Quat_Slerp, "Quat::Slerp") { q2[i] = q[i].Slerp(q2[i], uf[i]); } BENCHMARK_END; Quat PreciseSlerp(const Quat &a, const Quat &b, float t) { double angle = a.x*b.x + a.y*b.y + a.z*b.z + a.w*b.w; double sign = 1.0; if (angle < 0) { angle = -angle; sign = -1.0; } double A; double B; if (angle <= 1.0) // perform spherical linear interpolation. { angle = acos(angle); // After this, angle is in the range pi/2 -> 0 as the original angle variable ranged from 0 -> 1. double angleT = t*angle; double s[3] = { sin(angle), sin(angle - angleT), sin(angleT) }; double c = 1.0 / s[0]; A = s[1] * c; B = s[2] * c; } else // If angle is close to taking the denominator to zero, resort to linear interpolation (and normalization). { A = 1.0 - t; B = t; } Quat C; C.x = (float)(a.x*A*sign + b.x*B); C.y = (float)(a.y*A*sign + b.y*B); C.z = (float)(a.z*A*sign + b.z*B); C.w = (float)(a.w*A*sign + b.w*B); return C.Normalized(); } UNIQUE_TEST(<API key>) { float maxError = 0; float maxLerpError = 0; float magnitudeError = 0; for (int i = 0; i < 10000; ++i) { Quat q = Quat::RandomRotation(rng); Quat q2 = Quat::RandomRotation(rng); float t = rng.Float01Incl(); Quat correct = PreciseSlerp(q, q2, t); Quat fast = q.Slerp(q2, t); magnitudeError = Max(magnitudeError, Abs(1.f - fast.LengthSq())); Quat lerp = q.Lerp(q2, t); maxLerpError = Max(maxLerpError, RadToDeg(correct.AngleBetween(lerp))); maxError = Max(maxError, RadToDeg(correct.AngleBetween(fast))); } LOGI("Maximum quaternion slerp error: %f degrees. (%.2f%% error relative to nlerp). Squared magnitude error: %f", maxError, maxError * 100.0f / maxLerpError, magnitudeError); } UNIQUE_TEST(Quat_Slerp_perf) { tick_t min = 9999999999; const int nIters = 100; const int nSamples = 30000; float4 res; for (int i = 0; i < nIters; ++i) { Quat q = Quat::RandomRotation(rng); Quat q2 = Quat::RandomRotation(rng); float f = 0.f; tick_t t0 = Clock::Tick(); for (int j = 0; j < nSamples; ++j) { // AVX+FMA3: 10.289649 nsecs // Scalar: 13.228866 nsecs Quat q3 = q.Slerp(q2, f); // Precise: 58.709194 nsecs //Quat q3 = PreciseSlerp(q, q2, f); res += q3.CastToFloat4(); f += 0.1f / nSamples; } tick_t t1 = Clock::Tick(); min = Min(min, t1 - t0); } printf("Min: %f nsecs. %s", Clock::<API key>(min)* 1000000.0f / nSamples, res.ToString().c_str()); } RANDOMIZED_TEST(<API key>) { float3 axis = float3::RandomDir(rng); float4 axis4(axis, 0.f); float f = rng.Float(-10000.f, 10000.f); Quat q, q2; q.SetFromAxisAngle(axis, f); q2.SetFromAxisAngle(axis4, f); assert2(q.Equals(q2), q, q2); } RANDOMIZED_TEST(Quat_Transform) { Quat q = Quat::RandomRotation(rng); float3x3 m = float3x3(q); float3 v = float3::RandomSphere(rng, float3(0,0,0), 100.f); float3 mv = m*v; float3 qv = q*v; float3 qv2 = q.Transform(v); assert(mv.Equals(qv)); assert(qv.Equals(qv2)); float4 V(v, (float)rng.Int(0, 1)); float4x4 M = float4x4(q); float4 MV = M*V; float4 qV = q*V; float4 qV2 = q.Transform(V); assert(MV.Equals(qV)); assert(MV.Equals(qV2)); } RANDOMIZED_TEST(Quat_float4x4_conv) { Quat q = Quat::RandomRotation(rng); float4x4 m = q.ToFloat4x4(); assert(m.TranslatePart().Equals(0,0,0)); assert(!m.ContainsProjection()); Quat q2 = m.Float3x3Part().ToQuat(); assert(q.Equals(q2) || q.Equals(q2.Neg())); float4 v = float4::RandomGeneral(rng, -1000.f, 1000.f); v.w = (float)rng.Int(0,1); m = q.ToFloat4x4(v); assert(m.TranslatePart().Equals(v.xyz())); assert(!m.ContainsProjection()); q2 = m.Float3x3Part().ToQuat(); assert(q.Equals(q2) || q.Equals(q2.Neg())); } BENCHMARK(Quat_op_mul_Quat, "Quat * Quat") { q2[i] = q[i] * q2[i]; } BENCHMARK_END BENCHMARK(Quat_op_div_Quat, "Quat / Quat") { q2[i] = q[i] / q2[i]; } BENCHMARK_END BENCHMARK(Quat_Lerp, "Quat::Lerp") { q2[i] = q[i].Lerp(q2[i], uf[i]); } BENCHMARK_END BENCHMARK(Quat_RotateFromTo, "Quat::RotateFromTo") { q2[i] = Quat::RotateFromTo(nv[i], nv2[i]); } BENCHMARK_END #ifdef MATH_SIMD BENCHMARK(quat_mul_quat, "test against Quat_op_mul_Quat") { q2[i].q = quat_mul_quat(q[i].q, q2[i].q); } BENCHMARK_END #ifdef ANDROID BENCHMARK(quat_mul_quat_asm, "test against Quat_op_mul_Quat") { quat_mul_quat_asm(q[i].ptr(), q2[i].ptr(), q2[i].ptr()); } BENCHMARK_END #endif RANDOMIZED_TEST(Quat_Mul_Quat) { Quat q = Quat::RotateY(pi/2.f); Quat q2 = Quat::RotateX(pi/2.f); Quat q3 = q2*q; float4 v = float4::RandomDir(rng); float4 v2 = q3*v; float4 v3 = q2*(q*v); float3x3 m = q.ToFloat3x3(); float3x3 m2 = q2.ToFloat3x3(); float4 v4 = m2*m*v; assert(v2.Equals(v3)); assert(v2.Equals(v4)); } RANDOMIZED_TEST(quat_mul_quat) { Quat q = Quat::RandomRotation(rng); Quat q2 = Quat::RandomRotation(rng); Quat correct = Quat(q.ToFloat3x3() * q2.ToFloat3x3()); Quat q3 = quat_mul_quat(q.q, q2.q); assert(q3.Equals(correct) || q3.Equals(correct.Neg())); } RANDOMIZED_TEST(<API key>) { Quat q = Quat::RandomRotation(rng); float3 axis; float angle; q.ToAxisAngle(axis, angle); Quat q2; q2.SetFromAxisAngle(axis, angle); assert(q.Equals(q2)); } RANDOMIZED_TEST(<API key>) { Quat q = Quat::RandomRotation(rng); float4 axis; float angle; q.ToAxisAngle(axis, angle); vec axis2 = q.Axis(); assert(axis2.xyz().Equals(axis.xyz())); Quat q2; q2.SetFromAxisAngle(axis, angle); assert(q.Equals(q2)); } RANDOMIZED_TEST(<API key>) { float3 v = float3::RandomDir(rng); float3 v2 = float3::RandomDir(rng); Quat rot = Quat::RotateFromTo(v, v2); float3 v2_ = rot * v; assert2(v2.Equals(v2_), v2, v2_); } RANDOMIZED_TEST(<API key>) { float4 v = float4::RandomDir(rng); float4 v2 = float4::RandomDir(rng); Quat rot = Quat::RotateFromTo(v, v2); float4 v2_ = rot * v; assert2(v2.Equals(v2_), v2, v2_); } TEST(QuatNormalize) { Quat q(-1.f, 2.f, 3.f, 4.f); float oldLength = q.Normalize(); MARK_UNUSED(oldLength); assertcmp(oldLength, >, 0); assert(EqualAbs(q.x, -1.f / Sqrt(30.f))); assert(EqualAbs(q.y, 2.f / Sqrt(30.f))); assert(EqualAbs(q.z, 3.f / Sqrt(30.f))); assert(EqualAbs(q.w, 4.f / Sqrt(30.f))); Quat q2(0,0,0, 0.f); oldLength = q2.Normalize(); MARK_UNUSED(oldLength); assert(oldLength == 0.f); assert(q2.x == 1.f); assert(q2.y == 0.f); assert(q2.z == 0.f); assert(q2.w == 0.f); } TEST(QuatNormalized) { Quat q(-1.f, 2.f, 3.f, -4.f); Quat q2 = q.Normalized(); assert(EqualAbs(q2.x, -1.f / Sqrt(30.f))); assert(EqualAbs(q2.y, 2.f / Sqrt(30.f))); assert(EqualAbs(q2.z, 3.f / Sqrt(30.f))); assert(EqualAbs(q2.w, -4.f / Sqrt(30.f))); } #ifdef ANDROID RANDOMIZED_TEST(quat_mul_quat_asm) { Quat q = Quat::RandomRotation(rng); Quat q2 = Quat::RandomRotation(rng); Quat correct = q * q2; Quat q3; quat_mul_quat_asm(q.ptr(), q2.ptr(), q3.ptr()); assert(q3.Equals(correct)); } #endif #ifdef MATH_SSE BENCHMARK(quat_div_quat, "test against Quat_op_div_Quat") { q2[i].q = quat_div_quat(q[i].q, q2[i].q); } BENCHMARK_END RANDOMIZED_TEST(quat_div_quat) { Quat q = Quat::RandomRotation(rng); Quat q2 = Quat::RandomRotation(rng); Quat correct = q / q2; Quat q3 = quat_div_quat(q.q, q2.q); assert(q3.Equals(correct)); } #endif BENCHMARK(quat_lerp_simd, "test against Quat_Lerp") { q2[i].q = vec4_lerp(q[i].q, q2[i].q, uf[i]); } BENCHMARK_END /* TODO: Find a way to test better, this is broken. RANDOMIZED_TEST(quat_lerp) { Quat q = Quat::RandomRotation(rng); Quat q2 = Quat::RandomRotation(rng); float t = rng.Float(); Quat correct = q.Lerp(q2, t); Quat q3 = vec4_lerp(q.q, q2.q, t); assert2(q3.Equals(correct), q3, correct); } */ #endif
from django.utils.encoding import <API key> from allauth.account.models import EmailAddress from allauth.socialaccount import app_settings from ..adapter import get_adapter class AuthProcess(object): LOGIN = 'login' CONNECT = 'connect' REDIRECT = 'redirect' class AuthAction(object): AUTHENTICATE = 'authenticate' REAUTHENTICATE = 'reauthenticate' class AuthError(object): UNKNOWN = 'unknown' CANCELLED = 'cancelled' # Cancelled on request of user DENIED = 'denied' # Denied by server class ProviderException(Exception): pass class Provider(object): slug = None def __init__(self, request): self.request = request @classmethod def get_slug(cls): return cls.slug or cls.id def get_login_url(self, request, next=None, **kwargs): """ Builds the URL to redirect to when initiating a login for this provider. """ raise NotImplementedError("get_login_url() for " + self.name) def get_app(self, request): # NOTE: Avoid loading models at top due to registry boot... from allauth.socialaccount.models import SocialApp return SocialApp.objects.get_current(self.id, request) def media_js(self, request): """ Some providers may require extra scripts (e.g. a Facebook connect) """ return '' def wrap_account(self, social_account): return self.account_class(social_account) def get_settings(self): return app_settings.PROVIDERS.get(self.id, {}) def <API key>(self, request, response): """ Instantiates and populates a `SocialLogin` model based on the data retrieved in `response`. The method does NOT save the model to the DB. Data for `SocialLogin` will be extracted from `response` with the help of the `.extract_uid()`, `.extract_extra_data()`, `.<API key>()`, and `.<API key>()` methods. :param request: a Django `HttpRequest` object. :param response: object retrieved via the callback response of the social auth provider. :return: A populated instance of the `SocialLogin` model (unsaved). """ # NOTE: Avoid loading models at top due to registry boot... from allauth.socialaccount.models import SocialLogin, SocialAccount adapter = get_adapter(request) uid = self.extract_uid(response) extra_data = self.extract_extra_data(response) common_fields = self.<API key>(response) socialaccount = SocialAccount(extra_data=extra_data, uid=uid, provider=self.id) email_addresses = self.<API key>(response) self.<API key>(common_fields.get('email'), email_addresses) sociallogin = SocialLogin(account=socialaccount, email_addresses=email_addresses) user = sociallogin.user = adapter.new_user(request, sociallogin) user.<API key>() adapter.populate_user(request, sociallogin, common_fields) return sociallogin def extract_uid(self, data): """ Extracts the unique user ID from `data` """ raise NotImplementedError( 'The provider must implement the `extract_uid()` method' ) def extract_extra_data(self, data): """ Extracts fields from `data` that will be stored in `SocialAccount`'s `extra_data` JSONField. :return: any JSON-serializable Python structure. """ return data def <API key>(self, data): """ Extracts fields from `data` that will be used to populate the `User` model in the `<API key>`'s `populate_user()` method. For example: {'first_name': 'John'} :return: dictionary of key-value pairs. """ return {} def <API key>(self, email, addresses): # Move user.email over to EmailAddress if (email and email.lower() not in [ a.email.lower() for a in addresses]): addresses.append(EmailAddress(email=email, verified=False, primary=True)) # Force verified emails settings = self.get_settings() verified_email = settings.get('VERIFIED_EMAIL', False) if verified_email: for address in addresses: address.verified = True def <API key>(self, data): """ For example: [EmailAddress(email='john@example.com', verified=True, primary=True)] """ return [] @classmethod def get_package(cls): pkg = getattr(cls, 'package', None) if not pkg: pkg = cls.__module__.rpartition('.')[0] return pkg @<API key> class ProviderAccount(object): def __init__(self, social_account): self.account = social_account def get_profile_url(self): return None def get_avatar_url(self): return None def get_brand(self): """ Returns a dict containing an id and name identifying the brand. Useful when displaying logos next to accounts in templates. For most providers, these are identical to the provider. For OpenID however, the brand can derived from the OpenID identity url. """ provider = self.account.get_provider() return dict(id=provider.id, name=provider.name) def __str__(self): return self.to_str() def to_str(self): """ Due to the way <API key> works, this does not work: @<API key> class GoogleAccount(ProviderAccount): def __str__(self): dflt = super(GoogleAccount, self).__str__() return self.account.extra_data.get('name', dflt) It will result in and infinite recursion loop. That's why we add a method `to_str` that can be overriden in a conventional fashion, without having to worry about @<API key> """ return self.get_brand()['name']
// <API key>.h // RichInbox #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> #import "DCUITheme.h" #import "<API key>.h" @interface <API key> : NSObject + (UILabel *)<API key>:(DCUITheme *)theme; + (void)addBarButtonItem:(UIBarButtonItem *)buttonItem buttonSide:(<API key>)side <API key>:(UINavigationItem *)navigationItem; + (void)removeBarButtonItem:(UIBarButtonItem *)buttonItem buttonSide:(<API key>)side navigationItem:(UINavigationItem *)navigationItem; @end
// Type definitions for postman-collection 3.5 <reference types="node" /> export interface <API key> { description?: string | <API key>; } export class PropertyBase<TDefinition extends {}> implements <API key> { description?: string | <API key>; constructor(definition?: <API key> | { info: <API key> } | string); findInParents( property: string, customizer?: (item: PropertyBase<<API key>>) => boolean, ): PropertyBase<<API key>>; <API key>( property: any, customizer: (item: PropertyBase<<API key>>) => boolean, ): PropertyBase<<API key>>; forEachParent(iterator: (item: any) => void): void; forEachParent(options: { withRoot: boolean }, iterator: (item: any) => void): void; meta(): any; parent(): PropertyBase<<API key>> | undefined; setParent(parent: PropertyBase<<API key>>): void; toJSON(): TDefinition; static propertyIsMeta(_value: any, key: string): boolean; static <API key>(_value: any, key: string): string; static toJSON(obj: any): any; } export interface PropertyDefinition extends <API key> { id?: string; name?: string; disabled?: boolean; } export class Property<TDefinition extends {}> extends PropertyBase<TDefinition> implements PropertyDefinition { disabled: boolean; id: string; name: string; constructor(definition?: TDefinition | { info: TDefinition; disabled: boolean }); describe(content: string, type?: string): void; toObjectResolved( scope: { variables: VariableList } | null, overrides: any[], options?: { ignoreOwnVariables: boolean }, ): TDefinition; static <API key>(str: string, variables: VariableList | VariableList[]): string; static <API key><T>(obj: T, variables: VariableList[], mutate: boolean): T; } export interface <API key> extends PropertyDefinition { matches?: string[] | UrlMatchPatternList; key?: { src?: string } | string; cert?: { src?: string } | string; passphrase?: string; } export class Certificate extends Property<<API key>> implements <API key> { cert: { src?: string }; key: { src?: string }; matches: UrlMatchPatternList; passphrase: string; constructor(options: <API key>); canApplyTo(url: string | Url): boolean; update(options: <API key>): void; static isCertificate(obj: any): boolean; } export class PropertyList<TElement> extends PropertyBase<<API key>> { constructor(type: string, parent: any, populate: TElement[]); add(item: TElement): void; all(): TElement[]; append(item: TElement): void; assimilate(source: PropertyList<TElement> | TElement[], prune: boolean): void; clear(): void; count(): number; each(iterator: (item: TElement) => void, context?: any): void; eachParent(iterator: (item: any) => void, context?: any): void; filter(rule: (item: TElement) => boolean, context: any): TElement[]; find(rule: (item: TElement) => boolean, context: any): TElement; get(key: string): any; has(item: string | TElement, value?: any): boolean; idx(index: number): TElement; indexOf(item: string): number; insert(item: TElement, before: TElement | string): void; insertAfter(item: TElement, after: TElement | string): void; map(iterator: (item: TElement) => any, context?: any): any; one(id: string): TElement; populate(items: TElement[]): void; prepend(item: TElement): void; remove(predicate: ((item: TElement) => boolean) | string | TElement, context: any): void; repopulate(items: any): void; toJSON(): any; toObject(excludeDisabled?: boolean, caseSensitive?: boolean, multiValue?: boolean, sanitizeKeys?: boolean): any; toString(): string; upsert(item: TElement): boolean | null; static isPropertyList(obj: any): boolean; } export class CertificateList extends PropertyList<Certificate> { constructor(parent: any, list: <API key>[]); resolveOne(url: string): <API key>; static isCertificateList(obj: any): boolean; } export interface ItemGroupDefinition extends PropertyDefinition { item?: Array<ItemDefinition | ItemGroupDefinition>; auth?: <API key>; event?: EventDefinition[]; } export class ItemGroup<TItem> extends Property<ItemGroupDefinition> { auth?: RequestAuth; items: PropertyList<TItem | ItemGroup<TItem>>; events: EventList; constructor(definition?: ItemGroupDefinition); <API key>(type: string | <API key>, options?: VariableList): void; forEachItem(callback: (el: TItem) => void): void; forEachItemGroup(callback: (el: ItemGroup<TItem>) => void): void; oneDeep(idOrName: string): TItem; static isItemGroup(obj: any): boolean; } export interface <API key> extends ItemGroupDefinition { info?: { id?: string; name?: string; version?: string; }; variable?: VariableDefinition[]; } export class Collection extends ItemGroup<Item> { events: EventList; variables: VariableList; version?: Version; constructor(definition?: <API key>, environments?: any[]); syncVariablesFrom( obj: { [key: string]: VariableDefinition }, track?: boolean, prune?: boolean, ): { created: string[]; updated: string[]; deleted: string[] } | undefined; syncVariablesTo(obj?: { [key: string]: VariableDefinition }): { [key: string]: VariableDefinition }; toJSON(): <API key>; static isCollection(obj: any): boolean; } export interface CookieDefinition { key?: string; value?: string; expires?: string | Date | number; maxAge?: number; domain: string; path: string; secure?: boolean; httpOnly?: boolean; hostOnly?: boolean; session?: boolean; extensions?: Array<{ key: string; value: string }>; } export class Cookie extends PropertyBase<CookieDefinition> implements Exclude<CookieDefinition, 'key'> { name?: string; domain: string; expires: Date; extensions?: Array<{ key: string; value: string }>; hostOnly?: boolean; httpOnly?: boolean; maxAge?: number; path: string; secure?: boolean; session?: boolean; value?: string; constructor(options?: CookieDefinition); update(options: CookieDefinition): void; valueOf(): string; static isCookie(obj: any): boolean; static parse(str: string): CookieDefinition; static splitParam(param: string): { key: string; value: string | boolean }; } export class CookieList extends PropertyList<Cookie> { constructor(parent: any, cookies: Cookie[]); static isCookieList(obj: any): boolean; } export interface <API key> { content: string; type?: string; } export class Description implements <API key> { content: string; type: string; constructor(definition?: <API key> | string); toJSON(): <API key>; toString(): string; update(content: <API key>): void; update(content: string, type?: string): void; static isDescription(obj: any): boolean; } export interface EventDefinition extends PropertyDefinition { listen?: string; script: string | string[] | ScriptDefinition | Script; } export class Event extends Property<EventDefinition> implements EventDefinition { listen?: string; script: Script; constructor(definition: EventDefinition); update(definition: EventDefinition): void; } export class EventList extends PropertyList<Event> { constructor(parent: any, populate: Event[]); listeners(name: string): Event[]; listenersOwn(name: string): Event[]; static isEventList(obj: any): boolean; } export interface FormParamDefinition extends PropertyDefinition { key?: string; value?: any; } export class FormParam extends Property<FormParamDefinition> implements FormParamDefinition { key: string; value: any; constructor(options: FormParamDefinition); toString(): string; valueOf(): any; // static parse(): void; // TODO not implemented yet } export interface HeaderDefinition extends PropertyDefinition { key?: string; value?: string; system?: boolean; } export class Header extends Property<HeaderDefinition> implements HeaderDefinition { key: string; value: string; constructor(options: string | HeaderDefinition, name?: string); toString(): string; update(options: HeaderDefinition): void; valueOf(): string; static create(value?: HeaderDefinition | string, name?: string): Header; static isHeader(obj: any): boolean; static parse(headerString: string): HeaderDefinition[]; static parseSingle(header: string): HeaderDefinition; static unparse(headers: HeaderList | HeaderDefinition[], separator?: string): string; static unparseSingle(header: HeaderDefinition): string; } export class HeaderList extends PropertyList<Header> { constructor(parent: any, headers: Header[]); contentSize(): number; static isHeaderList(obj: any): boolean; } export interface ItemDefinition extends PropertyDefinition { request?: RequestDefinition; response?: ResponseDefinition[]; events?: EventDefinition[]; } export class Item extends Property<ItemDefinition> { events: EventList; request: Request; responses: PropertyList<Response>; constructor(definition?: ItemDefinition); <API key>(type: string | <API key>, options?: VariableList): void; getAuth(): RequestAuth; getEvents(name?: string): Event[]; static isItem(obj: any): boolean; } export interface <API key> extends PropertyDefinition { match?: string | { pattern: string } | UrlMatchPattern; host?: string; port?: number; tunnel?: boolean; } export class ProxyConfig extends Property<<API key>> implements <API key> { host: string; match: UrlMatchPattern; port: number; tunnel: boolean; constructor(options?: <API key>); getProtocols(): string[]; getProxyUrl(): string; test(urlStr?: string): boolean; update(options: <API key>): void; updateProtocols(protocols: string[]): void; static isProxyConfig(obj: any): boolean; } export class ProxyConfigList extends PropertyList<ProxyConfig> { constructor(parent: any, populate: ProxyConfig[]); resolve(url: string | Url): ProxyConfig; static isProxyConfigList(obj: any): boolean; } export interface <API key> extends PropertyDefinition { key: string | null; value: string | null; system?: boolean; } export class QueryParam extends Property<<API key>> implements <API key> { static <API key>: boolean; static <API key>: string; key: string | null; value: string | null; system?: boolean; constructor(options: <API key> | string); toString(): string; update(param: string | { key: string; value?: string }): void; valueOf(): string; static parse(query: string): <API key>[]; static parseSingle(param: string, idx: number, all: string[]): <API key>; static unparse(params: <API key>[], options?: { encode?: boolean; ignoreDisabled?: boolean }): string; static unparseSingle(obj: <API key>, encode: boolean): string; } export interface RequestDefinition extends PropertyDefinition { url: string | Url; method?: string; header?: HeaderDefinition[]; body?: <API key>; auth?: <API key>; proxy?: <API key>; certificate?: <API key>; } export class Request extends Property<RequestDefinition> implements RequestDefinition { auth?: RequestAuth; body?: RequestBody; certificate?: Certificate; headers: HeaderList; method: string; proxy?: ProxyConfig; url: Url; constructor(options: RequestDefinition | string); addHeader(header: Header | HeaderDefinition): void; addQueryParams(params: string | <API key>[]): void; authorizeUsing(type: string | <API key> | null, options?: VariableList): void; clone(): Request; forEachHeader(callback: (header: Header, context: Request) => void): void; getHeaders(options?: { ignoreCase?: boolean; enabled?: boolean }): any; removeHeader(toRemove: string | Header, options?: { ignoreCase: boolean }): void; removeQueryParams(params: string | string[] | <API key>[] | <API key>): void; toJSON(): RequestDefinition; update(options: RequestDefinition): void; upsertHeader(header: HeaderDefinition): void; static isRequest(obj: any): boolean; } export interface <API key> extends PropertyDefinition { type?: | 'oauth2' | 'hawk' | 'noauth' | 'basic' | 'oauth1' | 'apikey' | 'digest' | 'bearer' | 'awsv4' | 'edgegrid' | 'ntlm'; oauth2?: VariableDefinition[]; hawk?: VariableDefinition[]; basic?: VariableDefinition[]; oauth1?: VariableDefinition[]; apikey?: VariableDefinition[]; digest?: VariableDefinition[]; bearer?: VariableDefinition[]; awsv4?: VariableDefinition[]; edgegrid?: VariableDefinition[]; ntlm?: VariableDefinition[]; } export class RequestAuth extends Property<<API key>> implements <API key> { type: NonNullable<<API key>['type']>; constructor(options: <API key>, parent?: Property<PropertyDefinition> | PropertyList<RequestAuth>); clear(type: string): void; current(): any; parameters(): VariableList; update( options: VariableList | Array<{ key: string; value: string }> | { key: string; value: string }, type?: string, ): void; use( type: string, options: VariableList | Array<{ key: string; value: string }> | { key: string; value: string }, ): void; static isValidType(type: any): boolean; } export interface <API key> extends <API key> { mode: string; raw?: string; urlencoded?: <API key>[] | PropertyList<QueryParam> | string; file?: string | { src: string }; formdata?: FormParamDefinition[] | PropertyList<FormParam>; } export class RequestBody extends PropertyBase<<API key>> implements <API key> { static MODES: { raw: string; formdata: string; urlencoded: string; file: string; }; file?: { src: string }; formdata?: PropertyList<FormParam>; mode: string; raw?: string; urlencoded?: PropertyList<QueryParam>; constructor(options: <API key>); isEmpty(): boolean; toString(): string; update(options: <API key>): void; } export interface ResponseDefinition extends PropertyDefinition { code: number; header?: HeaderDefinition[]; cookie?: CookieDefinition[]; body?: string; stream?: Buffer | Uint8Array; responseTime: number; originalRequest?: RequestDefinition; } export class Response extends Property<ResponseDefinition> implements ResponseDefinition { body?: string; code: number; cookies: CookieList; headers: HeaderList; originalRequest?: Request; responseTime: number; status: string; stream?: Buffer | Uint8Array; responseSize?: number; constructor(options: ResponseDefinition); dataURI(): string; details(): { name: string; detail: string; code: number; standardName: string } | undefined; encoding(): { format: string; source: string }; json(reviver?: any, strict?: boolean): any; reason(): string; size(): number; text(): string | undefined; toJSON(): any; update(options: ResponseDefinition): void; static createFromNode( response: { body: string | Buffer | Uint8Array; headers?: HeaderDefinition[]; statusCode: number; statusMessage?: string; elapsedTime: number; }, cookies: CookieDefinition[], ): Response; static isResponse(obj: any): boolean; } export interface ScriptDefinition extends PropertyDefinition { type?: string; src?: string | Url; exec?: string | string[]; } export class Script extends Property<ScriptDefinition> implements ScriptDefinition { exec?: string[]; src?: Url; type: string; constructor(options?: ScriptDefinition | string | string[]); toSource(): string | undefined; update(options: ScriptDefinition | string | string[]): void; static isScript(obj: any): boolean; } export interface UrlDefinition extends <API key> { auth?: { user: string; password: string }; hash?: string; host?: string[] | string; path?: string[] | string; port?: string; query?: <API key>[] | PropertyList<QueryParam> | string; variable?: VariableDefinition[]; protocol?: string; } export class Url extends PropertyBase<UrlDefinition> implements UrlDefinition { auth?: { user: string; password: string }; hash?: string; host?: string[]; path?: string[]; port?: string; protocol?: string; query: PropertyList<QueryParam>; variables: VariableList; constructor(options: UrlDefinition | string); addQueryParams(params: <API key>[] | string): void; getHost(): string; getOAuth1BaseUrl(): string; getPath(options?: { unresolved: boolean }): string; getPathWithQuery(): string; getQueryString(options?: { encode?: boolean; ignoredDisabled?: boolean }): string; getRaw(): string; getRemote(options?: { forcePort: boolean }): string; removeQueryParams(params: <API key>[] | <API key> | string[] | string): void; toString(forceProtocol?: boolean): string; update(url: UrlDefinition | string): void; static isUrl(obj: any): boolean; static parse(url: string): UrlDefinition; } export class UrlMatchPattern { pattern?: string; constructor(options: string | { pattern: string }); createMatchPattern(): { protocols: string[]; host: string; path: RegExp } | undefined; getProtocols(): string[]; globPatternToRegexp(pattern: string): RegExp; <API key>( matchRegexObject: { protocols: string[]; host: string; path: RegExp }, remote: string, ): boolean; matchAnyHost(matchRegexObject: { protocols: string[]; host: string; path: RegExp }): boolean; <API key>( matchRegexObject: { protocols: string[]; host: string; path: RegExp }, remote: string, ): boolean; test(urlStr: string): boolean; testHost(host: string): boolean; testPath(path: string): boolean; testProtocol(protocol: string): boolean; toJSON(): { pattern: string }; toString(): string; update(options: { pattern: string }): void; static MATCH_ALL_URLS: string; static PROTOCOL_DELIMITER: string; } export class UrlMatchPatternList extends PropertyList<UrlMatchPattern> { constructor(parent: Property<PropertyDefinition>, list: string[]); test(urlStr: string): boolean; } export interface VariableDefinition extends PropertyDefinition { value?: any; type?: string; key?: string; } export class Variable extends Property<VariableDefinition> implements VariableDefinition { key?: string; type: string; value: any; constructor(definition?: VariableDefinition | { [index: string]: VariableDefinition }); cast(value: any): any; castIn(value: any): any; castOut(value: any): any; get(): any; set(value: any): void; toString(): string; update(options: VariableDefinition): void; valueOf(value: any): any; valueType(typeName: string, _noCast: boolean): string; static isVariable(obj: any): boolean; static types: { string: StringConstructor; boolean: BooleanConstructor; number: NumberConstructor; json: { in: (val: any) => string; out: (val: string) => any }; any: { in: <T>(val: T) => T; out: <T>(val: T) => T }; }; } export class VariableList extends PropertyList<Variable> { constructor(parent: Property<PropertyDefinition>, populate: Variable[]); replace(str: string, overrides?: VariableList): string; substitute<T>(obj: T, overrides?: VariableList, mutate?: boolean): T; syncFromObject( obj: { [key: string]: VariableDefinition }, track?: boolean, prune?: boolean, ): { created: string[]; updated: string[]; deleted: string[] } | undefined; syncToObject(obj?: { [key: string]: VariableDefinition }): { [key: string]: VariableDefinition }; static isVariableList(obj: any): boolean; } export interface <API key> extends PropertyDefinition { values?: VariableDefinition[]; } export class VariableScope extends Property<<API key>> implements <API key> { values?: VariableDefinition[]; constructor( definition: <API key> | VariableList | VariableDefinition[], layers?: VariableList[] | VariableList, ); addLayer(list: VariableList): void; clear(): void; get(key: string): any; has(variableName: string): boolean; set(key: string, value: any, type: string): void; syncVariablesFrom( obj: { [key: string]: VariableDefinition }, track?: boolean, prune?: boolean, ): { created: string[]; updated: string[]; deleted: string[] } | undefined; syncVariablesTo(obj?: { [key: string]: VariableDefinition }): { [key: string]: VariableDefinition }; toJSON(): any; toObject(excludeDisabled: boolean, caseSensitive: boolean): any; unset(key: string): void; variables(): { [key: string]: VariableDefinition }; static isVariableScope(obj: any): boolean; } export interface VersionDefinition extends <API key> { build?: string; major?: string; minor?: string; patch?: string; prerelease?: string; raw?: string; version?: string; } export class Version extends PropertyBase<VersionDefinition> implements VersionDefinition { build?: string; major?: string; minor?: string; patch?: string; prerelease?: string; raw?: string; string?: string; constructor(options?: VersionDefinition | string); set(value?: VersionDefinition | string): void; toString(): string; }
using System; using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.SpellCheck; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.SpellCheck { public class SpellCheckTests : <API key> { internal override (DiagnosticAnalyzer, CodeFixProvider) <API key>(Workspace workspace) => (null, new <API key>()); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @"class Goo { void Bar() { var a = new [|Fo|] } }"; await <API key>(text); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @"class Goo { void Bar() { void a = new [|Gooa|].ToString(); } }"; await <API key>(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Gooa", "Goo") }); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task TestInLocalType() { var text = @"class Foo { void Bar() { [|Foa|] a; } }"; await <API key>(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Foa", "Foo"), String.Format(FeaturesResources.Change_0_to_1, "Foa", "for") }); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task TestInFunc() { var text = @" using System; class Goo { void Bar(Func<[|Goa|]> f) { } }"; await <API key>(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Goa", "Goo") }); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task TestInExpression() { var text = @"class Program { void Main(string[] args) { var zzz = 2; var y = 2 + [|zza|]; } }"; await <API key>(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "zza", "zzz") }); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @"using System; public class Class1 { void F() { if (x is [|Boolea|]) {} } }"; await <API key>(text, new[] { String.Format(FeaturesResources.Change_0_to_1, "Boolea", "Boolean"), String.Format(FeaturesResources.Change_0_to_1, "Boolea", "bool") }); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @"class Program { void Main(string[] args) { var zzz = 2; var y = 2 + [|zza|]; } }"; var expected = @"class Program { void Main(string[] args) { var zzz = 2; var y = 2 + zzz; } }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task TestAfterDot() { var text = @"class Program { static void Main(string[] args) { Program.[|Mair|] } }"; var expected = @"class Program { static void Main(string[] args) { Program.Main } }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @"class Program { void Main(string[] args) { var z = new c().[|membr|] } } class c { protected int member { get; } }"; await <API key>(text); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task TestGenericName1() { var text = @"class Goo<T> { private [|Goo2|]<T> x; }"; var expected = @"class Goo<T> { private Goo<T> x; }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task TestGenericName2() { var text = @"class Goo<T> { private [|Goo2|] x; }"; var expected = @"class Goo<T> { private Goo x; }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task TestQualifiedName1() { var text = @"class Program { private object x = new [|Goo2|].Bar } class Goo { class Bar { } }"; var expected = @"class Program { private object x = new Goo.Bar } class Goo { class Bar { } }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task TestQualifiedName2() { var text = @"class Program { private object x = new Goo.[|Ba2|] } class Goo { public class Bar { } }"; var expected = @"class Program { private object x = new Goo.Bar } class Goo { public class Bar { } }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @"class Program { void Main(string[] args) { var z = new c().[|membr|].ToString(); } } class c { public int member { get; } }"; var expected = @"class Program { void Main(string[] args) { var z = new c().member.ToString(); } } class c { public int member { get; } }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @"class Program { void Main(string[] args) { } void Goo() { [|Method|](); } int Method(int argument) { } }"; await <API key>(text); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { [|Int3|] i; } }"; var expected = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { int i; } }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { [|Int3|] i; } }"; var expected = @" using System; using System.Collections.Generic; using System.Linq; class Program { void Main(string[] args) { Int32 i; } }"; await <API key>(text, expected, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task TestOnGeneric() { var text = @" interface Enumerable<T> { } class C { void Main(string[] args) { [|IEnumerable|]<int> x; } }"; var expected = @" interface Enumerable<T> { } class C { void Main(string[] args) { Enumerable<int> x; } }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { await <API key>( @"class AwesomeClass { void M() { var goo = new [|AwesomeClas()|]; } }", @"class AwesomeClass { void M() { var goo = new AwesomeClass(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task TestTestMissingName() { await <API key>( @"[assembly: Microsoft.CodeAnalysis.[||]]"); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] [WorkItem(12990, "https://github.com/dotnet/roslyn/issues/12990")] public async Task TestTrivia1() { var text = @" using System.Text; class C { void M() { /*leading*/ [|stringbuilder|] /*trailing*/ sb = null; } }"; var expected = @" using System.Text; class C { void M() { /*leading*/ StringBuilder /*trailing*/ sb = null; } }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] [WorkItem(13345, "https://github.com/dotnet/roslyn/issues/13345")] public async Task <API key>() { await <API key>( @"class C { void M() { // here 'for' is a keyword and snippet, so we should offer to spell check to it. [|foo|]; } }", @"class C { void M() { // here 'for' is a keyword and snippet, so we should offer to spell check to it. for; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] [WorkItem(18626, "https://github.com/dotnet/roslyn/issues/18626")] public async Task <API key>() { await <API key>( @"interface <API key> { void Method(); } class Program : <API key> { void [|<API key>|].Method() { } }", @"interface <API key> { void Method(); } class Program : <API key> { void <API key>.Method() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] [WorkItem(13345, "https://github.com/dotnet/roslyn/issues/13345")] public async Task <API key>() { await <API key>( @"class C { void M() { // here 'for' is *only* a snippet, and we should not offer to spell check to it. var v = [|goo|]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] [WorkItem(15733, "https://github.com/dotnet/roslyn/issues/15733")] public async Task TestMissingOnVar() { await <API key>( @" namespace bar { } class C { void M() { var y = [|var|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { await <API key>( @"class C<T> where T : [|umanaged|] { }", @"class C<T> where T : unmanaged { }"); } [WorkItem(28244, "https://github.com/dotnet/roslyn/issues/28244")] [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { await <API key>( @"public class SomeClass { public [|SomeClss|]() { } }", @"public class SomeClass { public SomeClass() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @" using System; class Program : IDisposable { void IDisposable.[|Dspose|] }"; var expected = @" using System; class Program : IDisposable { void IDisposable.Dispose }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @" using System; interface IInterface { void Generic<K, V>(); } class Program : IInterface { void IInterface.[|Generi|] }"; var expected = @" using System; interface IInterface { void Generic<K, V>(); } class Program : IInterface { void IInterface.Generic }"; await <API key>(text, expected); } [Fact, Trait(Traits.Feature, Traits.Features.<API key>)] public async Task <API key>() { var text = @" using System; interface IInterface { int this[int i] { get; } } class Program : IInterface { void IInterface.[|thi|] }"; var expected = @" using System; interface IInterface { int this[int i] { get; } } class Program : IInterface { void IInterface.this }"; await <API key>(text, expected); } } }
require 'test_helper' class RemoteStripeTest < Test::Unit::TestCase def setup @gateway = StripeGateway.new(fixtures(:stripe)) @amount = 100 @credit_card = credit_card('4242424242424242') @declined_card = credit_card('4000000000000002') @new_credit_card = credit_card('5105105105105100') @options = { :currency => "USD", :description => 'ActiveMerchant Test Purchase', :email => 'wow@example.com' } end def <API key> transcript = capture_transcript(@gateway) do @gateway.purchase(@amount, @credit_card, @options) end transcript = @gateway.scrub(transcript) assert_scrubbed(@credit_card.number, transcript) assert_scrubbed(@credit_card.verification_value, transcript) assert_scrubbed(@gateway.options[:login], transcript) end def <API key> assert response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal "charge", response.params["object"] assert response.params["paid"] assert_equal "ActiveMerchant Test Purchase", response.params["description"] assert_equal "wow@example.com", response.params["metadata"]["email"] end def <API key> custom_options = @options.merge(:eci => 'recurring') assert response = @gateway.purchase(@amount, @credit_card, custom_options) assert_success response assert_equal "charge", response.params["object"] assert response.params["paid"] assert_equal "ActiveMerchant Test Purchase", response.params["description"] assert_equal "wow@example.com", response.params["metadata"]["email"] end def <API key> assert response = @gateway.purchase(@amount, @declined_card, @options) assert_failure response assert_match %r{Your card was declined}, response.message assert_match Gateway::STANDARD_ERROR_CODE[:card_declined], response.error_code assert_match /ch_[a-zA-Z\d]+/, response.authorization end def test_<API key> assert authorization = @gateway.authorize(@amount, @credit_card, @options) assert_success authorization refute authorization.params["captured"] assert_equal "ActiveMerchant Test Purchase", authorization.params["description"] assert_equal "wow@example.com", authorization.params["metadata"]["email"] assert capture = @gateway.capture(@amount, authorization.authorization) assert_success capture end def test_<API key> assert authorization = @gateway.authorize(@amount, @credit_card, @options) assert_success authorization refute authorization.params["captured"] assert void = @gateway.void(authorization.authorization) assert_success void end def <API key> assert response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert response.authorization assert void = @gateway.void(response.authorization) assert_success void end def <API key> assert void = @gateway.void("<API key>") assert_failure void assert_match %r{<API key>}, void.message end def <API key> assert response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert response.authorization assert refund = @gateway.refund(@amount - 20, response.authorization) assert_success refund end def <API key> destination = fixtures(:stripe_destination)[:stripe_user_id] assert response = @gateway.purchase(@amount, @credit_card, @options.merge(destination: destination)) assert_success response assert refund = @gateway.refund(@amount - 20, response.authorization, reverse_transfer: true) assert_success refund assert_equal "Transaction approved", refund.message end def <API key> assert refund = @gateway.refund(@amount, "<API key>") assert_failure refund assert_match %r{<API key>}, refund.message end def <API key> assert response = @gateway.verify(@credit_card, @options) assert_success response assert_equal "Transaction approved", response.message assert_equal "wow@example.com", response.params["metadata"]["email"] assert_equal "charge", response.params["object"] assert_success response.responses.last, "The void should succeed" assert response.responses.last.params["refunded"] end def <API key> assert response = @gateway.verify(@declined_card, @options) assert_failure response assert_match %r{Your card was declined}, response.message end def <API key> assert response = @gateway.store(@credit_card, description: "TheDescription", email: "email@example.com") assert_success response assert_equal "customer", response.params["object"] assert_equal "TheDescription", response.params["description"] assert_equal "email@example.com", response.params["email"] first_card = response.params["sources"]["data"].first assert_equal response.params["default_source"], first_card["id"] assert_equal @credit_card.last_digits, first_card["last4"] end def <API key> assert response = @gateway.store(@credit_card) assert_success response assert response = @gateway.store(@new_credit_card, customer: response.params['id'], email: "email@example.com", description: "TheDesc") assert_success response assert_equal 2, response.responses.size card_response = response.responses[0] assert_equal "card", card_response.params["object"] assert_equal @new_credit_card.last_digits, card_response.params["last4"] customer_response = response.responses[1] assert_equal "customer", customer_response.params["object"] assert_equal "TheDesc", customer_response.params["description"] assert_equal "email@example.com", customer_response.params["email"] assert_equal 2, customer_response.params["sources"]["total_count"] end def <API key> assert store = @gateway.store(@credit_card) assert_success store assert response = @gateway.purchase(@amount, store.authorization) assert_success response assert_equal "Transaction approved", response.message assert response.params["paid"] assert_equal "4242", response.params["source"]["last4"] end def <API key> assert <API key> = @gateway.store(@credit_card) assert_success <API key> assert <API key> = @gateway.store(@new_credit_card, customer: <API key>.params['id']) assert_success <API key> assert response = @gateway.purchase(@amount, <API key>.authorization) assert_success response assert_equal "5100", response.params["source"]["last4"] end def <API key> assert store = @gateway.store(@credit_card) assert_success store recharge_options = @options.merge(:customer => store.params["id"]) <API key> do response = @gateway.purchase(@amount, nil, recharge_options) assert_success response assert_equal "4242", response.params["source"]["last4"] end end def <API key> creation = @gateway.store(@credit_card, {:description => "Active Merchant Unstore Customer"}) card_id = creation.params['sources']['data'].first['id'] assert response = @gateway.unstore(creation.authorization) assert_success response assert_equal card_id, response.params['id'] assert_equal true, response.params['deleted'] assert_equal "Transaction approved", response.message end def <API key> creation = @gateway.store(@credit_card, {:description => "Active Merchant Unstore Customer"}) card_id = creation.params['sources']['data'].first['id'] customer_id = creation.params["id"] <API key> do response = @gateway.unstore(customer_id, card_id) assert_success response assert_equal true, response.params['deleted'] end end def test_invalid_login gateway = StripeGateway.new(:login => '<API key>') assert response = gateway.purchase(@amount, @credit_card, @options) assert_failure response assert_match "Invalid API Key provided", response.message end def <API key> @credit_card.track_data = '%B378282246310005^LONGSON/LONGBOB^1705101130504392?' assert response = @gateway.purchase(@amount, @credit_card, @options) assert_success response assert_equal "charge", response.params["object"] assert response.params["paid"] end def test_card_present_<API key> @credit_card.track_data = '%B378282246310005^LONGSON/LONGBOB^1705101130504392?' assert authorization = @gateway.authorize(@amount, @credit_card, @options) assert_success authorization refute authorization.params["captured"] assert capture = @gateway.capture(@amount, authorization.authorization) assert_success capture end def <API key> assert response = @gateway.purchase(@amount, @credit_card, @options.merge(:customer => '1234')) assert_success response assert_equal "charge", response.params["object"] assert response.params["paid"] end def <API key> assert response = @gateway.purchase(@amount, @credit_card, @options.merge(:expand => 'balance_transaction')) assert_success response assert response.params['balance_transaction'].is_a?(Hash) assert_equal 'balance_transaction', response.params['balance_transaction']['object'] end def <API key> creation = @gateway.store(@credit_card, {:description => "Active Merchant Update Credit Card"}) customer_id = creation.params['id'] card_id = creation.params['sources']['data'].first['id'] assert response = @gateway.update(customer_id, card_id, { :name => "John Doe", :address_line1 => "123 Main Street", :address_city => "Pleasantville", :address_state => "NY", :address_zip => "12345", :exp_year => Time.now.year + 2, :exp_month => 6 }) assert_success response assert_equal "John Doe", response.params["name"] assert_equal "123 Main Street", response.params["address_line1"] assert_equal "Pleasantville", response.params["address_city"] assert_equal "NY", response.params["address_state"] assert_equal "12345", response.params["address_zip"] assert_equal Time.now.year + 2, response.params["exp_year"] assert_equal 6, response.params["exp_month"] end def <API key> card = credit_card('4242424242424241') assert response = @gateway.purchase(@amount, card, @options) assert_failure response assert_match Gateway::STANDARD_ERROR_CODE[:incorrect_number], response.error_code end def <API key> card = credit_card('-1') assert response = @gateway.purchase(@amount, card, @options) assert_failure response assert_match Gateway::STANDARD_ERROR_CODE[:invalid_number], response.error_code end def <API key> card = credit_card('4242424242424242', month: 16) assert response = @gateway.purchase(@amount, card, @options) assert_failure response assert_match Gateway::STANDARD_ERROR_CODE[:invalid_expiry_date], response.error_code end def <API key> card = credit_card('4242424242424242', year: 'xx') assert response = @gateway.purchase(@amount, card, @options) assert_failure response assert_match Gateway::STANDARD_ERROR_CODE[:invalid_expiry_date], response.error_code end def <API key> card = credit_card('4000000000000069') assert response = @gateway.purchase(@amount, card, @options) assert_failure response assert_match Gateway::STANDARD_ERROR_CODE[:expired_card], response.error_code end def <API key> card = credit_card('4242424242424242', verification_value: -1) assert response = @gateway.purchase(@amount, card, @options) assert_failure response assert_match Gateway::STANDARD_ERROR_CODE[:invalid_cvc], response.error_code end def <API key> card = credit_card('4000000000000127') assert response = @gateway.purchase(@amount, card, @options) assert_failure response assert_match Gateway::STANDARD_ERROR_CODE[:incorrect_cvc], response.error_code end def <API key> card = credit_card('4000000000000119') assert response = @gateway.purchase(@amount, card, @options) assert_failure response assert_match Gateway::STANDARD_ERROR_CODE[:processing_error], response.error_code end def <API key> assert response = @gateway.purchase(@amount, @credit_card, <API key>: "Eggcellent Description") assert_success response assert_equal "Eggcellent Description", response.params["<API key>"] end end
#include <limits.h> #include "src/base/atomic-utils.h" #include "testing/gtest/include/gtest/gtest.h" namespace v8 { namespace base { TEST(AtomicNumber, Constructor) { // Test some common types. AtomicNumber<int> zero_int; AtomicNumber<size_t> zero_size_t; AtomicNumber<intptr_t> zero_intptr_t; EXPECT_EQ(0, zero_int.Value()); EXPECT_EQ(0u, zero_size_t.Value()); EXPECT_EQ(0, zero_intptr_t.Value()); } TEST(AtomicNumber, Value) { AtomicNumber<int> a(1); EXPECT_EQ(1, a.Value()); AtomicNumber<int> b(-1); EXPECT_EQ(-1, b.Value()); AtomicNumber<size_t> c(1); EXPECT_EQ(1u, c.Value()); AtomicNumber<size_t> d(static_cast<size_t>(-1)); EXPECT_EQ(std::numeric_limits<size_t>::max(), d.Value()); } TEST(AtomicNumber, SetValue) { AtomicNumber<int> a(1); a.SetValue(-1); EXPECT_EQ(-1, a.Value()); } TEST(AtomicNumber, Increment) { AtomicNumber<int> a(std::numeric_limits<int>::max()); a.Increment(1); EXPECT_EQ(std::numeric_limits<int>::min(), a.Value()); // Check that potential signed-ness of the underlying storage has no impact // on unsigned types. AtomicNumber<size_t> b(std::numeric_limits<intptr_t>::max()); b.Increment(1); EXPECT_EQ(static_cast<size_t>(std::numeric_limits<intptr_t>::max()) + 1, b.Value()); // Should work as decrement as well. AtomicNumber<size_t> c(1); c.Increment(-1); EXPECT_EQ(0u, c.Value()); c.Increment(-1); EXPECT_EQ(std::numeric_limits<size_t>::max(), c.Value()); } TEST(AtomicNumber, Decrement) { AtomicNumber<size_t> a(std::numeric_limits<size_t>::max()); a.Increment(1); EXPECT_EQ(0u, a.Value()); a.Decrement(1); EXPECT_EQ(std::numeric_limits<size_t>::max(), a.Value()); } TEST(AtomicNumber, <API key>) { AtomicNumber<size_t> a(0u); AtomicNumber<size_t> b(std::numeric_limits<size_t>::max()); a += b.Value(); EXPECT_EQ(a.Value(), b.Value()); EXPECT_EQ(b.Value(), std::numeric_limits<size_t>::max()); } TEST(AtomicNumber, <API key>) { AtomicNumber<size_t> a(std::numeric_limits<size_t>::max()); AtomicNumber<size_t> b(std::numeric_limits<size_t>::max()); a -= b.Value(); EXPECT_EQ(a.Value(), 0u); EXPECT_EQ(b.Value(), std::numeric_limits<size_t>::max()); } namespace { enum TestFlag : base::AtomicWord { kA, kB, kC, }; } // namespace TEST(AtomicValue, Initial) { AtomicValue<TestFlag> a(kA); EXPECT_EQ(TestFlag::kA, a.Value()); } TEST(AtomicValue, TrySetValue) { AtomicValue<TestFlag> a(kA); EXPECT_FALSE(a.TrySetValue(kB, kC)); EXPECT_TRUE(a.TrySetValue(kA, kC)); EXPECT_EQ(TestFlag::kC, a.Value()); } TEST(AtomicValue, SetValue) { AtomicValue<TestFlag> a(kB); a.SetValue(kC); EXPECT_EQ(TestFlag::kC, a.Value()); } TEST(AtomicValue, WithVoidStar) { AtomicValue<void*> a(nullptr); AtomicValue<void*> dummy(nullptr); EXPECT_EQ(nullptr, a.Value()); a.SetValue(&a); EXPECT_EQ(&a, a.Value()); EXPECT_FALSE(a.TrySetValue(nullptr, &dummy)); EXPECT_TRUE(a.TrySetValue(&a, &dummy)); EXPECT_EQ(&dummy, a.Value()); } TEST(<API key>, Initial) { <API key><TestFlag> a(kA); EXPECT_EQ(TestFlag::kA, a.Value()); } TEST(<API key>, SetValue) { <API key><TestFlag> a(kB); a.SetValue(kC); EXPECT_EQ(TestFlag::kC, a.Value()); } TEST(<API key>, WithVoidStar) { <API key><void*> a(nullptr); <API key><void*> dummy(nullptr); EXPECT_EQ(nullptr, a.Value()); a.SetValue(&a); EXPECT_EQ(&a, a.Value()); } TEST(<API key>, Construction) { <API key><TestFlag> a(kA); TestFlag b = kA; <API key><TestFlag>* ptr = <API key><TestFlag>::FromAddress(&b); EXPECT_EQ(ptr->Value(), a.Value()); } TEST(<API key>, <API key>) { <API key><void*> a(nullptr); void* b = nullptr; <API key><void*>* ptr = <API key><void*>::FromAddress(&b); EXPECT_EQ(ptr->Value(), a.Value()); } namespace { enum TestSetValue { kAA, kBB, kCC, kLastValue = kCC }; } // namespace TEST(AtomicEnumSet, Constructor) { AtomicEnumSet<TestSetValue> a; EXPECT_TRUE(a.IsEmpty()); EXPECT_FALSE(a.Contains(kAA)); } TEST(AtomicEnumSet, AddSingle) { AtomicEnumSet<TestSetValue> a; a.Add(kAA); EXPECT_FALSE(a.IsEmpty()); EXPECT_TRUE(a.Contains(kAA)); EXPECT_FALSE(a.Contains(kBB)); EXPECT_FALSE(a.Contains(kCC)); } TEST(AtomicEnumSet, AddOtherSet) { AtomicEnumSet<TestSetValue> a; AtomicEnumSet<TestSetValue> b; a.Add(kAA); EXPECT_FALSE(a.IsEmpty()); EXPECT_TRUE(b.IsEmpty()); b.Add(a); EXPECT_FALSE(b.IsEmpty()); EXPECT_TRUE(a.Contains(kAA)); EXPECT_TRUE(b.Contains(kAA)); } TEST(AtomicEnumSet, RemoveSingle) { AtomicEnumSet<TestSetValue> a; a.Add(kAA); a.Add(kBB); EXPECT_TRUE(a.Contains(kAA)); EXPECT_TRUE(a.Contains(kBB)); a.Remove(kAA); EXPECT_FALSE(a.Contains(kAA)); EXPECT_TRUE(a.Contains(kBB)); } TEST(AtomicEnumSet, RemoveOtherSet) { AtomicEnumSet<TestSetValue> a; AtomicEnumSet<TestSetValue> b; a.Add(kAA); a.Add(kBB); b.Add(kBB); a.Remove(b); EXPECT_TRUE(a.Contains(kAA)); EXPECT_FALSE(a.Contains(kBB)); EXPECT_FALSE(a.Contains(kCC)); } TEST(AtomicEnumSet, RemoveEmptySet) { AtomicEnumSet<TestSetValue> a; AtomicEnumSet<TestSetValue> b; a.Add(kAA); a.Add(kBB); EXPECT_TRUE(a.Contains(kAA)); EXPECT_TRUE(a.Contains(kBB)); EXPECT_FALSE(a.Contains(kCC)); EXPECT_TRUE(b.IsEmpty()); a.Remove(b); EXPECT_TRUE(a.Contains(kAA)); EXPECT_TRUE(a.Contains(kBB)); EXPECT_FALSE(a.Contains(kCC)); } TEST(AtomicEnumSet, Intersect) { AtomicEnumSet<TestSetValue> a; AtomicEnumSet<TestSetValue> b; a.Add(kAA); b.Add(kCC); a.Intersect(b); EXPECT_TRUE(a.IsEmpty()); } TEST(AtomicEnumSet, ContainsAnyOf) { AtomicEnumSet<TestSetValue> a; AtomicEnumSet<TestSetValue> b; a.Add(kAA); b.Add(kCC); EXPECT_FALSE(a.ContainsAnyOf(b)); b.Add(kAA); EXPECT_TRUE(a.ContainsAnyOf(b)); } TEST(AtomicEnumSet, Equality) { AtomicEnumSet<TestSetValue> a; AtomicEnumSet<TestSetValue> b; a.Add(kAA); EXPECT_FALSE(a == b); EXPECT_TRUE(a != b); b.Add(kAA); EXPECT_TRUE(a == b); EXPECT_FALSE(a != b); } } // namespace base } // namespace v8
These are some of the configuration files that are used on the server - **[index.html](./index.html)** `/usr/share/nginx/html/index.html` nginx index file - **[default](./default)** `/etc/nginx/sites-enabled/default` nginx config file - **[monitorix.conf](./monitorix.conf)** `/etc/monitorix/monitorix.conf` monitorix config file - **[shiny-server.conf](./shiny-server.conf)** `/etc/shiny-server/shiny-server.conf` shiny server config file
module.exports = function (babel) { var Plugin = babel.Plugin; var t = babel.types; return new Plugin("<API key>", { visitor: { // In browsers that do not support defining non-enumerable // properties, defining any new methods on Array.prototype means // those methods will become visible to for-in loops. This transform // solves that problem by wrapping the object expression of every // for-in loop with a call to babelHelpers.sanitizeForInObject. ForInStatement: function (node) { node.right = t.callExpression( t.memberExpression( t.identifier("babelHelpers"), t.identifier("sanitizeForInObject"), false ), [node.right] ); } } }); };
#if HAVE_CONFIG_H #include "clamav-config.h" #endif #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #if HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifndef O_BINARY #define O_BINARY 0 #endif #include "others.h" #include "scanners.h" /* FIXME: use unicode detection and normalization from edwin */ static unsigned int u2a(uint8_t *dest, unsigned int len) { uint8_t *src = dest; unsigned int i,j; if (len<2) return len; if (len>4 && src[0]==0xff && src[1]==0xfe && src[2]) { len-=2; src+=2; } else { unsigned int cnt=0; j = (len > 20) ? 20 : (len&~1); for (i=0; i<j; i+=2) cnt+=(src[i]!=0 && src[i+1]==0); if (cnt*4 < j) return len; } j=len; len>>=1; for (i=0; i<j; i+=2) *dest++ = src[i]; return len; } struct MT { uint32_t mt[624]; uint32_t items; uint32_t *next; }; static uint8_t MT_getnext(struct MT *MT) { uint32_t r; if (!--MT->items) { uint32_t *mt = MT->mt; unsigned int i; MT->items = 624; MT->next = mt; for (i=0; i<227; i++) mt[i] = ((((mt[i] ^ mt[i+1])&0x7ffffffe)^mt[i])>>1)^((0-(mt[i+1]&1))&0x9908b0df)^mt[i+397]; for (; i<623; i++) mt[i] = ((((mt[i] ^ mt[i+1])&0x7ffffffe)^mt[i])>>1)^((0-(mt[i+1]&1))&0x9908b0df)^mt[i-227]; mt[623] = ((((mt[623] ^ mt[0])&0x7ffffffe)^mt[623])>>1)^((0-(mt[0]&1))&0x9908b0df)^mt[i-227]; } r = *(MT->next++); r ^= (r >> 11); r ^= ((r & 0xff3a58ad) << 7); r ^= ((r & 0xffffdf8c) << 15); r ^= (r >> 18); return (uint8_t)(r >> 1); } static void MT_decrypt(uint8_t *buf, unsigned int size, uint32_t seed) { struct MT MT; unsigned int i; uint32_t *mt = MT.mt; *mt=seed; for(i=1; i<624; i++) mt[i] = i+0x6c078965*((mt[i-1]>>30)^mt[i-1]); MT.items = 1; while(size *buf++ ^= MT_getnext(&MT); } struct UNP { uint8_t *outputbuf; uint8_t *inputbuf; uint32_t cur_output; uint32_t cur_input; uint32_t usize; uint32_t csize; uint32_t bits_avail; union { uint32_t full; struct { #if WORDS_BIGENDIAN != 0 uint16_t h; uint16_t l; #else uint16_t l; uint16_t h; #endif } half; } bitmap; uint32_t error; }; static uint32_t getbits(struct UNP *UNP, uint32_t size) { UNP->bitmap.half.h = 0; if (size > UNP->bits_avail && ((size - UNP->bits_avail - 1)/16+1)*2 > UNP->csize - UNP->cur_input) { cli_dbgmsg("autoit: getbits() - not enough bits available\n"); UNP->error = 1; return 0; /* won't infloop nor spam */ } while (size) { if (!UNP->bits_avail) { UNP->bitmap.half.l |= UNP->inputbuf[UNP->cur_input++]<<8; UNP->bitmap.half.l |= UNP->inputbuf[UNP->cur_input++]; UNP->bits_avail = 16; } UNP->bitmap.full<<=1; UNP->bits_avail size } return (uint32_t)UNP->bitmap.half.h; } static int ea05(int desc, cli_ctx *ctx, char *tmpd) { uint8_t b[300], comp; uint8_t *buf = b; uint32_t s, m4sum=0; int i; unsigned int files=0; char tempfile[1024]; struct UNP UNP; if (cli_readn(desc, buf, 16)!=16) return CL_CLEAN; for (i=0; i<16; i++) m4sum += buf[i]; while(!ctx->limits || !ctx->limits->maxfiles || files < ctx->limits->maxfiles) { buf = b; if (cli_readn(desc, buf, 8)!=8) return CL_CLEAN; /* MT_decrypt(buf,4,0x16fa); waste of time */ if((uint32_t)cli_readint32((char *)buf) != 0xceb06dff) { cli_dbgmsg("autoit: no FILE magic found, extraction complete\n"); return CL_CLEAN; } s = cli_readint32((char *)buf+4) ^ 0x29bc; if ((int32_t)s<0) return CL_CLEAN; /* the original code wouldn't seek back here */ if(cli_debug_flag && s<sizeof(b)) { if (cli_readn(desc, buf, s)!=(int)s) return CL_CLEAN; buf[s]='\0'; MT_decrypt(buf,s,s+0xa25e); cli_dbgmsg("autoit: magic string '%s'\n", buf); } else { lseek(desc, s, SEEK_CUR); } if (cli_readn(desc, buf, 4)!=4) return CL_CLEAN; s = cli_readint32((char *)buf) ^ 0x29ac; if ((int32_t)s<0) return CL_CLEAN; /* the original code wouldn't seek back here */ if (cli_debug_flag && s<sizeof(b)) { if (cli_readn(desc, buf, s)!=(int)s) return CL_CLEAN; MT_decrypt(buf,s,s+0xf25e); buf[s]='\0'; cli_dbgmsg("autoit: original filename '%s'\n", buf); } else { lseek(desc, s, SEEK_CUR); } if (cli_readn(desc, buf, 13)!=13) return CL_CLEAN; comp = *buf; UNP.csize = cli_readint32((char *)buf+1) ^ 0x45aa; if ((int32_t)UNP.csize<0) { cli_dbgmsg("autoit: bad file size - giving up\n"); return CL_CLEAN; } lseek(desc, 16, SEEK_CUR); if(!UNP.csize) { cli_dbgmsg("autoit: skipping empty file\n"); continue; } cli_dbgmsg("autoit: compressed size: %x\n", UNP.csize); cli_dbgmsg("autoit: advertised uncompressed size %x\n", cli_readint32((char *)buf+5) ^ 0x45aa); cli_dbgmsg("autoit: ref chksum: %x\n", cli_readint32((char *)buf+9) ^ 0xc3d2); if(ctx->limits && ctx->limits->maxfilesize && UNP.csize > ctx->limits->maxfilesize) { cli_dbgmsg("autoit: skipping file due to size limit (%u, max: %lu)\n", UNP.csize, ctx->limits->maxfilesize); lseek(desc, UNP.csize, SEEK_CUR); continue; } if (!(buf = cli_malloc(UNP.csize))) return CL_EMEM; if (cli_readn(desc, buf, UNP.csize)!=(int)UNP.csize) { cli_dbgmsg("autoit: failed to read compressed stream. broken/truncated file?\n"); free(buf); return CL_CLEAN; } MT_decrypt(buf,UNP.csize,0x22af+m4sum); if (comp == 1) { cli_dbgmsg("autoit: file is compressed\n"); if (cli_readint32((char *)buf)!=0x35304145) { cli_dbgmsg("autoit: bad magic or unsupported version\n"); free(buf); continue; } if(!(UNP.usize = be32_to_host(*(uint32_t *)(buf+4)))) UNP.usize = UNP.csize; /* only a specifically crafted or badly corrupted sample should land here */ if(ctx->limits && ctx->limits->maxfilesize && UNP.usize > ctx->limits->maxfilesize) { cli_dbgmsg("autoit: skipping file due to size limit (%u, max: %lu)\n", UNP.csize, ctx->limits->maxfilesize); free(buf); continue; } if (!(UNP.outputbuf = cli_malloc(UNP.usize))) { free(buf); return CL_EMEM; } cli_dbgmsg("autoit: uncompressed size again: %x\n", UNP.usize); UNP.inputbuf = buf; UNP.cur_output = 0; UNP.cur_input = 8; UNP.bitmap.full = 0; UNP.bits_avail = 0; UNP.error = 0; while (!UNP.error && UNP.cur_output < UNP.usize) { if (getbits(&UNP, 1)) { uint32_t bb, bs, addme=0; bb = getbits(&UNP, 15); if ((bs = getbits(&UNP, 2))==3) { addme = 3; if((bs = getbits(&UNP, 3))==7) { addme = 10; if((bs = getbits(&UNP, 5))==31) { addme = 41; if((bs = getbits(&UNP, 8))==255) { addme = 296; while((bs = getbits(&UNP, 8))==255) { addme+=255; } } } } } bs += 3+addme; if(!CLI_ISCONTAINED(UNP.outputbuf, UNP.usize, &UNP.outputbuf[UNP.cur_output], bs) || !CLI_ISCONTAINED(UNP.outputbuf, UNP.usize, &UNP.outputbuf[UNP.cur_output-bb], bs)) { UNP.error = 1; break; } while(bs UNP.outputbuf[UNP.cur_output]=UNP.outputbuf[UNP.cur_output-bb]; UNP.cur_output++; } } else { UNP.outputbuf[UNP.cur_output] = (uint8_t)getbits(&UNP, 8); UNP.cur_output++; } } free(buf); /* Sometimes the autoit exe is in turn packed/lamed with a runtime compressor and similar shit. * However, since the autoit script doesn't compress a second time very well, chances are we're * still able to match the headers and unpack something (see sample 0811129) * I'd rather unpack something (although possibly highly corrupted) than nothing at all * * - Fortuna audaces iuvat - */ if (UNP.error) cli_dbgmsg("autoit: decompression error - partial file may exist\n"); } else { cli_dbgmsg("autoit: file is not compressed\n"); UNP.outputbuf = buf; UNP.usize = UNP.csize; } files++; /* FIXME: TODO send to text notmalization */ /* FIXME: ad-interim solution. ideally we should detect text and turn it to ascii */ UNP.usize = u2a(UNP.outputbuf, UNP.usize); snprintf(tempfile, 1023, "%s/autoit.%.3u", tmpd, files); tempfile[1023]='\0'; if((i = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) { cli_dbgmsg("autoit: Can't create file %s\n", tempfile); free(UNP.outputbuf); return CL_EIO; } if(cli_writen(i, UNP.outputbuf, UNP.usize) != (int32_t)UNP.usize) { cli_dbgmsg("autoit: cannot write %d bytes\n", UNP.usize); close(i); free(UNP.outputbuf); return CL_EIO; } free(UNP.outputbuf); if(cli_leavetemps_flag) cli_dbgmsg("autoit: file extracted to %s\n", tempfile); else cli_dbgmsg("autoit: file successfully extracted\n"); fsync(i); lseek(i, 0, SEEK_SET); if(cli_magic_scandesc(i, ctx) == CL_VIRUS) { close(i); if(!cli_leavetemps_flag) unlink(tempfile); return CL_VIRUS; } close(i); if(!cli_leavetemps_flag) unlink(tempfile); } cli_dbgmsg("autoit: files limit reached (max: %u)\n", ctx->limits->maxfiles); return CL_EMAXFILES; } #ifdef FPU_WORDS_BIGENDIAN #define ROFL(a,b) (( a << (b % (sizeof(a)<<3) )) | (a >> ( (sizeof(a)<<3) - (b % (sizeof(a)<<3 )) ) )) struct LAME { uint32_t c0; uint32_t c1; uint32_t grp1[17]; }; static double LAME_fpusht(struct LAME *l) { union { double as_double; struct { #if FPU_WORDS_BIGENDIAN == 0 uint32_t lo; uint32_t hi; #else uint32_t hi; uint32_t lo; #endif } as_uint; } ret; uint32_t rolled = ROFL(l->grp1[l->c0],9) + ROFL(l->grp1[l->c1],13); l->grp1[l->c0] = rolled; if (!l->c0--) l->c0 = 16; if (!l->c1--) l->c1 = 16; /* if (l->grp1[l->c0] == l->grp2[0]) { */ /* if (!memcmp(l->grp1, (uint32_t *)l + 0x24 - l->c0, 0x44)) */ /* return 0.0; */ ret.as_uint.lo = rolled << 0x14; ret.as_uint.hi = 0x3ff00000 | (rolled >> 0xc); return ret.as_double - 1.0; } static void LAME_srand(struct LAME *l, uint32_t seed) { unsigned int i; for (i=0; i<17; i++) { seed *= 0x53A9B4FB; /*1403630843*/ seed = 1 - seed; l->grp1[i] = seed; } l->c0 = 0; l->c1 = 10; for (i = 0; i < 9; i++) LAME_fpusht(l); } static uint8_t LAME_getnext(struct LAME *l) { double x; uint8_t ret; LAME_fpusht(l); x = LAME_fpusht(l) * 256.0; if ((int32_t)x < 256) ret = (uint8_t)x; else ret=0xff; return ret; } static void LAME_decrypt (uint8_t *cypher, uint32_t size, uint16_t seed) { struct LAME lame; /* mt_srand_timewrap(struct srand_struc bufDC); */ LAME_srand(&lame, (uint32_t)seed); while(size *cypher++^=LAME_getnext(&lame); } static int ea06(int desc, cli_ctx *ctx, char *tmpd) { uint8_t b[600], comp, script; uint8_t *buf; uint32_t s; int i; unsigned int files=0; char tempfile[1024]; const char prefixes[] = { '\0', '\0', '@', '$', '\0', '.', '"', ' const char *opers[] = { ",", "=", ">", "<", "<>", ">=", "<=", "(", ")", "+", "-", "/", "*", "&", "[", "]", "==", "^", "+=", "-=", "/=", "*=", "&=" }; struct UNP UNP; /* Useless due to a bug in CRC calculation - LMAO!!1 */ /* if (cli_readn(desc, buf, 24)!=24) */ /* return CL_CLEAN; */ /* LAME_decrypt(buf, 0x10, 0x99f2); */ /* buf+=0x10; */ lseek(desc, 16, SEEK_CUR); /* for now we just skip the garbage */ while(!ctx->limits || !ctx->limits->maxfiles || files < ctx->limits->maxfiles) { buf = b; if (cli_readn(desc, buf, 8)!=8) return CL_CLEAN; /* LAME_decrypt(buf, 4, 0x18ee); waste of time */ if(cli_readint32((char *)buf) != 0x52ca436b) { cli_dbgmsg("autoit: no FILE magic found, giving up\n"); return CL_CLEAN; } script = 0; s = cli_readint32((char *)buf+4) ^ 0xadbc; if ((int32_t)(s*2)<0) return CL_CLEAN; /* the original code wouldn't seek back here */ if(s<300) { if (cli_readn(desc, buf, s*2)!=(int)s*2) return CL_CLEAN; LAME_decrypt(buf,s*2,s+0xb33f); u2a(buf,s*2); cli_dbgmsg("autoit: magic string '%s'\n", buf); if (s==19 && !memcmp(">>>AUTOIT SCRIPT<<<", buf, 19)) script = 1; } else { cli_dbgmsg("autoit: magic string too long to print\n"); lseek(desc, s*2, SEEK_CUR); } if (cli_readn(desc, buf, 4)!=4) return CL_CLEAN; s = cli_readint32((char *)buf) ^ 0xf820; if ((int32_t)(s*2)<0) return CL_CLEAN; /* the original code wouldn't seek back here */ if(cli_debug_flag && s<300) { if (cli_readn(desc, buf, s*2)!=(int)s*2) return CL_CLEAN; LAME_decrypt(buf,s*2,s+0xf479); buf[s*2]='\0'; buf[s*2+1]='\0'; u2a(buf,s*2); cli_dbgmsg("autoit: original filename '%s'\n", buf); } else { lseek(desc, s*2, SEEK_CUR); } if (cli_readn(desc, buf, 13)!=13) return CL_CLEAN; comp = *buf; UNP.csize = cli_readint32((char *)buf+1) ^ 0x87bc; if ((int32_t)UNP.csize<0) { cli_dbgmsg("autoit: bad file size - giving up\n"); return CL_CLEAN; } lseek(desc, 16, SEEK_CUR); if(!UNP.csize) { cli_dbgmsg("autoit: skipping empty file\n"); continue; } cli_dbgmsg("autoit: compressed size: %x\n", UNP.csize); cli_dbgmsg("autoit: advertised uncompressed size %x\n", cli_readint32((char *)buf+5) ^ 0x87bc); cli_dbgmsg("autoit: ref chksum: %x\n", cli_readint32((char *)buf+9) ^ 0xa685); if(ctx->limits && ctx->limits->maxfilesize && UNP.csize > ctx->limits->maxfilesize) { cli_dbgmsg("autoit: skipping file due to size limit (%u, max: %lu)\n", UNP.csize, ctx->limits->maxfilesize); lseek(desc, UNP.csize, SEEK_CUR); continue; } files++; if (!(buf = cli_malloc(UNP.csize))) return CL_EMEM; if (cli_readn(desc, buf, UNP.csize)!=(int)UNP.csize) { cli_dbgmsg("autoit: failed to read compressed stream. broken/truncated file?\n"); free(buf); return CL_CLEAN; } LAME_decrypt(buf,UNP.csize,0x2477 /* + m4sum (broken by design) */ ); if (comp == 1) { cli_dbgmsg("autoit: file is compressed\n"); if (cli_readint32((char *)buf)!=0x36304145) { cli_dbgmsg("autoit: bad magic or unsupported version\n"); free(buf); continue; } if(!(UNP.usize = be32_to_host(*(uint32_t *)(buf+4)))) UNP.usize = UNP.csize; /* only a specifically crafted or badly corrupted sample should land here */ if(ctx->limits && ctx->limits->maxfilesize && UNP.usize > ctx->limits->maxfilesize) { free(buf); continue; } if (!(UNP.outputbuf = cli_malloc(UNP.usize))) { free(buf); return CL_EMEM; } cli_dbgmsg("autoit: uncompressed size again: %x\n", UNP.usize); UNP.inputbuf = buf; UNP.cur_output = 0; UNP.cur_input = 8; UNP.bitmap.full = 0; UNP.bits_avail = 0; UNP.error = 0; while (!UNP.error && UNP.cur_output < UNP.usize) { if (!getbits(&UNP, 1)) { uint32_t bb, bs, addme=0; bb = getbits(&UNP, 15); if ((bs = getbits(&UNP, 2))==3) { addme = 3; if((bs = getbits(&UNP, 3))==7) { addme = 10; if((bs = getbits(&UNP, 5))==31) { addme = 41; if((bs = getbits(&UNP, 8))==255) { addme = 296; while((bs = getbits(&UNP, 8))==255) { addme+=255; } } } } } bs += 3+addme; if(!CLI_ISCONTAINED(UNP.outputbuf, UNP.usize, &UNP.outputbuf[UNP.cur_output], bs) || !CLI_ISCONTAINED(UNP.outputbuf, UNP.usize, &UNP.outputbuf[UNP.cur_output-bb], bs)) { UNP.error = 1; break; } while(bs UNP.outputbuf[UNP.cur_output]=UNP.outputbuf[UNP.cur_output-bb]; UNP.cur_output++; } } else { UNP.outputbuf[UNP.cur_output] = (uint8_t)getbits(&UNP, 8); UNP.cur_output++; } } free(buf); if (UNP.error) cli_dbgmsg("autoit: decompression error - partial file may exist\n"); } else { cli_dbgmsg("autoit: file is not compressed\n"); UNP.outputbuf = buf; UNP.usize = UNP.csize; } if (UNP.usize<4) { cli_dbgmsg("autoit: file is too short\n"); free(UNP.outputbuf); continue; } if (script) { UNP.csize = UNP.usize; if (!(buf = cli_malloc(UNP.csize))) { free(UNP.outputbuf); return CL_EMEM; } UNP.cur_output = 0; UNP.cur_input = 4; UNP.bits_avail = cli_readint32((char *)UNP.outputbuf); UNP.error = 0; cli_dbgmsg("autoit: script has got %u lines\n", UNP.bits_avail); while (!UNP.error && UNP.bits_avail && UNP.cur_input < UNP.usize) { uint8_t op; switch((op = UNP.outputbuf[UNP.cur_input++])) { case 5: /* <INT> */ if (UNP.cur_input >= UNP.usize-4) { UNP.error = 1; cli_dbgmsg("autoit: not enough space for an int\n"); break; } if (UNP.cur_output+12 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; if (!(newout = cli_realloc(buf, UNP.csize))) { UNP.error = 1; break; } buf = newout; } snprintf((char *)&buf[UNP.cur_output], 12, "0x%08x ", cli_readint32((char *)&UNP.outputbuf[UNP.cur_input])); UNP.cur_output += 11; UNP.cur_input += 4; break; case 0x10: /* <INT64> */ { uint64_t val; if (UNP.usize < 8 || UNP.cur_input >= UNP.usize-8) { UNP.error = 1; cli_dbgmsg("autoit: not enough space for an int64\n"); break; } if (UNP.cur_output+20 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; if (!(newout = cli_realloc(buf, UNP.csize))) { UNP.error = 1; break; } buf = newout; } val = (uint64_t)cli_readint32((char *)&UNP.outputbuf[UNP.cur_input+4]); val <<=32; val += (uint64_t)cli_readint32((char *)&UNP.outputbuf[UNP.cur_input]); snprintf((char *)&buf[UNP.cur_output], 20, "0x%016lx ", val); UNP.cur_output += 19; UNP.cur_input += 8; break; } case 0x20: /* <DOUBLE> */ if (UNP.usize < 8 || UNP.cur_input >= UNP.usize-8) { UNP.error = 1; cli_dbgmsg("autoit: not enough space for a double\n"); break; } if (UNP.cur_output+40 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; if (!(newout = cli_realloc(buf, UNP.csize))) { UNP.error = 1; break; } buf = newout; } #if FPU_WORDS_BIGENDIAN == 0 snprintf((char *)&buf[UNP.cur_output], 39, "%g ", *(double *)&UNP.outputbuf[UNP.cur_input]); #else do { double x; uint8_t *j = (uint8_t *)&x; unsigned int i; for(i=0; i<8; i++) j[7-i]=UNP.outputbuf[UNP.cur_input+i]; snprintf((char *)&buf[UNP.cur_output], 39, "%g ", x); /* FIXME: check */ } while(0); #endif buf[UNP.cur_output+38]=' '; buf[UNP.cur_output+39]='\0'; UNP.cur_output += strlen((char *)&buf[UNP.cur_output]); UNP.cur_input += 8; break; case 0x30: /* COSTRUCT */ case 0x31: /* COMMAND */ case 0x32: /* MACRO */ case 0x33: /* VAR */ case 0x34: /* FUNC */ case 0x35: /* OBJECT */ case 0x36: /* STRING */ case 0x37: /* DIRECTIVE */ { uint32_t chars, dchars, i; if (UNP.cur_input >= UNP.usize-4) { UNP.error = 1; cli_dbgmsg("autoit: not enough space for size\n"); break; } chars = cli_readint32((char *)&UNP.outputbuf[UNP.cur_input]); dchars = chars*2; UNP.cur_input+=4; if (UNP.usize < dchars || UNP.cur_input >= UNP.usize-dchars) { UNP.error = 1; cli_dbgmsg("autoit: size too big - needed %d, total %d, avail %d\n", dchars, UNP.usize, UNP.usize - UNP.cur_input); break; } if (UNP.cur_output+chars+3 >= UNP.csize) { uint8_t *newout; UNP.csize += chars + 512; if (!(newout = cli_realloc(buf, UNP.csize))) { UNP.error = 1; break; } buf = newout; } if(prefixes[op-0x30]) buf[UNP.cur_output++] = prefixes[op-0x30]; if (chars) { for (i = 0; i<dchars; i+=2) { UNP.outputbuf[UNP.cur_input+i] ^= (uint8_t)chars; UNP.outputbuf[UNP.cur_input+i+1] ^= (uint8_t)(chars>>8); } u2a(&UNP.outputbuf[UNP.cur_input], dchars); memcpy(&buf[UNP.cur_output], &UNP.outputbuf[UNP.cur_input], chars); UNP.cur_output += chars; UNP.cur_input += dchars; } if (op==0x36) buf[UNP.cur_output++] = '"'; if (op!=0x34) buf[UNP.cur_output++] = ' '; } break; case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: case 0x4c: case 0x4d: case 0x4e: case 0x4f: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: if (UNP.cur_output+4 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; if (!(newout = cli_realloc(buf, UNP.csize))) { UNP.error = 1; break; } buf = newout; } UNP.cur_output += snprintf((char *)&buf[UNP.cur_output], 4, "%s ", opers[op-0x40]); break; case 0x7f: UNP.bits_avail if (UNP.cur_output+1 >= UNP.csize) { uint8_t *newout; UNP.csize += 512; if (!(newout = cli_realloc(buf, UNP.csize))) { UNP.error = 1; break; } buf = newout; } buf[UNP.cur_output++]='\n'; break; default: cli_dbgmsg("autoit: found unknown op (%x)\n", op); UNP.error = 1; } } if (UNP.error) cli_dbgmsg("autoit: decompilation aborted - partial script may exist\n"); free(UNP.outputbuf); } else { buf = UNP.outputbuf; UNP.cur_output = UNP.usize ; } snprintf(tempfile, 1023, "%s/autoit.%.3u", tmpd, files); tempfile[1023]='\0'; if((i = open(tempfile, O_RDWR|O_CREAT|O_TRUNC|O_BINARY, S_IRWXU)) < 0) { cli_dbgmsg("autoit: Can't create file %s\n", tempfile); free(buf); return CL_EIO; } if(cli_writen(i, buf, UNP.cur_output) != (int32_t)UNP.cur_output) { cli_dbgmsg("autoit: cannot write %d bytes\n", UNP.usize); close(i); free(buf); return CL_EIO; } free(buf); if(cli_leavetemps_flag) cli_dbgmsg("autoit: %s extracted to %s\n", (script)?"script":"file", tempfile); else cli_dbgmsg("autoit: %s successfully extracted\n", (script)?"script":"file"); fsync(i); lseek(i, 0, SEEK_SET); if(cli_magic_scandesc(i, ctx) == CL_VIRUS) { close(i); if(!cli_leavetemps_flag) unlink(tempfile); return CL_VIRUS; } close(i); if(!cli_leavetemps_flag) unlink(tempfile); } cli_dbgmsg("autoit: Files limit reached (max: %u)\n", ctx->limits->maxfiles); return CL_EMAXFILES; } #endif /* FPU_WORDS_BIGENDIAN */ int cli_scanautoit(int desc, cli_ctx *ctx, off_t offset) { uint8_t version; int r; char *tmpd; lseek(desc, offset, SEEK_SET); if (cli_readn(desc, &version, 1)!=1) return CL_EIO; cli_dbgmsg("in scanautoit()\n"); if (!(tmpd = cli_gentemp(NULL))) return CL_ETMPDIR; if (mkdir(tmpd, 0700)) { cli_dbgmsg("autoit: Can't create temporary directory %s\n", tmpd); free(tmpd); return CL_ETMPDIR; } if (cli_leavetemps_flag) cli_dbgmsg("autoit: Extracting files to %s\n", tmpd); switch(version) { case 0x35: r = ea05(desc, ctx, tmpd); break; case 0x36: #ifdef FPU_WORDS_BIGENDIAN r = ea06(desc, ctx, tmpd); #else cli_dbgmsg("autoit: EA06 support not available\n"); r = CL_CLEAN; #endif break; default: /* NOT REACHED */ cli_dbgmsg("autoit: unknown method\n"); r = CL_CLEAN; } if (!cli_leavetemps_flag) cli_rmdirs(tmpd); free(tmpd); return r; }
// Defines all of the command line switches used by cefclient. #ifndef <API key> #define <API key> #pragma once namespace client { namespace switches { extern const char kStartupPath[]; extern const char <API key>[]; extern const char kCachePath[]; extern const char kUrl[]; extern const char <API key>[]; extern const char kOffScreenFrameRate[]; extern const char <API key>[]; extern const char kShowUpdateRect[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char kBackgroundColor[]; extern const char kEnableGPU[]; extern const char kFilterURL[]; // CefSettings attributes. extern const char kLogFile[]; extern const char kLogSeverity[]; extern const char <API key>[]; extern const char kLogSeverity_Info[]; extern const char <API key>[]; extern const char kLogSeverity_Error[]; extern const char <API key>[]; extern const char <API key>[]; extern const char kGraphicsImpl[]; extern const char kGraphicsImpl_Angle[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char kLocalStorageQuota[]; extern const char <API key>[]; extern const char kJavascriptFlags[]; // CefBrowserSettings attributes. extern const char kDragDropDisabled[]; extern const char kLoadDropsDisabled[]; extern const char kHistoryDisabled[]; extern const char <API key>[]; extern const char kDefaultEncoding[]; extern const char <API key>[]; extern const char kJavascriptDisabled[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char kDomPasteDisabled[]; extern const char <API key>[]; extern const char kJavaDisabled[]; extern const char kPluginsDisabled[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char kXssAuditorEnabled[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char kPageCacheDisabled[]; extern const char kTabToLinksDisabled[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char k<API key>[]; extern const char <API key>[]; extern const char kDatabasesDisabled[]; extern const char <API key>[]; extern const char kWebglDisabled[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char <API key>[]; extern const char kFullscreenEnabled[]; } // namespace switches } // namespace client #endif // <API key>
CKEDITOR.plugins.setLang("codesnippet","el",{button:"Εισαγωγή Αποσπάσματος Κώδικα",codeContents:"Περιεχόμενο κώδικα",emptySnippetError:"Δεν γίνεται να είναι κενά τα αποσπάσματα κώδικα.",language:"Γλώσσα",title:"Απόσπασμα κώδικα",pathName:"απόσπασμα κώδικα"});
<?php defined('BX_DOL') or die('hack attempt'); class BxBaseFormView extends BxDolForm { protected static $_isToggleJsAdded = false; protected static $_isCssJsAdded = false; protected static $<API key> = false; /** * Enable or disable error message displaying */ protected $bEnableErrorIcon = true; /** * HTML Code of this form */ protected $sCode; /** * Code which will be added to the beginning of the form. * For example, hidden inputs. * For internal use only */ protected $_sCodeAdd = ''; /** * for internal use only */ protected $_isSectionOpened = false; /** * Default divider for several inputs */ protected $_sDivider = '<span class="bx-def-margin-left"></span>'; /** * Alternative divider for several inputs */ protected $_sDividerAlt = '<br />'; /** * Form is added dynamically. */ protected $_bDynamicMode = false; /** * Function name for generation close form section HTML. */ protected $_sSectionClose = 'getCloseSection'; /** * Function name for generation open form section HTML. */ protected $_sSectionOpen = 'getOpenSection'; /** * Constructor * * @param array $aInfo Form contents * * $aInfo['params'] = array( * 'remove_form' => true|false, * ); * * @return BxBaseFormView */ function __construct($aInfo, $oTemplate) { parent::__construct($aInfo, $oTemplate); if (isset($this->aParams['view_mode']) && $this->aParams['view_mode']) { $this->_sSectionClose = '<API key>'; $this->_sSectionOpen = '<API key>'; } } /** * Return Form code * @param $bDynamicMode - set it to true if form is added via JS/AJAX call, for example form in AJAX popup. * @return string */ function getCode($bDynamicMode = false) { $this->_bDynamicMode = $bDynamicMode; $this->addCssJs (); $this->aFormAttrs = $this->_replaceMarkers($this->aFormAttrs); return ($this->sCode = $this->genForm()); } /** * Generate the whole form * * @return string */ function genForm() { $this->_sCodeAdd = ''; $sTable = $this->genRows(); $sHtmlBefore = isset($this->aParams['html_before']) ? $this->aParams['html_before'] : ''; $sHtmlAfter = isset($this->aParams['html_after']) ? $this->aParams['html_after'] : ''; if (!empty($this->aParams['remove_form']) || (isset($this->aParams['view_mode']) && $this->aParams['view_mode'])) { $sForm = <<<BLAH $sHtmlBefore {$this->_sCodeAdd} <div class="<API key> {$this->id}_wrapper"> $sTable </div> $sHtmlAfter BLAH; } else { $sFormAttrs = <API key>($this->aFormAttrs, 'bx-form-advanced'); $sForm = <<<BLAH $sHtmlBefore <form $sFormAttrs> {$this->_sCodeAdd} <div class="<API key> {$this->id}_wrapper"> $sTable </div> </form> <script> $(document).ready(function() { $(this).addWebForms(); }); </script> $sHtmlAfter BLAH; } return $sForm; } /** * Generate Table HTML code * * @return string */ function genRows() { // add CSRF token if it's needed. if (!(isset($this->aParams['view_mode']) && $this->aParams['view_mode']) && getParam('<API key>') == 'on' && (!isset($this->aParams['csrf']['disable']) || (isset($this->aParams['csrf']['disable']) && $this->aParams['csrf']['disable'] !== true)) && ($mixedCsrfToken = BxDolForm::getCsrfToken()) !== false) { $this->aInputs['csrf_token'] = array( 'type' => 'hidden', 'name' => 'csrf_token', 'value' => $mixedCsrfToken, 'db' => array ('pass' => 'Xss'), 'visible_for_levels' => PHP_INT_MAX, ); } // check if we need to generate open section clause $sOpenSection = ''; foreach ($this->aInputs as $aInput) { if (isset($aInput['type']) && 'hidden' == $aInput['type']) continue; if (isset($aInput['type']) && 'block_header' != $aInput['type']) $sOpenSection = $this->{$this->_sSectionOpen}(); break; } // generate rows contents $sCont = ''; $sFuncGenRow = isset($this->aParams['view_mode']) && $this->aParams['view_mode'] ? 'genViewRow' : 'genRow'; foreach ($this->aInputs as $aInput) if (!isset($aInput['visible_for_levels']) || self::isVisible($aInput)) $sCont .= $this->$sFuncGenRow($aInput); $sCloseSection = $this->{$this->_sSectionClose}(); return $sOpenSection . $sCont . $sCloseSection; } /** * Generate single Table Row * * @param array $aInput * @return string */ function genRow(&$aInput) { if (!isset($aInput['type'])) $aInput['type'] = false; if (!empty($aInput['name'])) { $sCustomMethod = 'genCustomRow' . $this->_genMethodName($aInput['name']); if (method_exists($this, $sCustomMethod)) return $this->$sCustomMethod($aInput); } switch ($aInput['type']) { case 'block_header': $sRow = $this->genRowBlockHeader($aInput); break; case 'block_end': $sRow = $this->genBlockEnd($aInput); break; case 'hidden': // do not generate row for hidden inputs $sRow = ''; $this->_sCodeAdd .= $this->genInput($aInput); break; case 'select_box': $sRow = $this->genRowCustom($aInput, 'genInputSelectBox'); break; case 'files': $sRow = $this->genRowCustom($aInput, 'genInputFiles'); break; case 'switcher': case 'checkbox': $sRow = $this->genRowStandard($aInput, true); break; default: $sRow = $this->genRowStandard($aInput); } return $sRow; } /** * Generate single Table Row for view mode * * @param array $aInput * @return string */ function genViewRow(&$aInput) { if (!isset($aInput['type'])) $aInput['type'] = false; if (!empty($aInput['name'])) { $sCustomMethod = 'genCustomRow' . $this->_genMethodName($aInput['name']); if (method_exists($this, $sCustomMethod)) return $this->$sCustomMethod($aInput); } switch ($aInput['type']) { case 'block_header': $sRow = $this->genRowBlockHeader($aInput); break; case 'block_end': $sRow = $this->genBlockEnd($aInput); break; default: $sRow = $this->genViewRowWrapped($aInput); } return $sRow; } /** * Generate complete wrapped row for view mode form * * @param array $aInput * @return string */ function genViewRowWrapped(&$aInput) { $sValue = $this->genViewRowValue($aInput); if (null === $sValue) return ''; $sCaption = isset($aInput['caption']) ? bx_process_output($aInput['caption']) : ''; return <<<EOS <div class="<API key> <API key>-{$aInput['type']} <API key>"> <div class="<API key> <API key>">{$sCaption}:</div> <div class="<API key>">{$sValue}</div> </div> EOS; } /** * Generate value for view mode row * * @param array $aInput * @return string */ function genViewRowValue(&$aInput) { switch ($aInput['type']) { case 'hidden': $sValue = null; break; case 'select': case 'radio_set': $sValue = $this-><API key>($aInput); break; case 'datepicker': $iTime = bx_process_input ($aInput['value'], BX_DATA_DATE_TS, false, false); $sValue = bx_time_js ($iTime, BX_FORMAT_DATE); break; case 'date_time': case 'datetime': $iTime = bx_process_input ($aInput['value'], BX_DATA_DATETIME_TS, false, false); $sValue = bx_time_js ($iTime, BX_FORMAT_DATE_TIME); break; case 'checkbox_set': case 'select_multiple': $sValue = null; if (!empty($aInput['value']) && is_array($aInput['value'])) { $sValue = ''; foreach ($aInput['value'] as $sVal) $sValue .= $aInput['values'][$sVal] . ', '; $sValue = trim ($sValue, ', '); } break; case 'checkbox': case 'switcher': $sValue = isset($aInput['checked']) && $aInput['checked'] ? _t('<API key>') : _t('<API key>'); break; case 'textarea': if (isset($aInput['value']) && '' !== $aInput['value']) $sValue = isset($aInput['html']) && $aInput['html'] ? $aInput['value'] : nl2br(bx_process_output($aInput['value'])); else $sValue = null; break; default: $sValue = isset($aInput['value']) && '' !== $aInput['value'] ? bx_process_output($aInput['value']) : null; } return $sValue; } function <API key>(&$aInput) { $s = isset($aInput['value']) && isset($aInput['values'][$aInput['value']]) ? $aInput['values'][$aInput['value']] : null; if (isset($aInput['values_list_name']) && ($oCategory = BxDolCategory::<API key>($this->aFormAttrs['name'], $aInput['values_list_name']))) return $oCategory->getCategoryLink($s, $aInput['value']); return $s; } /** * Generate standard row * * @param array $aInput * @return string */ function genRowStandard(&$aInput, $isOneLine = false) { $sCaption = isset($aInput['caption']) ? bx_process_output($aInput['caption']) : ''; $sRequired = !empty($aInput['required']) ? '<span class="bx-form-required">*</span> ' : ''; $sClassAdd = !empty($aInput['error']) ? ' bx-form-error' : ''; $sInfoIcon = !empty($aInput['info']) ? $this->genInfoIcon($aInput['info']) : ''; $sErrorIcon = $this->genErrorIcon(empty($aInput['error']) ? '' : $aInput['error']); if (isset($aInput['name'])) $aInput['tr_attrs']['id'] = "bx-form-element-" . $aInput['name']; $sTrAttrs = <API key>(isset($aInput['tr_attrs']) && is_array($aInput['tr_attrs']) ? $aInput['tr_attrs'] : array(), "<API key> bx-def-margin-top"); $<API key> = ''; $sClassOneLineValue = ''; if ($isOneLine) { $<API key> = ' <API key> <API key>-' . $aInput['type'] . ' <API key>'; $sClassOneLineValue = ' <API key> <API key>-' . $aInput['type']; $aInput['attrs']['id'] = $this->getInputId($aInput); if ($sCaption) $sCaption = '<label for="' . $aInput['attrs']['id'] . '">' . $sCaption . '</label>'; } $sInput = $this->genInput($aInput); $sCaptionCode = ''; if ($sCaption) $sCaptionCode = '<div class="bx-form-caption' . $<API key> . '">' . $sCaption . $sRequired . '</div>'; else $sInput .= $sRequired; $sInputCode = $this->genWrapperInput($aInput, $sInput); if (empty($sInputCodeExtra)) $sInputCodeExtra = ''; if (empty($sInfoIcon)) $sInfoIcon = ''; if (empty($sInputCode)) $sInputCode = ''; if (empty($sErrorIcon)) $sErrorIcon = ''; $sValueCode = ' <div class="bx-form-value bx-clearfix' . $sClassAdd . $sClassOneLineValue . '"> ' . $sInputCode . ' ' . ($isOneLine ? '' : $sInfoIcon . $sErrorIcon) . ' ' . $sInputCodeExtra . ' </div>'; if ($isOneLine) $sCode = $sValueCode . $sCaptionCode . '<div class="bx-clear"></div>' . $sInfoIcon . $sErrorIcon; else $sCode = $sCaptionCode . $sValueCode; return "<div $sTrAttrs>" . $sCode . "</div>"; } function genWrapperInput($aInput, $sContent) { $sAttr = isset($aInput['attrs_wrapper']) && is_array($aInput['attrs_wrapper']) ? <API key>($aInput['attrs_wrapper']) : ''; $sCode = <<<BLAH <div class="<API key> <API key>-{$aInput['type']}" $sAttr> $sContent </div> BLAH; return $sCode; } /** * Generate custom row * * @param array $aInput * @param string $sCustomMethod custom method to generate code for input * @return string */ function genRowCustom(&$aInput, $sCustomMethod) { $sCaption = isset($aInput['caption']) ? bx_process_output($aInput['caption']) : ''; $sRequired = !empty($aInput['required']) ? '<span class="bx-form-required">*</span> ' : ''; $sClassAdd = !empty($aInput['error']) ? ' bx-form-error' : ''; $sInfoIcon = !empty($aInput['info']) ? $this->genInfoIcon($aInput['info']) : ''; $sErrorIcon = $this->genErrorIcon(empty($aInput['error']) ? '' : $aInput['error']); $sInput = $this->$sCustomMethod($aInput, $sInfoIcon, $sErrorIcon); if (isset($aInput['name'])) $aInput['tr_attrs']['id'] = "bx-form-element-" . $aInput['name']; $sTrAttrs = <API key>(empty($aInput['tr_attrs']) ? array() : $aInput['tr_attrs'], "<API key> bx-def-margin-top"); $sCaptionCode = ''; if ($sCaption) $sCaptionCode = '<div class="bx-form-caption">' . $sCaption . $sRequired . '</div>'; $sCode = <<<BLAH <div $sTrAttrs> $sCaptionCode <div class="bx-form-value$sClassAdd"> <div class="bx-clear"></div> $sInput <div class="bx-clear"></div> </div> </div> BLAH; return $sCode; } /** * Generate Block Headers row * * @param array $aInput * @return string */ function genRowBlockHeader(&$aInput) { $aAttrs = empty($aInput['attrs']) ? '' : $aInput['attrs']; // if there is no caption - show divider only if (empty($aInput['caption'])) { $sCode = $this->{$this->_sSectionClose}(); $sCode .= $this->{$this->_sSectionOpen}($aAttrs); return $sCode; } // if section is collapsed by default, add necessary code $<API key> = 'bx-form-collapsable'; if (isset($aInput['collapsed']) and $aInput['collapsed']) $<API key> .= ' bx-form-collapsed <API key>'; // display section with caption $sCode = $this->{$this->_sSectionClose}(); if (empty($aAttrs)) $aAttrs['class'] = 'bx-form-collapsable ' . $<API key>; else $aAttrs['class'] .= ' bx-form-collapsable ' . $<API key>; if (isset($this->aParams['view_mode']) && $this->aParams['view_mode']) $sLegend = '<legend class="<API key> bx-def-font-grayed bx-def-font-h3">' . bx_process_output($aInput['caption']) . '</legend>'; else $sLegend = '<legend class="bx-def-padding-left <API key> bx-def-font-grayed bx-def-font-h3"><a href="javascript:void(0);">' . bx_process_output($aInput['caption']) . '</a></legend>'; $sCode .= $this->{$this->_sSectionOpen}($aAttrs, $sLegend); return $sCode; } function genBlockEnd() { $aNextTbodyAdd = false; // need to have some default $sCode = ''; $sCode .= $this->{$this->_sSectionClose}(); $sCode .= $this->{$this->_sSectionOpen}($aNextTbodyAdd); return $sCode; } /** * Generate HTML Input Element * * @param array $aInput * @return string Output HTML Code */ function genInput(&$aInput) { if (!empty($aInput['name'])) { $sCustomMethod = 'genCustomInput' . $this->_genMethodName($aInput['name']); if (method_exists($this, $sCustomMethod)) return $this->$sCustomMethod($aInput); } switch ($aInput['type']) { // standard inputs (and non-standard, interpreted as standard) case 'text': case 'datepicker': case 'date_time': case 'datetime': case 'number': case 'checkbox': case 'radio': case 'file': case 'image': case 'password': case 'slider': case 'doublerange': case 'hidden': $sInput = $this->genInputStandard($aInput); break; case 'switcher': $sInput = $this->genInputSwitcher($aInput); break; case 'button': case 'reset': case 'submit': $sInput = $this->genInputButton($aInput); break; case 'textarea': $sInput = $this->genInputTextarea($aInput); break; case 'select': $sInput = $this->genInputSelect($aInput); break; case 'select_multiple': $sInput = $this-><API key>($aInput); break; case 'checkbox_set': $sInput = $this->genInputCheckboxSet($aInput); break; case 'radio_set': $sInput = $this->genInputRadioSet($aInput); break; case 'input_set': // numeric array of inputs $sInput = ''; $sDivider = isset($aInput['dv']) ? $aInput['dv'] : ' '; foreach ($aInput as $iKey => $aSubInput) { if (!is_int($iKey) or !$aSubInput) continue; // parse only integer keys and existing values $sInput .= $this->genInput($aSubInput); // recursive call $sInput .= $sDivider; } $sInput .= '<div class="bx-clear"></div>'; break; case 'custom': $sInput = isset($aInput['content']) ? $aInput['content'] : ''; break; case 'captcha': $sInput = $this->genInputCaptcha($aInput); break; case 'value': $sInput = $aInput['value']; break; default: //unknown control type $sInput = 'Unknown control type'; } // create input label $sInput .= $this->genLabel($aInput); return $sInput; } /** * Generate new Input Element id * * @param array $aInput * @return string */ function getInputId(&$aInput) { if (isset($aInput['id'])) return $aInput['id']; $sName = md5($aInput['name']); $sID = $this->id . '_input_' . $sName; if ( // multiple elements cause identical id's ( ( $aInput['type'] == 'checkbox' and substr($aInput['name'], -2) == '[]' // it is multiple element ) or $aInput['type'] == 'radio' // it is always multiple (i think so... hm) ) and isset($aInput['value']) // if we can make difference ) { $sValue = md5($aInput['value']); // add value $sID .= '_' . $sValue; } $sID = trim($sID, '_'); $aInput['id'] = $sID; // just for repeated calls return $sID; } /** * Generate standard Input Element * * @param array $aInput * @return string */ function genInputStandard(&$aInput) { // clone attributes for system use ;) $aAttrs = empty($aInput['attrs']) ? array() : $aInput['attrs']; // add default className to attributes $aAttrs['type'] = $aInput['type']; if ('datetime' == $aAttrs['type']) $aAttrs['type'] = 'date_time'; if (isset($aInput['name'])) $aAttrs['name'] = $aInput['name']; if (isset($aInput['value'])) $aAttrs['value'] = $aInput['value']; // for inputs with labels generate id if (isset($aInput['label'])) $aAttrs['id'] = $this->getInputId($aInput); // for checkboxes if (isset($aInput['checked']) and $aInput['checked']) $aAttrs['checked'] = 'checked'; $sAttrs = <API key>($aAttrs, "bx-def-font-inputs bx-form-input-{$aInput['type']}"); return "<input $sAttrs />\n"; } /** * Generate Switcher Input Element (based on checkbox) * * @param array $aInput * @return string */ function genInputSwitcher(&$aInput) { $aInput['type'] = 'checkbox'; $sCheckbox = $this->genInputStandard($aInput); $aInput['type'] = 'switcher'; $sClass = 'off'; if (isset($aInput['checked']) and $aInput['checked']) $sClass = 'on'; return ' <div class="bx-switcher-cont ' . $sClass . '">' . $sCheckbox . ' <div class="bx-switcher-canvas"> <div class="bx-switcher-on"><i class="sys-icon check"></i></div> <div class="bx-switcher-off"><i class="sys-icon times"></i></div> <div class="bx-switcher-handler">&nbsp;</div> </div> </div>'; } /** * Generate Button Input Element * * @param array $aInput * @return string */ function genInputButton(&$aInput) { // clone attributes for system use ;) $aAttrs = empty($aInput['attrs']) ? array() : $aInput['attrs']; // add default className to attributes $aAttrs['type'] = $aInput['type']; if (isset($aInput['value'])) $aAttrs['value'] = $aInput['value']; if (isset($aInput['name'])) $aAttrs['name'] = $aInput['name']; $sAttrs = <API key>($aAttrs, "bx-def-font-inputs bx-form-input-{$aInput['type']} bx-btn" . ('submit' == $aInput['type'] ? ' bx-btn-primary' : '')); return "<button $sAttrs>" . $aInput['value'] . "</button>\n"; } /** * Generate Textarea Element * * @param array $aInput * @return string */ function genInputTextarea(&$aInput) { // clone attributes for system use ;) $aAttrs = empty($aInput['attrs']) ? array() : $aInput['attrs']; $aAttrs['name'] = $aInput['name']; // for inputs with labels generate id if (isset($aInput['label'])) $aAttrs['id'] = $this->getInputId($aInput); $sAttrs = <API key>($aAttrs, "bx-def-font-inputs bx-form-input-{$aInput['type']}" . ((isset($aInput['html']) and $aInput['html'] and $this->addHtmlEditor($aInput['html'], $aInput)) ? ' bx-form-input-html' : '')); $sValue = isset($aInput['value']) ? bx_process_output($aInput['value']) : ''; return "<textarea $sAttrs>$sValue</textarea>"; } function addHtmlEditor($iViewMode, &$aInput) { $oEditor = BxDolEditor::getObjectInstance(false, $this->oTemplate); if (!$oEditor) return false; $this->_sCodeAdd .= $oEditor->attachEditor ('#' . $this->aFormAttrs['id'] . ' [name='.$aInput['name'].']', $iViewMode, $this->_bDynamicMode); return true; } /** * Generate Select Box Element * * @param array $aInput * @return string */ function genInputSelectBox(&$aInput, $sInfo = '', $sError = '') { $aNewInput = $aInput; $aNewInput['type'] = 'select'; $aNewInput['name'] .= '[]'; $sInput = $this->genInput($aNewInput); return <<<BLAH <div class="<API key> input-wrapper-{$aInput['type']}"> $sInput </div> $sInfo $sError BLAH; } /** * Generate Select Box Element * * @param array $aInput * @return string */ function genInputFiles(&$aInput, $sInfo = '', $sError = '') { $sUniqId = genRndPwd (8, false); $sUploaders = ''; $oUploader = null; foreach ($aInput['uploaders'] as $sUploaderObject) { $oUploader = BxDolUploader::getObjectInstance($sUploaderObject, $aInput['storage_object'], $sUniqId); if (!$oUploader) continue; $sGhostTemplate = false; if (isset($aInput['ghost_template']) && is_object($aInput['ghost_template'])) { // form is not submitted and ghost template is BxDolFormNested object $oFormNested = $aInput['ghost_template']; if ($oFormNested instanceof BxDolFormNested) $sGhostTemplate = $oFormNested->getCode(); } elseif (isset($aInput['ghost_template']) && is_array($aInput['ghost_template']) && isset($aInput['ghost_template']['inputs'])) { // form is not submitted and ghost template is form array $oFormNested = new BxDolFormNested($aInput['name'], $aInput['ghost_template'], $this->aParams['db']['submit_name'], $this->oTemplate); $sGhostTemplate = $oFormNested->getCode(); } elseif (isset($aInput['ghost_template']) && is_array($aInput['ghost_template']) && $aInput['ghost_template']) { // form is submitted and ghost template is array of BxDolFormNested objects $sGhostTemplate = array (); foreach ($aInput['ghost_template'] as $iFileId => $oFormNested) if (is_object($oFormNested) && $oFormNested instanceof BxDolFormNested) $sGhostTemplate[$iFileId] = $oFormNested->getCode(); } elseif (isset($aInput['ghost_template']) && is_string($aInput['ghost_template'])) { // ghost template is just string template, without nested form $sGhostTemplate = $aInput['ghost_template']; } $aParams = array( 'button_title' => bx_js_string($oUploader-><API key>(isset($aInput['<API key>']) ? $aInput['<API key>'] : false)), 'content_id' => isset($aInput['content_id']) ? $aInput['content_id'] : '', 'storage_private' => isset($aInput['storage_private']) ? $aInput['storage_private'] : '1', ); if (isset($aInput['images_transcoder']) && $aInput['images_transcoder']) $aParams['images_transcoder'] = bx_js_string($aInput['images_transcoder']); $sUploaders .= $oUploader->getUploaderButton($sGhostTemplate, isset($aInput['multiple']) ? $aInput['multiple'] : true, $aParams); } return $this->oTemplate->parseHtmlByName('form_field_uploader.html', array( 'uploaders_buttons' => $sUploaders, 'info' => $sInfo, 'error' => $sError, 'id_container_errors' => $oUploader ? $oUploader-><API key>() : '', 'id_container_result' => $oUploader ? $oUploader-><API key>() : '', '<API key>' => $oUploader ? $oUploader-><API key>() : '', 'is_init_ghosts' => isset($aInput['init_ghosts']) && !$aInput['init_ghosts'] ? 0 : 1, )); } /** * Generate Select Element * * @param array $aInput * @return string */ function genInputSelect(&$aInput) { $sCurValue = isset($aInput['value']) ? $aInput['value'] : ''; return $this->_genInputSelect($aInput, false, $sCurValue, '_isSelected'); } /** * Generate Multiple Select Element * * @param array $aInput * @return string */ function <API key>(&$aInput) { $aCurValues = array(); if (isset($aInput['value']) && $aInput['value']) $aCurValues = is_array($aInput['value']) ? $aInput['value'] : array(); return $this->_genInputSelect($aInput, true, $aCurValues, '_isSelectedMultiple'); } /** * Generate Checkbox Set Element * * @param array $aInput * @return string */ function genInputCheckboxSet(&$aInput) { $aCurValues = array(); if (isset($aInput['value']) && $aInput['value']) $aCurValues = is_array($aInput['value']) ? $aInput['value'] : array(); return $this->_genInputsSet($aInput, 'checkbox', $aCurValues, '_isSelectedMultiple', '[]'); } /** * Generate Radiobuttons Set Element * * @param array $aInput * @return string */ function genInputRadioSet(&$aInput) { $sCurValue = isset($aInput['value']) ? $aInput['value'] : ''; return $this->_genInputsSet($aInput, 'radio', $sCurValue, '_isSelected'); } function _isSelected ($sValue, $sCurValue) { return ((string)$sValue === (string)$sCurValue); } function _isSelectedMultiple ($sValue, $aCurValues) { return in_array($sValue, $aCurValues); } function _genInputSelect(&$aInput, $isMultiple, $mixedCurrentVal, $sIsSelectedFunc) { $aAttrs = empty($aInput['attrs']) ? array() : $aInput['attrs']; $aAttrs['name'] = $aInput['name']; if ($isMultiple) { $aAttrs['name'] .= '[]'; $aAttrs['multiple'] = 'multiple'; } // for inputs with labels generate id if (isset($aInput['label'])) $aAttrs['id'] = $this->getInputId($aInput); $sAttrs = <API key>($aAttrs, "bx-def-font-inputs bx-form-input-{$aInput['type']}"); // generate options $sOptions = ''; if (isset($aInput['values']) and is_array($aInput['values'])) { foreach ($aInput['values'] as $sValue => $sTitle) { $sClassC = $sStyleC = ""; if(is_array($sTitle)) { if(isset($sTitle['type'])) { switch($sTitle['type']) { case 'group_header': $sTitle = bx_process_output($sTitle['value']); $sOptions .= <<<BLAH <optgroup label="$sTitle"> BLAH; break; case 'group_end': $sOptions .= <<<BLAH </optgroup> BLAH; break; } continue; } $sClassC = isset($sTitle['class']) ? " class=\"" . $sTitle['class'] . "\"" : ""; $sStyleC = isset($sTitle['style']) ? " style=\"" . $sTitle['style'] . "\"" : ""; $sValue = $sTitle['key']; $sTitle = $sTitle['value']; } $sValueC = bx_html_attribute($sValue); $sTitleC = bx_process_output($sTitle); $sSelected = $this->$sIsSelectedFunc($sValue, $mixedCurrentVal) ? 'selected="selected"' : ''; $sOptions .= <<<BLAH <option value="$sValueC"$sClassC$sStyleC $sSelected>$sTitleC</option> BLAH; } } // generate element $sCode = <<<BLAH <select $sAttrs> $sOptions </select> BLAH; return $sCode; } function _genInputsSet(&$aInput, $sType, $mixedCurrentVal, $sIsCheckedFunc, $sNameAppend = '') { $aAttrs = empty($aInput['attrs']) || 'radio_set' == $aInput['type'] || 'checkbox_set' == $aInput['type'] ? array() : $aInput['attrs']; $aAttrs['name'] = $aInput['name']; // for inputs with labels generate id if (isset($aInput['label'])) $aAttrs['id'] = $this->getInputId($aInput); $sAttrs = <API key>($aAttrs, "bx-form-input-{$aInput['type']}"); // generate options $sDivider = isset($aInput['dv']) ? $aInput['dv'] : $this->_sDivider; $sOptions = ''; if (isset($aInput['values']) and is_array($aInput['values'])) { if (count($aInput['values']) > 3 && $sDivider == $this->_sDivider) $sDivider = $this->_sDividerAlt; // generate complex input using simple standard inputs foreach ($aInput['values'] as $sValue => $sLabel) { // create new simple input $aNewInput = array( 'type' => $sType, 'name' => $aInput['name'] . $sNameAppend, 'value' => $sValue, 'checked' => $this->$sIsCheckedFunc($sValue, $mixedCurrentVal), 'label' => $sLabel, 'attrs' => !empty($aInput['attrs']) && ('radio_set' == $aInput['type'] || 'checkbox_set' == $aInput['type']) ? $aInput['attrs'] : false, ); $sNewInput = $this->genInput($aNewInput); // attach new input to complex $sOptions .= ($sNewInput . $sDivider); } } // generate element $sCode = <<<BLAH <div $sAttrs> $sOptions </div> BLAH; return $sCode; } function genInputCaptcha(&$aInput) { $aAttrs = empty($aInput['attrs']) ? array() : $aInput['attrs']; // for inputs with labels generate id if (isset($aInput['label'])) $aAttrs['id'] = $this->getInputId($aInput); $sAttrs = <API key>($aAttrs, "bx-form-input-{$aInput['type']}"); $oCaptcha = BxDolCaptcha::getObjectInstance(); return "<div $sAttrs>" . ($oCaptcha ? $oCaptcha->display($this->_bDynamicMode) : _t('<API key>')) . "</div>"; } /** * Generate Label Element * * @param string $sLabel Text of the Label * @param string $sInputID Dependant Input Element ID * @return string HTML code */ function genLabel(&$aInput) { if (!isset($aInput['label']) or empty($aInput['label'])) return ''; $sLabel = $aInput['label']; $sInputID = $this->getInputId($aInput); $sRet = '<label for="' . $sInputID . '">' . bx_process_output($sLabel) . '</label>'; return $sRet; } function genInfoIcon($sInfo) { return '<div class="bx-form-info bx-def-font-grayed bx-def-font-small">' . bx_process_output($sInfo) . '</div>'; } function genErrorIcon( $sError = '' ) { if ($this->bEnableErrorIcon) { $sStyle = ''; if (!$sError) $sStyle = 'style="display:none;"'; return '<div class="bx-form-warn" ' . $sStyle . '>' . $sError . '</div>'; } } function getOpenSection($aAttrs = array(), $sLegend = '') { if (!$this->_isSectionOpened) { if (!$aAttrs || !is_array($aAttrs)) $aAttrs = array(); if ($sLegend) $sClassesAdd = "<API key>"; else $sClassesAdd = "<API key>"; $sAttrs = <API key>($aAttrs, "bx-form-section <API key> bx-def-border-top " . $sClassesAdd); $this->_isSectionOpened = true; return "<!-- form header content begins -->\n <div class=\"<API key> bx-def-margin-top\"> <fieldset $sAttrs> $sLegend <div class=\"<API key> bx-def-padding-top <API key>" . ($sLegend ? ' bx-def-padding-left <API key>' : '') . "\">\n"; } else { return ''; } } function getCloseSection() { if ($this->_isSectionOpened) { $this->_isSectionOpened = false; return "</div> </fieldset> </div> \n<!-- form header content ends -->\n"; } else { return ''; } } function <API key>($aAttrs = array(), $sLegend = '') { if (!$this->_isSectionOpened) { if (!$aAttrs || !is_array($aAttrs)) $aAttrs = array(); if ($sLegend) $sClassesAdd = "<API key>"; else $sClassesAdd = "<API key>"; $sAttrs = <API key>($aAttrs, "bx-form-section <API key> <API key> bx-def-border-top " . $sClassesAdd); $this->_isSectionOpened = true; return "<!-- form header content begins -->\n <div class=\"<API key> bx-def-margin-top\"> <fieldset $sAttrs> $sLegend <div class=\"<API key> bx-def-padding-top\">\n"; } else { return ''; } } function <API key>() { if ($this->_isSectionOpened) { $this->_isSectionOpened = false; return "</div> </fieldset> </div> \n<!-- form header content ends -->\n"; } else { return ''; } } function addCssJs () { if (isset($this->aParams['view_mode']) && $this->aParams['view_mode']) { if (self::$<API key>) return; $this->oTemplate->addCss('forms.css'); self::$<API key> = true; } else { if (self::$_isCssJsAdded) return; $aCss = array( 'forms.css', 'jquery-ui/jquery-ui.css', 'timepicker-addon/<API key>.css', ); $aUiLangs = array ('af' => 1, 'ar-DZ' => 1, 'ar' => 1, 'az' => 1, 'be' => 1, 'bg' => 1, 'bs' => 1, 'ca' => 1, 'cs' => 1, 'cy-GB' => 1, 'da' => 1, 'de' => 1, 'el' => 1, 'en-AU' => 1, 'en-GB' => 1, 'en-NZ' => 1, 'en' => 1, 'eo' => 1, 'es' => 1, 'et' => 1, 'eu' => 1, 'fa' => 1, 'fi' => 1, 'fo' => 1, 'fr-CA' => 1, 'fr-CH' => 1, 'fr' => 1, 'gl' => 1, 'he' => 1, 'hi' => 1, 'hr' => 1, 'hu' => 1, 'hy' => 1, 'id' => 1, 'is' => 1, 'it' => 1, 'ja' => 1, 'ka' => 1, 'kk' => 1, 'km' => 1, 'ko' => 1, 'ky' => 1, 'lb' => 1, 'lt' => 1, 'lv' => 1, 'mk' => 1, 'ml' => 1, 'ms' => 1, 'nb' => 1, 'nl-BE' => 1, 'nl' => 1, 'nn' => 1, 'no' => 1, 'pl' => 1, 'pt-BR' => 1, 'pt' => 1, 'rm' => 1, 'ro' => 1, 'ru' => 1, 'sk' => 1, 'sl' => 1, 'sq' => 1, 'sr-SR' => 1, 'sr' => 1, 'sv' => 1, 'ta' => 1, 'th' => 1, 'tj' => 1, 'tr' => 1, 'uk' => 1, 'vi' => 1, 'zh-CN' => 1, 'zh-HK' => 1, 'zh-TW' => 1); $aCalendarLangs = array ('af' => 1, 'am' => 1, 'bg' => 1, 'ca' => 1, 'cs' => 1, 'da' => 1, 'de' => 1, 'el' => 1, 'es' => 1, 'et' => 1, 'eu' => 1, 'fa' => 1, 'fi' => 1, 'fr' => 1, 'gl' => 1, 'he' => 1, 'hr' => 1, 'hu' => 1, 'id' => 1, 'it' => 1, 'ja' => 1, 'ko' => 1, 'lt' => 1, 'lv' => 1, 'mk' => 1, 'nl' => 1, 'no' => 1, 'pl' => 1, 'pt-BR' => 1, 'pt' => 1, 'ro' => 1, 'ru' => 1, 'sk' => 1, 'sl' => 1, 'sr-RS' => 1, 'sr-YU' => 1, 'sv' => 1, 'th' => 1, 'tr' => 1, 'uk' => 1, 'vi' => 1, 'zh-CN' => 1, 'zh-TW' => 1); $sCalendarLang = BxDolLanguages::getInstance()-><API key> ($aCalendarLangs); $sUiLang = BxDolLanguages::getInstance()-><API key> ($aUiLangs); $aJs = array( 'jquery.webForms.js', 'jquery-ui/jquery.ui.core.min.js', 'jquery-ui/jquery.ui.widget.min.js', 'jquery-ui/jquery.ui.mouse.min.js', 'jquery-ui/jquery.ui.position.min.js', 'jquery-ui/jquery.ui.slider.min.js', 'jquery-ui/jquery.ui.datepicker.min.js', 'jquery-ui/i18n/jquery.ui.datepicker-' . $sUiLang . '.js', 'timepicker-addon/<API key>.min.js', 'timepicker-addon/<API key>.js', 'timepicker-addon/i18n/<API key>-' . $sCalendarLang . '.js', ); foreach ($this->aInputs as $aInput) { if (!isset($aInput['type']) || 'files' != $aInput['type'] || !isset($aInput['uploaders'])) continue; foreach ($aInput['uploaders'] as $sUploaderObject) { $oUploader = BxDolUploader::getObjectInstance($sUploaderObject, $aInput['storage_object'], ''); if ($oUploader) $oUploader->addCssJs(); } } $this->oTemplate->addJs($aJs); $this->oTemplate->addCss($aCss); self::$_isCssJsAdded = true; } } }
/** \file * * Header file for BootloaderDFU.c. */ #ifndef _BOOTLOADER_H_ #define _BOOTLOADER_H_ /* Includes: */ #include <avr/io.h> #include <avr/wdt.h> #include <avr/boot.h> #include <avr/pgmspace.h> #include <avr/eeprom.h> #include <avr/power.h> #include <avr/interrupt.h> #include <util/delay.h> #include <stdbool.h> #include "Descriptors.h" #include <LUFA/Drivers/USB/USB.h> #include <LUFA/Drivers/Board/LEDs.h> /* Macros: */ /** Configuration define. Define this token to true to case the bootloader to reject all memory commands * until a memory erase has been performed. When used in conjunction with the lockbits of the AVR, this * can protect the AVR's firmware from being dumped from a secured AVR. When false, memory operations are * allowed at any time. */ #define SECURE_MODE false /** Major bootloader version number. */ #define <API key> 2 /** Minor bootloader version number. */ #define <API key> 0 /** Complete bootloader version number expressed as a packed byte, constructed from the * two individual bootloader version macros. */ #define BOOTLOADER_VERSION ((<API key> << 4) | <API key>) /** First byte of the bootloader identification bytes, used to identify a device's bootloader. */ #define BOOTLOADER_ID_BYTE1 0xDC /** Second byte of the bootloader identification bytes, used to identify a device's bootloader. */ #define BOOTLOADER_ID_BYTE2 0xFB /** Convenience macro, used to determine if the issued command is the given one-byte long command. * * \param[in] dataarr Command byte array to check against * \param[in] cb1 First command byte to check */ #define IS_ONEBYTE_COMMAND(dataarr, cb1) (dataarr[0] == (cb1)) /** Convenience macro, used to determine if the issued command is the given two-byte long command. * * \param[in] dataarr Command byte array to check against * \param[in] cb1 First command byte to check * \param[in] cb2 Second command byte to check */ #define IS_TWOBYTE_COMMAND(dataarr, cb1, cb2) ((dataarr[0] == (cb1)) && (dataarr[1] == (cb2))) /** Length of the DFU file suffix block, appended to the end of each complete memory write command. * The DFU file suffix is currently unused (but is designed to give extra file information, such as * a CRC of the complete firmware for error checking) and so is discarded. */ #define <API key> 16 /** Length of the DFU file filler block, appended to the start of each complete memory write command. * Filler bytes are added to the start of each complete memory write command, and must be discarded. */ #define <API key> 26 /** DFU class command request to detach from the host. */ #define DFU_REQ_DETATCH 0x00 /** DFU class command request to send data from the host to the bootloader. */ #define DFU_REQ_DNLOAD 0x01 /** DFU class command request to send data from the bootloader to the host. */ #define DFU_REQ_UPLOAD 0x02 /** DFU class command request to get the current DFU status and state from the bootloader. */ #define DFU_REQ_GETSTATUS 0x03 /** DFU class command request to reset the current DFU status and state variables to their defaults. */ #define DFU_REQ_CLRSTATUS 0x04 /** DFU class command request to get the current DFU state of the bootloader. */ #define DFU_REQ_GETSTATE 0x05 /** DFU class command request to abort the current multi-request transfer and return to the dfuIDLE state. */ #define DFU_REQ_ABORT 0x06 /** DFU command to begin programming the device's memory. */ #define COMMAND_PROG_START 0x01 /** DFU command to begin reading the device's memory. */ #define COMMAND_DISP_DATA 0x03 /** DFU command to issue a write command. */ #define COMMAND_WRITE 0x04 /** DFU command to issue a read command. */ #define COMMAND_READ 0x05 /** DFU command to issue a memory base address change command, to set the current 64KB flash page * that subsequent flash operations should use. */ #define <API key> 0x06 /* Type Defines: */ /** Type define for a non-returning function pointer to the loaded application. */ typedef void (*AppPtr_t)(void) ATTR_NO_RETURN; /** Type define for a structure containing a complete DFU command issued by the host. */ typedef struct { uint8_t Command; /**< Single byte command to perform, one of the COMMAND_* macro values */ uint8_t Data[5]; /**< Command parameters */ uint16_t DataSize; /**< Size of the command parameters */ } DFU_Command_t; /* Enums: */ /** DFU bootloader states. Refer to the DFU class specification for information on each state. */ enum DFU_State_t { appIDLE = 0, appDETACH = 1, dfuIDLE = 2, dfuDNLOAD_SYNC = 3, dfuDNBUSY = 4, dfuDNLOAD_IDLE = 5, dfuMANIFEST_SYNC = 6, dfuMANIFEST = 7, <API key> = 8, dfuUPLOAD_IDLE = 9, dfuERROR = 10 }; /** DFU command status error codes. Refer to the DFU class specification for information on each error code. */ enum DFU_Status_t { OK = 0, errTARGET = 1, errFILE = 2, errWRITE = 3, errERASE = 4, errCHECK_ERASED = 5, errPROG = 6, errVERIFY = 7, errADDRESS = 8, errNOTDONE = 9, errFIRMWARE = 10, errVENDOR = 11, errUSBR = 12, errPOR = 13, errUNKNOWN = 14, errSTALLEDPKT = 15 }; /* Function Prototypes: */ void SetupHardware(void); void ResetHardware(void); void <API key>(void); #if defined(<API key>) static void DiscardFillerBytes(uint8_t NumberOfBytes); static void <API key>(void); static void <API key>(void); static void <API key>(void); static void <API key>(void); static void ProcessWriteCommand(void); static void ProcessReadCommand(void); #endif #endif
.oo-ui-icon-globe { background-image: url('themes/wikimediaui/images/icons/globe.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/globe.svg'); } .oo-ui-image-invert.oo-ui-icon-globe { background-image: url('themes/wikimediaui/images/icons/globe-invert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/globe-invert.svg'); } .<API key>.oo-ui-icon-globe { background-image: url('themes/wikimediaui/images/icons/globe-progressive.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/globe-progressive.svg'); } .oo-ui-icon-map { background-image: url('themes/wikimediaui/images/icons/map-rtl.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/map-rtl.svg'); } .oo-ui-image-invert.oo-ui-icon-map { background-image: url('themes/wikimediaui/images/icons/map-rtl-invert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/map-rtl-invert.svg'); } .<API key>.oo-ui-icon-map { background-image: url('themes/wikimediaui/images/icons/map-rtl-progressive.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/map-rtl-progressive.svg'); } .oo-ui-icon-mapPin { background-image: url('themes/wikimediaui/images/icons/mapPin.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/mapPin.svg'); } .oo-ui-image-invert.oo-ui-icon-mapPin { background-image: url('themes/wikimediaui/images/icons/mapPin-invert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/mapPin-invert.svg'); } .<API key>.oo-ui-icon-mapPin { background-image: url('themes/wikimediaui/images/icons/mapPin-progressive.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/mapPin-progressive.svg'); } .<API key> { background-image: url('themes/wikimediaui/images/icons/mapPinAdd.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/mapPinAdd.svg'); } .oo-ui-image-invert.<API key> { background-image: url('themes/wikimediaui/images/icons/mapPinAdd-invert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/mapPinAdd-invert.svg'); } .<API key>.<API key> { background-image: url('themes/wikimediaui/images/icons/<API key>.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/<API key>.svg'); } .oo-ui-icon-mapTrail { background-image: url('themes/wikimediaui/images/icons/mapTrail.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/mapTrail.svg'); } .oo-ui-image-invert.oo-ui-icon-mapTrail { background-image: url('themes/wikimediaui/images/icons/mapTrail-invert.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/mapTrail-invert.svg'); } .<API key>.oo-ui-icon-mapTrail { background-image: url('themes/wikimediaui/images/icons/<API key>.png'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/wikimediaui/images/icons/<API key>.svg'); }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.Contracts; using System.Linq; using System.Threading.Tasks; using Utilities.DataTypes.Comparison; namespace Utilities.DataTypes { <summary> <API key> extensions </summary> [EditorBrowsable(<API key>.Never)] public static class <API key> { <summary> Copies the dictionary to another dictionary. </summary> <typeparam name="TKey">The type of the key.</typeparam> <typeparam name="TValue">The type of the value.</typeparam> <param name="Dictionary">The dictionary.</param> <param name="Target">The target dictionary.</param> <returns> This </returns> <exception cref="System.<API key>">Thrown if the dictionary is null</exception> public static <API key><TKey, TValue> CopyTo<TKey, TValue>(this <API key><TKey, TValue> Dictionary, <API key><TKey, TValue> Target) { Contract.Requires<<API key>>(Dictionary != null, "Dictionary"); Contract.Requires<<API key>>(Target != null, "Target"); Parallel.ForEach(Dictionary, x => Target.SetValue(x.Key, x.Value)); return Dictionary; } <summary> Gets the value from a dictionary or the default value if it isn't found </summary> <typeparam name="TKey">Key type</typeparam> <typeparam name="TValue">Value type</typeparam> <param name="Dictionary">Dictionary to get the value from</param> <param name="Key">Key to look for</param> <param name="Default">Default value if the key is not found</param> <returns> The value associated with the key or the default value if the key is not found </returns> <exception cref="System.<API key>">Thrown if the dictionary is null</exception> public static TValue GetValue<TKey, TValue>(this <API key><TKey, TValue> Dictionary, TKey Key, TValue Default = default(TValue)) { Contract.Requires<<API key>>(Dictionary != null, "Dictionary"); TValue ReturnValue = Default; return Dictionary.TryGetValue(Key, out ReturnValue) ? ReturnValue : Default; } <summary> Sets the value in a dictionary </summary> <typeparam name="TKey">Key type</typeparam> <typeparam name="TValue">Value type</typeparam> <param name="Dictionary">Dictionary to set the value in</param> <param name="Key">Key to look for</param> <param name="Value">Value to add</param> <returns>The dictionary</returns> <exception cref="System.<API key>">Thrown if the dictionary is null</exception> public static <API key><TKey, TValue> SetValue<TKey, TValue>(this <API key><TKey, TValue> Dictionary, TKey Key, TValue Value) { Contract.Requires<<API key>>(Dictionary != null, "Dictionary"); Dictionary.AddOrUpdate(Key, Value, (x, y) => Value); return Dictionary; } } }
import Vue from 'vue'; import delayedJobMixin from '~/jobs/mixins/delayed_job_mixin'; import mountComponent from 'spec/helpers/<API key>'; describe('DelayedJobMixin', () => { const delayedJobFixture = getJSONFixture('jobs/delayed.json'); const dummyComponent = Vue.extend({ mixins: [delayedJobMixin], props: { job: { type: Object, required: true, }, }, template: '<div>{{ remainingTime }}</div>', }); let vm; beforeEach(() => { jasmine.clock().install(); }); afterEach(() => { vm.$destroy(); jasmine.clock().uninstall(); }); describe('if job is empty object', () => { beforeEach(() => { vm = mountComponent(dummyComponent, { job: {}, }); }); it('sets remaining time to 00:00:00', () => { expect(vm.$el.innerText).toBe('00:00:00'); }); describe('after mounting', () => { beforeEach(done => { Vue.nextTick() .then(done) .catch(done.fail); }); it('doe not update remaining time', () => { expect(vm.$el.innerText).toBe('00:00:00'); }); }); }); describe('if job is delayed job', () => { let <API key> = 42000; beforeEach(() => { spyOn(Date, 'now').and.callFake( () => new Date(delayedJobFixture.scheduled_at).getTime() - <API key>, ); vm = mountComponent(dummyComponent, { job: delayedJobFixture, }); }); it('sets remaining time to 00:00:00', () => { expect(vm.$el.innerText).toBe('00:00:00'); }); describe('after mounting', () => { beforeEach(done => { Vue.nextTick() .then(done) .catch(done.fail); }); it('sets remaining time', () => { expect(vm.$el.innerText).toBe('00:00:42'); }); it('updates remaining time', done => { <API key> = 41000; jasmine.clock().tick(1000); Vue.nextTick() .then(() => { expect(vm.$el.innerText).toBe('00:00:41'); }) .then(done) .catch(done.fail); }); }); }); });