text:
import os
import pytest

from pycondor.basenode import BaseNode

def test_BaseNode_extra_lines_raises():
    with pytest.raises(TypeError) as excinfo:
        BaseNode('test_basenode', extra_lines=1111)
    error = 'extra_lines must be of type str, list, or tuple'
    assert error == str(excinfo.value)

def test_BaseNode_extra_lines_str():
    extra_lines_str = 'single extra line'
    basenode = BaseNode('test_basenode', extra_lines=extra_lines_str)
    assert basenode.extra_lines == [extra_lines_str]

def test_BaseNode_hadchildren():
    basenode = BaseNode('test_basenode')
    assert basenode.haschildren() is False

    child_node = BaseNode('child_basenode')
    basenode.add_child(child_node)
    assert basenode.haschildren() is True

def test_BaseNode_hasparents():
    basenode = BaseNode('test_basenode')
    assert basenode.hasparents() is False

    parent_node = BaseNode('parent_basenode')
    basenode.add_parent(parent_node)
    assert basenode.hasparents() is True

def test_BaseNode_submit_default():
    basenode = BaseNode('test_basenode')

    assert basenode.submit == os.getcwd()

def test_BaseNode_submit_environment_variable(tmpdir, monkeypatch):
    # Use monkeypatch fixture to set pycondor environment variable
    tmp_submit_dir = str(tmpdir.mkdir('submit'))
    monkeypatch.setenv('PYCONDOR_SUBMIT_DIR', tmp_submit_dir)
    basenode = BaseNode('test_basenode')

    assert basenode.submit == tmp_submit_dir


text:
// Uses AMD or browser globals to create a jQuery plugin.
(function (factory) {
  if (typeof define === 'function' && define.amd) {
      // AMD. Register as an anonymous module.
      define(['jquery'], factory);
  } else {
      // Browser globals
      factory(jQuery);
  }
} (function (jQuery) {
    var module = { exports: { } }; // Fake component

/**
 * Expose `Emitter`.
 */

module.exports = Emitter;

/**
 * Initialize a new `Emitter`.
 *
 * @api public
 */

function Emitter(obj) {
  if (obj) return mixin(obj);
};

/**
 * Mixin the emitter properties.
 *
 * @param {Object} obj
 * @return {Object}
 * @api private
 */

function mixin(obj) {
  for (var key in Emitter.prototype) {
    obj[key] = Emitter.prototype[key];
  }
  return obj;
}

/**
 * Listen on the given `event` with `fn`.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */

Emitter.prototype.on = function(event, fn){
  this._callbacks = this._callbacks || {};
  (this._callbacks[event] = this._callbacks[event] || [])
    .push(fn);
  return this;
};

/**
 * Adds an `event` listener that will be invoked a single
 * time then automatically removed.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */

Emitter.prototype.once = function(event, fn){
  var self = this;
  this._callbacks = this._callbacks || {};

  function on() {
    self.off(event, on);
    fn.apply(this, arguments);
  }

  fn._off = on;
  this.on(event, on);
  return this;
};

/**
 * Remove the given callback for `event` or all
 * registered callbacks.
 *
 * @param {String} event
 * @param {Function} fn
 * @return {Emitter}
 * @api public
 */

Emitter.prototype.off =
Emitter.prototype.removeListener =
Emitter.prototype.removeAllListeners = function(event, fn){
  this._callbacks = this._callbacks || {};
  var callbacks = this._callbacks[event];
  if (!callbacks) return this;

  // remove all handlers
  if (1 == arguments.length) {
    delete this._callbacks[event];
    return this;
  }

  // remove specific handler
  var i = callbacks.indexOf(fn._off || fn);
  if (~i) callbacks.splice(i, 1);
  return this;
};

/**
 * Emit `event` with the given args.
 *
 * @param {String} event
 * @param {Mixed} ...
 * @return {Emitter}
 */

Emitter.prototype.emit = function(event){
  this._callbacks = this._callbacks || {};
  var args = [].slice.call(arguments, 1)
    , callbacks = this._callbacks[event];

  if (callbacks) {
    callbacks = callbacks.slice(0);
    for (var i = 0, len = callbacks.length; i < len; ++i) {
      callbacks[i].apply(this, args);
    }
  }

  return this;
};

/**
 * Return array of callbacks for `event`.
 *
 * @param {String} event
 * @return {Array}
 * @api public
 */

Emitter.prototype.listeners = function(event){
  this._callbacks = this._callbacks || {};
  return this._callbacks[event] || [];
};

/**
 * Check if this emitter has `event` handlers.
 *
 * @param {String} event
 * @return {Boolean}
 * @api public
 */

Emitter.prototype.hasListeners = function(event){
  return !! this.listeners(event).length;
};

    // Generated by CoffeeScript 1.4.0

/*
#
# More info at [www.dropzonejs.com](http://www.dropzonejs.com)
#
# Copyright (c) 2012, Matias Meno
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
*/

(function() {
  var Dropzone, Em, camelize, contentLoaded, createElement, noop, without,
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
    __slice = [].slice;

  Em = typeof Emitter !== "undefined" && Emitter !== null ? Emitter : require("emitter");

  noop = function() {};

  Dropzone = (function(_super) {

    __extends(Dropzone, _super);

    /*
      This is a list of all available events you can register on a dropzone object.

      You can register an event handler like this:

          dropzone.on("dragEnter", function() { });
    */

    Dropzone.prototype.events = ["drop", "dragstart", "dragend", "dragenter", "dragover", "dragleave", "selectedfiles", "addedfile", "removedfile", "thumbnail", "error", "processingfile", "uploadprogress", "sending", "success", "complete", "reset"];

    Dropzone.prototype.defaultOptions = {
      url: null,
      parallelUploads: 2,
      maxFilesize: 256,
      paramName: "file",
      createImageThumbnails: true,
      maxThumbnailFilesize: 2,
      thumbnailWidth: 100,
      thumbnailHeight: 100,
      params: {},
      clickable: true,
      enqueueForUpload: true,
      previewsContainer: null,
      dictDefaultMessage: "Drop files here to upload",
      dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.",
      dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.",
      accept: function(file, done) {
        return done();
      },
      init: function() {
        return noop;
      },
      fallback: function() {
        var child, messageElement, span, _i, _len, _ref;
        this.element.className = "" + this.element.className + " browser-not-supported";
        _ref = this.element.getElementsByTagName("div");
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          child = _ref[_i];
          if (/(^| )message($| )/.test(child.className)) {
            messageElement = child;
            child.className = "message";
            continue;
          }
        }
        if (!messageElement) {
          messageElement = createElement("

");
          this.element.appendChild(messageElement);
        }
        span = messageElement.getElementsByTagName("span")[0];
        if (span) {
          span.textContent = this.options.dictFallbackMessage;
        }
        return this.element.appendChild(this.getFallbackForm());
      },
      /*
          Those functions register themselves to the events on init and handle all
          the user interface specific stuff. Overwriting them won't break the upload
          but can break the way it's displayed.
          You can overwrite them if you don't like the default behavior. If you just
          want to add an additional event handler, register it on the dropzone object
          and don't overwrite those options.
      */

      drop: function(e) {
        return this.element.classList.remove("drag-hover");
      },
      dragstart: noop,
      dragend: function(e) {
        return this.element.classList.remove("drag-hover");
      },
      dragenter: function(e) {
        return this.element.classList.add("drag-hover");
      },
      dragover: function(e) {
        return this.element.classList.add("drag-hover");
      },
      dragleave: function(e) {
        return this.element.classList.remove("drag-hover");
      },
      selectedfiles: function(files) {
        if (this.element === this.previewsContainer) {
          return this.element.classList.add("started");
        }
      },
      reset: function() {
        return this.element.classList.remove("started");
      },
      addedfile: function(file) {
        file.previewTemplate = createElement(this.options.previewTemplate);
        this.previewsContainer.appendChild(file.previewTemplate);
        file.previewTemplate.querySelector(".filename span").textContent = file.name;
        return file.previewTemplate.querySelector(".details").appendChild(createElement("
" + (this.filesize(file.size)) + "
"));
      },
      removedfile: function(file) {
        return file.previewTemplate.parentNode.removeChild(file.previewTemplate);
      },
      thumbnail: function(file, dataUrl) {
        file.previewTemplate.classList.remove("file-preview");
        file.previewTemplate.classList.add("image-preview");
        return file.previewTemplate.querySelector(".details").appendChild(createElement(""));
      },
      error: function(file, message) {
        file.previewTemplate.classList.add("error");
        return file.previewTemplate.querySelector(".error-message span").textContent = message;
      },
      processingfile: function(file) {
        return file.previewTemplate.classList.add("processing");
      },
      uploadprogress: function(file, progress) {
        return file.previewTemplate.querySelector(".progress .upload").style.width = "" + progress + "%";
      },
      sending: noop,
      success: function(file) {
        return file.previewTemplate.classList.add("success");
      },
      complete: noop,
      previewTemplate: "
\n
\n

\n
\n

\n
✔
\n
✘
\n

\n
"
    };

    function Dropzone(element, options) {
      var elementId, elementOptions, extend, fallback, _ref;
      this.element = element;
      this.version = Dropzone.version;
      this.defaultOptions.previewTemplate = this.defaultOptions.previewTemplate.replace(/\n*/g, "");
      if (typeof this.element === "string") {
        this.element = document.querySelector(this.element);
      }
      if (!(this.element && (this.element.nodeType != null))) {
        throw new Error("Invalid dropzone element.");
      }
      if (Dropzone.forElement(this.element)) {
        throw new Error("Dropzone already attached.");
      }
      Dropzone.instances.push(this);
      elementId = this.element.id;
      elementOptions = (_ref = (elementId ? Dropzone.options[camelize(elementId)] : void 0)) != null ? _ref : {};
      extend = function() {
        var key, object, objects, target, val, _i, _len;
        target = arguments[0], objects = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
        for (_i = 0, _len = objects.length; _i < _len; _i++) {
          object = objects[_i];
          for (key in object) {
            val = object[key];
            target[key] = val;
          }
        }
        return target;
      };
      this.options = extend({}, this.defaultOptions, elementOptions, options != null ? options : {});
      if (this.options.url == null) {
        this.options.url = this.element.action;
      }
      if (!this.options.url) {
        throw new Error("No URL provided.");
      }
      if (!Dropzone.isBrowserSupported()) {
        return this.options.fallback.call(this);
      }
      if ((fallback = this.getExistingFallback()) && fallback.parentNode) {
        fallback.parentNode.removeChild(fallback);
      }
      if (this.options.previewsContainer) {
        if (typeof this.options.previewsContainer === "string") {
          this.previewsContainer = document.querySelector(this.options.previewsContainer);
        } else if (this.options.previewsContainer.nodeType != null) {
          this.previewsContainer = this.options.previewsContainer;
        }
        if (this.previewsContainer == null) {
          throw new Error("Invalid `previewsContainer` option provided. Please provide a CSS selector or a plain HTML element.");
        }
      } else {
        this.previewsContainer = this.element;
      }
      this.init();
    }

    Dropzone.prototype.init = function() {
      var eventName, noPropagation, _i, _len, _ref, _ref1,
        _this = this;
      if (this.element.tagName === "form") {
        this.element.setAttribute("enctype", "multipart/form-data");
      }
      if (this.element.classList.contains("dropzone") && !this.element.querySelector(".message")) {
        this.element.appendChild(createElement("
" + this.options.dictDefaultMessage + "
"));
      }
      if (this.options.clickable) {
        this.hiddenFileInput = document.createElement("input");
        this.hiddenFileInput.setAttribute("type", "file");
        this.hiddenFileInput.setAttribute("multiple", "multiple");
        this.hiddenFileInput.style.display = "none";
        document.body.appendChild(this.hiddenFileInput);
        this.hiddenFileInput.addEventListener("change", function() {
          var files;
          files = _this.hiddenFileInput.files;
          if (files.length) {
            _this.emit("selectedfiles", files);
            return _this.handleFiles(files);
          }
        });
      }
      this.files = [];
      this.filesQueue = [];
      this.filesProcessing = [];
      this.URL = (_ref = window.URL) != null ? _ref : window.webkitURL;
      _ref1 = this.events;
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        eventName = _ref1[_i];
        this.on(eventName, this.options[eventName]);
      }
      noPropagation = function(e) {
        e.stopPropagation();
        if (e.preventDefault) {
          return e.preventDefault();
        } else {
          return e.returnValue = false;
        }
      };
      this.listeners = {
        "dragstart": function(e) {
          return _this.emit("dragstart", e);
        },
        "dragenter": function(e) {
          noPropagation(e);
          return _this.emit("dragenter", e);
        },
        "dragover": function(e) {
          noPropagation(e);
          return _this.emit("dragover", e);
        },
        "dragleave": function(e) {
          return _this.emit("dragleave", e);
        },
        "drop": function(e) {
          noPropagation(e);
          _this.drop(e);
          return _this.emit("drop", e);
        },
        "dragend": function(e) {
          return _this.emit("dragend", e);
        },
        "click": function(evt) {
          if (!_this.options.clickable) {
            return;
          }
          if (evt.target === _this.element || evt.target === _this.element.querySelector(".message")) {
            return _this.hiddenFileInput.click();
          }
        }
      };
      this.enable();
      return this.options.init.call(this);
    };

    Dropzone.prototype.getFallbackForm = function() {
      var existingFallback, fields, fieldsString, form;
      if (existingFallback = this.getExistingFallback()) {
        return existingFallback;
      }
      fieldsString = "
";
      if (this.options.dictFallbackText) {
        fieldsString += "
" + this.options.dictFallbackText + "
";
      }
      fieldsString += "<input type=\"file\" name=\"" + this.options.paramName + "\" multiple=\"multiple\" /><button type=\"submit\">Upload!</button>
";
      fields = createElement(fieldsString);
      if (this.element.tagName !== "FORM") {
        form = createElement("<form action=\"" + this.options.url + "\" enctype=\"multipart/form-data\" method=\"post\"></form>");
        form.appendChild(fields);
      } else {
        this.element.setAttribute("enctype", "multipart/form-data");
        this.element.setAttribute("method", "post");
      }
      return form != null ? form : fields;
    };

    Dropzone.prototype.getExistingFallback = function() {
      var fallback, getFallback, tagName, _i, _len, _ref;
      getFallback = function(elements) {
        var el, _i, _len;
        for (_i = 0, _len = elements.length; _i < _len; _i++) {
          el = elements[_i];
          if (/(^| )fallback($| )/.test(el.className)) {
            return el;
          }
        }
      };
      _ref = ["div", "form"];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        tagName = _ref[_i];
        if (fallback = getFallback(this.element.getElementsByTagName("div"))) {
          return fallback;
        }
      }
    };

    Dropzone.prototype.setupEventListeners = function() {
      var event, listener, _ref, _results;
      _ref = this.listeners;
      _results = [];
      for (event in _ref) {
        listener = _ref[event];
        _results.push(this.element.addEventListener(event, listener, false));
      }
      return _results;
    };

    Dropzone.prototype.removeEventListeners = function() {
      var event, listener, _ref, _results;
      _ref = this.listeners;
      _results = [];
      for (event in _ref) {
        listener = _ref[event];
        _results.push(this.element.removeEventListener(event, listener, false));
      }
      return _results;
    };

    Dropzone.prototype.disable = function() {
      if (this.options.clickable) {
        this.element.classList.remove("clickable");
      }
      this.removeEventListeners();
      this.filesProcessing = [];
      return this.filesQueue = [];
    };

    Dropzone.prototype.enable = function() {
      if (this.options.clickable) {
        this.element.classList.add("clickable");
      }
      return this.setupEventListeners();
    };

    Dropzone.prototype.filesize = function(size) {
      var string;
      if (size >= 100000000000) {
        size = size / 100000000000;
        string = "TB";
      } else if (size >= 100000000) {
        size = size / 100000000;
        string = "GB";
      } else if (size >= 100000) {
        size = size / 100000;
        string = "MB";
      } else if (size >= 100) {
        size = size / 100;
        string = "KB";
      } else {
        size = size * 10;
        string = "b";
      }
      return "" + (Math.round(size) / 10) + " " + string;
    };

    Dropzone.prototype.drop = function(e) {
      var files;
      if (!e.dataTransfer) {
        return;
      }
      files = e.dataTransfer.files;
      this.emit("selectedfiles", files);
      if (files.length) {
        return this.handleFiles(files);
      }
    };

    Dropzone.prototype.handleFiles = function(files) {
      var file, _i, _len, _results;
      _results = [];
      for (_i = 0, _len = files.length; _i < _len; _i++) {
        file = files[_i];
        _results.push(this.addFile(file));
      }
      return _results;
    };

    Dropzone.prototype.accept = function(file, done) {
      if (file.size > this.options.maxFilesize * 1024 * 1024) {
        return done("File is too big (" + (Math.round(file.size / 1024 / 10.24) / 100) + "MB). Max filesize: " + this.options.maxFilesize + "MB");
      } else {
        return this.options.accept.call(this, file, done);
      }
    };

    Dropzone.prototype.addFile = function(file) {
      var _this = this;
      this.files.push(file);
      this.emit("addedfile", file);
      if (this.options.createImageThumbnails && file.type.match(/image.*/) && file.size <= this.options.maxThumbnailFilesize * 1024 * 1024) {
        this.createThumbnail(file);
      }
      return this.accept(file, function(error) {
        if (error) {
          return _this.errorProcessing(file, error);
        } else {
          if (_this.options.enqueueForUpload) {
            _this.filesQueue.push(file);
            return _this.processQueue();
          }
        }
      });
    };

    Dropzone.prototype.removeFile = function(file) {
      if (file.processing) {
        throw new Error("Can't remove file currently processing");
      }
      this.files = without(this.files, file);
      this.filesQueue = without(this.filesQueue, file);
      this.emit("removedfile", file);
      if (this.files.length === 0) {
        return this.emit("reset");
      }
    };

    Dropzone.prototype.createThumbnail = function(file) {
      var fileReader,
        _this = this;
      fileReader = new FileReader;
      fileReader.onload = function() {
        var img;
        img = new Image;
        img.onload = function() {
          var canvas, ctx, srcHeight, srcRatio, srcWidth, srcX, srcY, thumbnail, trgHeight, trgRatio, trgWidth, trgX, trgY;
          canvas = document.createElement("canvas");
          ctx = canvas.getContext("2d");
          srcX = 0;
          srcY = 0;
          srcWidth = img.width;
          srcHeight = img.height;
          canvas.width = _this.options.thumbnailWidth;
          canvas.height = _this.options.thumbnailHeight;
          trgX = 0;
          trgY = 0;
          trgWidth = canvas.width;
          trgHeight = canvas.height;
          srcRatio = img.width / img.height;
          trgRatio = canvas.width / canvas.height;
          if (img.height < canvas.height || img.width < canvas.width) {
            trgHeight = srcHeight;
            trgWidth = srcWidth;
          } else {
            if (srcRatio > trgRatio) {
              srcHeight = img.height;
              srcWidth = srcHeight * trgRatio;
            } else {
              srcWidth = img.width;
              srcHeight = srcWidth / trgRatio;
            }
          }
          srcX = (img.width - srcWidth) / 2;
          srcY = (img.height - srcHeight) / 2;
          trgY = (canvas.height - trgHeight) / 2;
          trgX = (canvas.width - trgWidth) / 2;
          ctx.drawImage(img, srcX, srcY, srcWidth, srcHeight, trgX, trgY, trgWidth, trgHeight);
          thumbnail = canvas.toDataURL("image/png");
          return _this.emit("thumbnail", file, thumbnail);
        };
        return img.src = fileReader.result;
      };
      return fileReader.readAsDataURL(file);
    };

    Dropzone.prototype.processQueue = function() {
      var i, parallelUploads, processingLength;
      parallelUploads = this.options.parallelUploads;
      processingLength = this.filesProcessing.length;
      i = processingLength;
      while (i < parallelUploads) {
        if (!this.filesQueue.length) {
          return;
        }
        this.processFile(this.filesQueue.shift());
        i++;
      }
    };

    Dropzone.prototype.processFile = function(file) {
      this.filesProcessing.push(file);
      file.processing = true;
      this.emit("processingfile", file);
      return this.uploadFile(file);
    };

    Dropzone.prototype.uploadFile = function(file) {
      var formData, handleError, input, inputName, inputType, key, progressObj, value, xhr, _i, _len, _ref, _ref1, _ref2,
        _this = this;
      xhr = new XMLHttpRequest();
      xhr.open("POST", this.options.url, true);
      handleError = function() {
        return _this.errorProcessing(file, xhr.responseText || ("Server responded with " + xhr.status + " code."));
      };
      xhr.onload = function(e) {
        var response, _ref;
        if (!((200 <= (_ref = xhr.status) && _ref < 300))) {
          return handleError();
        } else {
          _this.emit("uploadprogress", file, 100);
          response = xhr.responseText;
          if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) {
            response = JSON.parse(response);
          }
          return _this.finished(file, response, e);
        }
      };
      xhr.onerror = function() {
        return handleError();
      };
      progressObj = (_ref = xhr.upload) != null ? _ref : xhr;
      progressObj.onprogress = function(e) {
        return _this.emit("uploadprogress", file, Math.max(0, Math.min(100, (e.loaded / e.total) * 100)));
      };
      xhr.setRequestHeader("Accept", "application/json");
      xhr.setRequestHeader("Cache-Control", "no-cache");
      xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
      xhr.setRequestHeader("X-File-Name", file.name);
      formData = new FormData();
      if (this.options.params) {
        _ref1 = this.options.params;
        for (key in _ref1) {
          value = _ref1[key];
          formData.append(key, value);
        }
      }
      if (this.element.tagName = "FORM") {
        _ref2 = this.element.querySelectorAll("input, textarea, select, button");
        for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
          input = _ref2[_i];
          inputName = input.getAttribute("name");
          inputType = input.getAttribute("type");
          if (!inputType || inputType.toLowerCase() !== "checkbox" || input.checked) {
            formData.append(inputName, input.value);
          }
        }
      }
      this.emit("sending", file, xhr, formData);
      formData.append(this.options.paramName, file);
      return xhr.send(formData);
    };

    Dropzone.prototype.finished = function(file, responseText, e) {
      this.filesProcessing = without(this.filesProcessing, file);
      file.processing = false;
      this.processQueue();
      this.emit("success", file, responseText, e);
      this.emit("finished", file, responseText, e);
      return this.emit("complete", file);
    };

    Dropzone.prototype.errorProcessing = function(file, message) {
      this.filesProcessing = without(this.filesProcessing, file);
      file.processing = false;
      this.processQueue();
      this.emit("error", file, message);
      return this.emit("complete", file);
    };

    return Dropzone;

  })(Em);

  Dropzone.version = "2.0.5-dev";

  Dropzone.options = {};

  Dropzone.instances = [];

  Dropzone.forElement = function(element) {
    var instance, _i, _len, _ref;
    if (typeof element === "string") {
      element = document.querySelector(element);
    }
    _ref = Dropzone.instances;
    for (_i = 0, _len = _ref.length; _i < _len; _i++) {
      instance = _ref[_i];
      if (instance.element === element) {
        return instance;
      }
    }
    return null;
  };

  Dropzone.blacklistedBrowsers = [/opera.*Macintosh.*version\/12/i];

  Dropzone.isBrowserSupported = function() {
    var capableBrowser, regex, _i, _len, _ref;
    capableBrowser = true;
    if (window.File && window.FileReader && window.FileList && window.Blob && window.FormData && document.querySelector) {
      if (!("classList" in document.createElement("a"))) {
        capableBrowser = false;
      } else {
        _ref = Dropzone.blacklistedBrowsers;
        for (_i = 0, _len = _ref.length; _i < _len; _i++) {
          regex = _ref[_i];
          if (regex.test(navigator.userAgent)) {
            capableBrowser = false;
            continue;
          }
        }
      }
    } else {
      capableBrowser = false;
    }
    return capableBrowser;
  };

  without = function(list, rejectedItem) {
    var item, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = list.length; _i < _len; _i++) {
      item = list[_i];
      if (item !== rejectedItem) {
        _results.push(item);
      }
    }
    return _results;
  };

  camelize = function(str) {
    return str.replace(/[\-_](\w)/g, function(match) {
      return match[1].toUpperCase();
    });
  };

  createElement = function(string) {
    var div;
    div = document.createElement("div");
    div.innerHTML = string;
    return div.childNodes[0];
  };

  if (typeof jQuery !== "undefined" && jQuery !== null) {
    jQuery.fn.dropzone = function(options) {
      return this.each(function() {
        return new Dropzone(this, options);
      });
    };
  }

  if (typeof module !== "undefined" && module !== null) {
    module.exports = Dropzone;
  } else {
    window.Dropzone = Dropzone;
  }

  contentLoaded = function(win, fn) {
    var add, doc, done, init, poll, pre, rem, root, top;
    done = false;
    top = true;
    doc = win.document;
    root = doc.documentElement;
    add = (doc.addEventListener ? "addEventListener" : "attachEvent");
    rem = (doc.addEventListener ? "removeEventListener" : "detachEvent");
    pre = (doc.addEventListener ? "" : "on");
    init = function(e) {
      if (e.type === "readystatechange" && doc.readyState !== "complete") {
        return;
      }
      (e.type === "load" ? win : doc)[rem](pre + e.type, init, false);
      if (!done && (done = true)) {
        return fn.call(win, e.type || e);
      }
    };
    poll = function() {
      try {
        root.doScroll("left");
      } catch (e) {
        setTimeout(poll, 50);
        return;
      }
      return init("poll");
    };
    if (doc.readyState !== "complete") {
      if (doc.createEventObject && root.doScroll) {
        try {
          top = !win.frameElement;
        } catch (_error) {}
        if (top) {
          poll();
        }
      }
      doc[add](pre + "DOMContentLoaded", init, false);
      doc[add](pre + "readystatechange", init, false);
      return win[add](pre + "load", init, false);
    }
  };

  contentLoaded(window, function() {
    var checkElements, dropzone, dropzones, _i, _len, _results;
    if (false) {
      dropzones = document.querySelectorAll(".dropzone");
    } else {
      dropzones = [];
      checkElements = function(elements) {
        var el, _i, _len, _results;
        _results = [];
        for (_i = 0, _len = elements.length; _i < _len; _i++) {
          el = elements[_i];
          if (/(^| )dropzone($| )/.test(el.className)) {
            _results.push(dropzones.push(el));
          } else {
            _results.push(void 0);
          }
        }
        return _results;
      };
      checkElements(document.getElementsByTagName("div"));
      checkElements(document.getElementsByTagName("form"));
    }
    _results = [];
    for (_i = 0, _len = dropzones.length; _i < _len; _i++) {
      dropzone = dropzones[_i];
      _results.push(new Dropzone(dropzone));
    }
    return _results;
  });

}).call(this);

    return module.exports;
}));

redpajama_set_name: RedPajamaGithub


text:
from __future__ import absolute_import

from sentry.api.base import DocSection
from sentry.api.bases.group import GroupEndpoint
from sentry.api.serializers import serialize
from sentry.api.paginator import DateTimePaginator
from sentry.models import Event

class GroupEventsEndpoint(GroupEndpoint):
    doc_section = DocSection.EVENTS

    def get(self, request, group):
        """
        List an aggregate's available samples

        Return a list of sampled events bound to an aggregate.

            {method} {path}

        """

        events = Event.objects.filter(
            group=group
        )

        return self.paginate(
            request=request,
            queryset=events,
            order_by='-datetime',
            on_results=lambda x: serialize(x, request.user),
            paginator_cls=DateTimePaginator,
        )


text:
<link rel="import" href="firebase_collection_nodart.html">
<link rel="import" href="firebase_query_behavior.html">

<script type="application/dart" src="firebase_collection.dart"></script>


text:
package com.fasterxml.jackson.annotation;

// Silly test for OptBoolean, for code coverage
public class OptBooleanTest extends TestBase
{
    public void testProperties()
    {
        assertTrue(OptBoolean.TRUE.asPrimitive());
        assertFalse(OptBoolean.FALSE.asPrimitive());
        assertFalse(OptBoolean.DEFAULT.asPrimitive());

        assertSame(OptBoolean.FALSE, OptBoolean.fromBoolean(false));
        assertSame(OptBoolean.TRUE, OptBoolean.fromBoolean(true));
    }
}


text:
package com.oltruong.demo;

import org.junit.runner.RunWith;

import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;

@RunWith(Cucumber.class)
@CucumberOptions(features = "classpath:features", format = {"html:target/cucumber-html-report","json:target/cucumber.json"})
public class RunCukesIT {

}


text:
package org.laladev.moneyjinn.model;

import java.io.Serializable;

public abstract class AbstractEntityID<I extends Serializable> implements Serializable {
	private static final long serialVersionUID = 1L;
	private I id;

	protected AbstractEntityID() {
	}

	protected AbstractEntityID(final I id) {
		this.id = id;
	}

	public final I getId() {
		return this.id;
	}

	public final void setId(final I id) {
		this.id = id;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());
		return result;
	}

	@Override
	public boolean equals(final Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (this.getClass() != obj.getClass()) {
			return false;
		}
		final AbstractEntityID<?> other = (AbstractEntityID<?>) obj;
		if (this.id == null) {
			if (other.id != null) {
				return false;
			}
		} else if (!this.id.equals(other.id)) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		final StringBuilder builder = new StringBuilder();
		builder.append("[id=").append(this.id).append("]");
		return builder.toString();
	}

}


text:
class InstantclientOdbc < Formula
  desc "Oracle Instant Client ODBC x64"
  homepage "https://www.oracle.com/database/technologies/instant-client/macos-intel-x86-downloads.html"

  url "https://download.oracle.com/otn_software/mac/instantclient/198000/instantclient-odbc-macos.x64-19.8.0.0.0dbru.zip"
  sha256 "4bafb93f875a2bffa75f0a0798e923e032241edc1dccee463a408223ad766d16"

  option "with-basiclite", "Depend on instantclient-basiclite instead of instantclient-basic."

  depends_on "instantclient-basic" if build.without?("basiclite")
  depends_on "instantclient-basiclite" if build.with?("basiclite")

  def install
    lib.install Dir["*.dylib*"]
  end
end


text:
from flask import Flask
from crochet import setup, run_in_reactor, wait_for

## this MUST be called _before_ any Autobahn or Twisted imports!
setup()

from autobahn.twisted.wamp import Application

## our WAMP app
##
wapp = Application()

## this is a synchronous wrapper around the asynchronous WAMP code
##
@wait_for(timeout = 1)
def publish(topic, *args, **kwargs):
   return wapp.session.publish(topic, *args, **kwargs)

## our Flask app
##
app = Flask(__name__)
app._visits = 0

@app.route('/')
def index():
   app._visits += 1
   publish('com.example.on_visit', app._visits, msg = "hello from flask")
   return "Visit {}".format(app._visits)

if __name__ == '__main__':
   import sys
   import logging
   logging.basicConfig(stream = sys.stderr, level = logging.DEBUG)

   ## this will start the WAMP app on a background thread and setup communication
   ## with the main thread that runs a (blocking) Flask server
   ##
   @run_in_reactor
   def start_wamp():
      wapp.run("ws://localhost:9000", "realm1", standalone = True, start_reactor = False)

   start_wamp()

   ## now start the Flask dev server (which is a regular blocking WSGI server)
   ##
   app.run(port = 8080)


text:
<?php

namespace Kraken\_Unit\Runtime\Command\Container;

use Kraken\_Unit\Runtime\Command\_T\TCommand;
use Kraken\Runtime\Command\Container\ContainerStopCommand;

class ContainerStopCommandTest extends TCommand
{
    /**
     * @var string
     */
    protected $class = ContainerStopCommand::class;

    /**
     *
     */
    public function testApiCommand_InvokesProperAction()
    {
        $command = $this->createCommand();
        $runtime = $this->createRuntime([ 'stop' ]);
        $runtime
            ->expects($this->once())
            ->method('stop');

        $this->assertSame(
            null,
            $this->callProtectedMethod(
                $command, 'command', []
            )
        );
    }
}


text:
export instance_type=n1-standard-8
export instance_name=fusion-4-1-0
export centos7ver=v20180716

# Create firewall rule for Fusion Console (port 8764) (tag instances w/ 'fusion-server')
gcloud compute --project="$GOOGLE_CLOUD_PROJECT" firewall-rules create allow-fusion --network=default --allow=tcp:8764 --source-ranges=0.0.0.0/0 --target-tags=fusion-server

gcloud compute --project "$GOOGLE_CLOUD_PROJECT" instances create "$instance_name" \
  --zone "us-central1-c" --machine-type "$instance_type" --subnet "default" \
  --metadata "startup-script=curl https://raw.githubusercontent.com/lucidworks/fusion-examples/master/misc/scripts/RHEL_7_Fusion_Setup.sh >setup.sh && chmod +x setup.sh && ./setup.sh" \
  --no-restart-on-failure --maintenance-policy "TERMINATE" --preemptible \
  --service-account "731036704764-compute@developer.gserviceaccount.com" \
  --scopes "https://www.googleapis.com/auth/devstorage.read_only","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/monitoring.write","https://www.googleapis.com/auth/servicecontrol","https://www.googleapis.com/auth/service.management.readonly","https://www.googleapis.com/auth/trace.append" \
  --tags "http-server","https-server","fusion-server" \
  --image "centos-7-$centos7ver" --image-project "centos-cloud" \
  --boot-disk-size "100" --boot-disk-type "pd-ssd" --boot-disk-device-name "$instance_name"


text:
package org.dice.solrenhancements.queryparsers;

import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.search.QParser;
import org.apache.solr.search.QParserPlugin;
import org.dice.solrenhancements.JarVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by simon.hughes on 7/31/15.
 */
public class QueryBoostingQParserPlugin extends QParserPlugin {
    public static String NAME = "queryboost";

    @Override
    public void init(NamedList args) {
    }

    @Override
    public QParser createParser(String qstr, SolrParams localParams, SolrParams params, SolrQueryRequest req) {
        return new QueryBoostingQParser(qstr, localParams, params, req);
    }

    private static final Logger Log = LoggerFactory.getLogger(QueryBoostingQParserPlugin.class);

    private String version = null;

    @Override
    public String getVersion() {
        if (version != null) {
            return version;
        }

        version = JarVersion.getVersion(Log);
        return version;
    }
}


text:
/**
 * <details> and <summary> crossbrowser support
 *
 * This polyfill makes <details>/<summary> ready for use
 * in all modern browsers.
 * http://dev.w3.org/html5/spec/Overview.html#the-details-element
 *
 * @author Marian Kostadinov
 * @version 0.5
 * @license http://www.gnu.org/licenses/lgpl-3.0.txt LGPL
 *
 * Date $LastChangedDate: 2012-05-27 09:07:30 +0300 (Sun, 27 May 2012) $
 *
 */

;(function() {
    var summaryNode = 'summary';
    var detailsNode = 'details';

    //Power up old IEs. When these are created, IE understands that
    //there are suche elements.
    document.createElement (detailsNode);
    document.createElement (summaryNode);

    function init() {

        //Feature support check used here:
        //http://mathiasbynens.be/notes/html5-details-jquery
        var isDetailsSupported = (function(doc) {
            var el = doc.createElement('details'), fake, root, diff;
            if (!('open' in el)) {
                return false;
            }
            root = doc.body || (function() {
                var de = doc.documentElement;
                fake = true;
                return de.insertBefore (doc.createElement('body'), de.firstElementChild || de.firstChild);
            }());
            el.innerHTML = '<summary>a</summary>b';
            el.style.display = 'block';
            root.appendChild (el);
            diff = el.offsetHeight;
            el.open = true;
            diff = diff != el.offsetHeight;
            root.removeChild(el);
            if (fake) {
                root.parentNode.removeChild(root);
            }
            return diff;
        }(document));

        if (!isDetailsSupported) {
            var rightArrow = String.fromCharCode (9658);
            var downArrow = String.fromCharCode (9660);

            var styles = [
                'details > * {position: absolute;top: -4000px;left: -4000px;}',
                'details > summary, details[open] > * {position: static;}',
                'details, details > summary {display: block;}',
                'details > summary:before {content: "' + rightArrow + '";padding-right: 5px;font-size: 15px;padding-bottom:2px;}',
                'details[open] > summary:before {content:"' + downArrow + '"}'
            ];

            if (/*IE7*/ false) {
                //TODO - add a background-image for right and down arrows
                styles.push ('details > summary { ... }');
            }
            styles = styles.join ('\n');

            //Build a stylesheet for the css based handling.
            var head = document.getElementsByTagName ('HEAD')[0];
            var css = document.createElement('style');
            css.type = 'text/css';
            if (css.styleSheet) {
                css.styleSheet.cssText = styles;
            } else {
                css.appendChild(document.createTextNode(styles));
            }

            //Insert the stylesheet on the top.
            //The idea is to keep it before other stylesheets
            //so they can be applied after this one.
            var c = head.childNodes && head.childNodes[0];
            if (c) {
                head.insertBefore (css, c);
            } else {
                head.appendChild (css);
            }

            var body = document.getElementsByTagName ('BODY')[0];

            if (!window.addEventListener) {
                window.addEventListener = function (eventType, callback, dummy) {
                    //This is intentional. The click event is firing on document for IE<9.
                    document.attachEvent ('on' + eventType, function (event) {
                        //Compatibility code for the event object.
                        var e = event || window.event;
                        if (!e.target) e.target = e.srcElement;
                        if (typeof e.preventDefault != 'function') {
                            e.preventDefault = function() { this.returnValue = false; };
                        }
                        if (typeof e.stopPropagation != 'function') {
                            e.stopPropagation = function() { this.cancelBubble = true; };
                        }
                        callback (e);
                    });
                };

            }

            //Body class name gets altered in order to trigger
            //document rerender, because set/remove attribute
            //function don't do it.
            var dummyClassName = 'trigger-refresh ';
            var dummyClassNameLength = dummyClassName.length;
            body.className = body.className || '';

            //Now what we need is a click listener that toggles the open
            //attribute of the details element only when the click
            //is on its summary child element.
            window.addEventListener ('click', function (event) {
                var target = event.target;
                var targetNode, parentNode;

                //The loop is required because there can be additional
                //child elements within the summary element.
                while (target) {
                    targetNode = target.nodeName.toLowerCase();
                    if (targetNode == summaryNode) {
                        parentNode = target.parentNode;
                        //getAttributeNode is used instead of hasAttribute because
                        //older IEs don't support it.
                        if (parentNode.getAttributeNode ('open')) {
                            parentNode.removeAttribute ('open');
                        } else {
                            parentNode.setAttribute ('open', 'open');
                        }
                        //Force refresh for IE.
                        body.className = dummyClassName + body.className;
                        body.className = body.className.substr (dummyClassNameLength);
                        break;
                    }
                    if (targetNode == detailsNode) {
                        break;
                    }
                    target = target.parentNode;
                }
            }, false);
        }
    }

    //Wait for the BODY element to become available
    function loader() {
        if (document.getElementsByTagName ('BODY').length > 0) {
            init();
        } else {
            setTimeout (loader, 50);
        }
    }
    loader();
})();


text:
namespace base {
class SequencedTaskRunner;
class Thread;
}  // namespace base

namespace service_manager {
class Connector;
}  // namespace service_manager

namespace chromecast {
namespace external_mojo {
class ExternalMojoBroker;

// A Mojo service (intended to run within cast_shell or some other Chromium
// ServiceManager environment) that allows Mojo services built into external
// processes to interoperate with the Mojo services within cast_shell.
class BrokerService : public ::service_manager::Service {
 public:
  static BrokerService* GetInstance();
  static void ServiceRequestHandler(
      mojo::PendingReceiver<service_manager::mojom::Service> receiver);

  static constexpr char const* kServiceName = "external_mojo_broker";

  // Adds a manifest for an external Mojo service (ie, one that is running in
  // a non-Chromium process). A manifest is only needed for external services
  // that bind to Mojo services within cast_shell, or for external services that
  // are bound to (used) by internal Mojo services. All external manifests must
  // be added before GetExternalMojoBrokerManifest() is called (otherwise they
  // will not be included in the broker manifest, and so the relevant
  // permissions will not be set correctly).
  static void AddExternalServiceManifest(service_manager::Manifest manifest);

  // Returns the manifest for this service.
  static const service_manager::Manifest& GetManifest();

  explicit BrokerService(service_manager::Connector* connector);

  BrokerService(const BrokerService&) = delete;
  BrokerService& operator=(const BrokerService&) = delete;

  ~BrokerService() override;

  // ::service_manager::Service implementation:
  void OnConnect(const service_manager::BindSourceInfo& source,
                 const std::string& interface_name,
                 mojo::ScopedMessagePipeHandle interface_pipe) override;

  // Dispenses a connector for use in a remote process. The remote process must
  // already belong to the same process network as the BrokerService.
  mojo::PendingRemote<mojom::ExternalConnector> CreateConnector();

 private:
  void BindServiceRequest(
      mojo::PendingReceiver<service_manager::mojom::Service> receiver);

  void BindConnector(mojo::PendingReceiver<mojom::ExternalConnector> receiver);

  service_manager::ServiceReceiver service_receiver_{this};

  std::unique_ptr<base::Thread> io_thread_;
  scoped_refptr<base::SequencedTaskRunner> io_task_runner_;

  InterfaceBundle bundle_;

  base::SequenceBound<ExternalMojoBroker> broker_;
};

}  // namespace external_mojo
}  // namespace chromecast

#endif  // CHROMECAST_EXTERNAL_MOJO_BROKER_SERVICE_BROKER_SERVICE_H_


text:
<?php

declare(strict_types = 1);

namespace dpi\ak;

use dpi\ak\Annotation\AvatarService;

/**
 * Discovers avatar services.
 */
interface AvatarServiceDiscoveryInterface {

  /**
   * Get all annotations.
   *
   * @return \dpi\ak\Annotation\AvatarService[]
   *   Get all discovered avatar services, keyed by class name.
   */
  public function getAvatarServices() : array;

  /**
   * Get metadata for an avatar service.
   *
   * @param string $id
   *   An avatar service ID.
   *
   * @return \dpi\ak\Annotation\AvatarService
   *   An avatar service annotation.
   *
   * @throws \dpi\ak\Exception\AvatarDiscoveryException
   *   Thrown if the service does not exist.
   */
  public function getMetadata(string $id) : AvatarService;

  /**
   * Get class name of an avatar service.
   *
   * @param string $id
   *   An avatar service ID.
   *
   * @return string
   *   The class name of an avatar service.
   *
   * @throws \dpi\ak\Exception\AvatarDiscoveryException
   *   Thrown if the service does not exist.
   */
  public function getClass(string $id) : string;

}


text:
<?php

namespace Spatie\MediaLibrary\ImageGenerators;

use Spatie\MediaLibrary\Conversion\Conversion;
use Spatie\MediaLibrary\Media;

interface ImageGenerator
{
    public function canConvert(Media $media);

    /**
     * Receive a file and return a thumbnail in jpg/png format.
     *
     * @param string $path
     * @param \Spatie\MediaLibrary\Conversion\Conversion|null $conversion
     *
     * @return string
     */
    public function convert(string $path, Conversion $conversion = null) : string;

    public function canHandleMime(string $mime = ''): bool;

    public function canHandleExtension(string $extension = ''): bool;

    public function getType(): string;
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.docs.v1.model;

/**
 * A StructuralElement describes content that provides structure to the document.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Google Docs API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class StructuralElement extends com.google.api.client.json.GenericJson {

  /**
   * The zero-based end index of this structural element, exclusive, in UTF-16 code units.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer endIndex;

  /**
   * A paragraph type of structural element.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private Paragraph paragraph;

  /**
   * A section break type of structural element.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private SectionBreak sectionBreak;

  /**
   * The zero-based start index of this structural element, in UTF-16 code units.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Integer startIndex;

  /**
   * A table type of structural element.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private Table table;

  /**
   * A table of contents type of structural element.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private TableOfContents tableOfContents;

  /**
   * The zero-based end index of this structural element, exclusive, in UTF-16 code units.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getEndIndex() {
    return endIndex;
  }

  /**
   * The zero-based end index of this structural element, exclusive, in UTF-16 code units.
   * @param endIndex endIndex or {@code null} for none
   */
  public StructuralElement setEndIndex(java.lang.Integer endIndex) {
    this.endIndex = endIndex;
    return this;
  }

  /**
   * A paragraph type of structural element.
   * @return value or {@code null} for none
   */
  public Paragraph getParagraph() {
    return paragraph;
  }

  /**
   * A paragraph type of structural element.
   * @param paragraph paragraph or {@code null} for none
   */
  public StructuralElement setParagraph(Paragraph paragraph) {
    this.paragraph = paragraph;
    return this;
  }

  /**
   * A section break type of structural element.
   * @return value or {@code null} for none
   */
  public SectionBreak getSectionBreak() {
    return sectionBreak;
  }

  /**
   * A section break type of structural element.
   * @param sectionBreak sectionBreak or {@code null} for none
   */
  public StructuralElement setSectionBreak(SectionBreak sectionBreak) {
    this.sectionBreak = sectionBreak;
    return this;
  }

  /**
   * The zero-based start index of this structural element, in UTF-16 code units.
   * @return value or {@code null} for none
   */
  public java.lang.Integer getStartIndex() {
    return startIndex;
  }

  /**
   * The zero-based start index of this structural element, in UTF-16 code units.
   * @param startIndex startIndex or {@code null} for none
   */
  public StructuralElement setStartIndex(java.lang.Integer startIndex) {
    this.startIndex = startIndex;
    return this;
  }

  /**
   * A table type of structural element.
   * @return value or {@code null} for none
   */
  public Table getTable() {
    return table;
  }

  /**
   * A table type of structural element.
   * @param table table or {@code null} for none
   */
  public StructuralElement setTable(Table table) {
    this.table = table;
    return this;
  }

  /**
   * A table of contents type of structural element.
   * @return value or {@code null} for none
   */
  public TableOfContents getTableOfContents() {
    return tableOfContents;
  }

  /**
   * A table of contents type of structural element.
   * @param tableOfContents tableOfContents or {@code null} for none
   */
  public StructuralElement setTableOfContents(TableOfContents tableOfContents) {
    this.tableOfContents = tableOfContents;
    return this;
  }

  @Override
  public StructuralElement set(String fieldName, Object value) {
    return (StructuralElement) super.set(fieldName, value);
  }

  @Override
  public StructuralElement clone() {
    return (StructuralElement) super.clone();
  }

}


text:
import {Component} from '@angular/core';
import { Title } from "@angular/platform-browser";

@Component({
  selector: 'home',
  styleUrls: ['./home.component.css'],
  templateUrl: './home.component.html'
})
export class HomeComponent {
  constructor(private title: Title) { }

  ngOnInit() {
    this.title.setTitle("Hello from Home Component");
  }
}


text:
package org.cfr.capsicum.log;

import java.lang.reflect.Array;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import org.apache.cayenne.ExtendedEnumeration;
import org.apache.cayenne.access.jdbc.ParameterBinding;
import org.apache.cayenne.conn.DataSourceInfo;
import org.apache.cayenne.log.JdbcEventLogger;
import org.apache.cayenne.map.DbAttribute;
import org.apache.cayenne.util.IDUtil;
import org.apache.cayenne.util.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Slf4jJdbcEventLogger implements JdbcEventLogger {

    private static final Logger logger = LoggerFactory.getLogger(Slf4jJdbcEventLogger.class);

    private static final int TRIM_VALUES_THRESHOLD = 30;

    void sqlLiteralForObject(StringBuilder buffer, Object object) {
        if (object == null) {
            buffer.append("NULL");
        } else if (object instanceof String) {
            buffer.append('\'');
            // lets escape quotes
            String literal = (String) object;
            if (literal.length() > TRIM_VALUES_THRESHOLD) {
                literal = literal.substring(0, TRIM_VALUES_THRESHOLD)
                        + "...";
            }

            int curPos = 0;
            int endPos = 0;

            while ((endPos = literal.indexOf('\'', curPos)) >= 0) {
                buffer.append(literal.substring(curPos, endPos + 1)).append('\'');
                curPos = endPos + 1;
            }

            if (curPos < literal.length()) {
                buffer.append(literal.substring(curPos));
            }

            buffer.append('\'');
        }
        // handle byte pretty formatting
        else if (object instanceof Byte) {
            IDUtil.appendFormattedByte(buffer, ((Byte) object).byteValue());
        } else if (object instanceof Number) {
            // process numeric value (do something smart in the future)
            buffer.append(object);
        } else if (object instanceof java.sql.Date) {
            buffer.append('\'').append(object).append('\'');
        } else if (object instanceof java.sql.Time) {
            buffer.append('\'').append(object).append('\'');
        } else if (object instanceof java.util.Date) {
            long time = ((java.util.Date) object).getTime();
            buffer.append('\'').append(new java.sql.Timestamp(time)).append('\'');
        } else if (object instanceof java.util.Calendar) {
            long time = ((java.util.Calendar) object).getTimeInMillis();
            buffer.append(object.getClass().getName()).append('(').append(new java.sql.Timestamp(time)).append(')');
        } else if (object instanceof Character) {
            buffer.append(((Character) object).charValue());
        } else if (object instanceof Boolean) {
            buffer.append('\'').append(object).append('\'');
        } else if (object instanceof Enum<?>) {
            // buffer.append(object.getClass().getName()).append(".");
            buffer.append(((Enum<?>) object).name()).append("=");
            if (object instanceof ExtendedEnumeration) {
                Object value = ((ExtendedEnumeration) object).getDatabaseValue();
                if (value instanceof String) {
                    buffer.append("'");
                }
                buffer.append(value);
                if (value instanceof String) {
                    buffer.append("'");
                }
            } else {
                buffer.append(((Enum<?>) object).ordinal());
                // FIXME -- this isn't quite right
            }
        } else if (object instanceof ParameterBinding) {
            sqlLiteralForObject(buffer, ((ParameterBinding) object).getValue());
        } else if (object.getClass().isArray()) {
            buffer.append("< ");

            int len = Array.getLength(object);
            boolean trimming = false;
            if (len > TRIM_VALUES_THRESHOLD) {
                len = TRIM_VALUES_THRESHOLD;
                trimming = true;
            }

            for (int i = 0; i < len; i++) {
                if (i > 0) {
                    buffer.append(",");
                }
                sqlLiteralForObject(buffer, Array.get(object, i));
            }

            if (trimming) {
                buffer.append("...");
            }

            buffer.append('>');
        } else {
            buffer.append(object.getClass().getName()).append("@").append(System.identityHashCode(object));
        }
    }

    @Override
    public void log(String message) {
        if (message != null) {
            logger.info(message);
        }
    }

    @Override
    public void logConnect(String dataSource) {
        if (isLoggable()) {
            logger.info("Connecting. JNDI path: "
                    + dataSource);
        }
    }

    @Override
    public void logConnect(String url, String userName, String password) {
        if (isLoggable()) {
            StringBuilder buf = new StringBuilder("Opening connection: ");

            // append URL on the same line to make log somewhat grep-friendly
            buf.append(url);
            buf.append("\n\tLogin: ").append(userName);
            buf.append("\n\tPassword: *******");

            logger.info(buf.toString());
        }
    }

    @Override
    public void logPoolCreated(DataSourceInfo dsi) {
        if (isLoggable()) {
            StringBuilder buf = new StringBuilder("Created connection pool: ");

            if (dsi != null) {
                // append URL on the same line to make log somewhat grep-friendly
                buf.append(dsi.getDataSourceUrl());

                if (dsi.getAdapterClassName() != null) {
                    buf.append("\n\tCayenne DbAdapter: ").append(dsi.getAdapterClassName());
                }

                buf.append("\n\tDriver class: ").append(dsi.getJdbcDriver());

                if (dsi.getMinConnections() >= 0) {
                    buf.append("\n\tMin. connections in the pool: ").append(dsi.getMinConnections());
                }
                if (dsi.getMaxConnections() >= 0) {
                    buf.append("\n\tMax. connections in the pool: ").append(dsi.getMaxConnections());
                }
            } else {
                buf.append(" pool information unavailable");
            }

            logger.info(buf.toString());
        }
    }

    @Override
    public void logConnectSuccess() {
        logger.info("+++ Connecting: SUCCESS.");
    }

    @Override
    public void logConnectFailure(Throwable th) {
        logger.info("*** Connecting: FAILURE.", th);
    }

    @Override
    public void logGeneratedKey(DbAttribute attribute, Object value) {
        if (isLoggable()) {
            String entity = attribute.getEntity().getName();
            String key = attribute.getName();

            logger.info("Generated PK: "
                    + entity + "." + key + " = " + value);
        }
    }

    public void logQuery(String queryStr, List<?> params) {
        logQuery(queryStr, null, params, -1);
    }

    private void buildLog(StringBuilder buffer,
                          String prefix,
                          String postfix,
                          List<DbAttribute> attributes,
                          List<?> parameters,
                          boolean isInserting) {
        if (parameters != null
                && parameters.size() > 0) {
            DbAttribute attribute = null;
            Iterator<DbAttribute> attributeIterator = null;
            int position = 0;

            if (attributes != null) {
                attributeIterator = attributes.iterator();
            }

            for (Object parameter : parameters) {
                // If at the beginning, output the prefix, otherwise a separator.
                if (position++ == 0) {
                    buffer.append(prefix);
                } else {
                    buffer.append(", ");
                }

                // Find the next attribute and SKIP generated attributes. Only
                // skip when logging inserts, though. Should show previously
                // generated keys on DELETE, UPDATE, or SELECT.
                while (attributeIterator != null
                        && attributeIterator.hasNext()) {
                    attribute = attributeIterator.next();

                    if (isInserting == false
                            || attribute.isGenerated() == false) {
                        break;
                    }
                }

                buffer.append(position);

                if (attribute != null) {
                    buffer.append("->");
                    buffer.append(attribute.getName());
                }

                buffer.append(":");
                sqlLiteralForObject(buffer, parameter);
            }

            buffer.append(postfix);
        }
    }

    private boolean isInserting(String query) {
        if (query == null
                || query.length() == 0) {
            return false;
        }

        char firstCharacter = query.charAt(0);

        if (firstCharacter == 'I'
                || firstCharacter == 'i') {
            return true;
        } else {
            return false;
        }
    }

    public void logQuery(String queryStr, List<DbAttribute> attrs, List<?> params, long time) {
        if (isLoggable()) {
            StringBuilder buffer = new StringBuilder(queryStr);
            buildLog(buffer, " [bind: ", "]", attrs, params, isInserting(queryStr));

            // log preparation time only if it is something significant
            if (time > 5) {
                buffer.append(" - prepared in ").append(time).append(" ms.");
            }

            logger.info(buffer.toString());
        }
    }

    public void logQueryParameters(String label, List<DbAttribute> attrs, List<Object> parameters, boolean isInserting) {
        String prefix = "["
                + label + ": ";
        if (isLoggable()
                && parameters.size() > 0) {
            StringBuilder buffer = new StringBuilder();
            buildLog(buffer, prefix, "]", attrs, parameters, isInserting);
            logger.info(buffer.toString());
        }
    }

    @Override
    public void logSelectCount(int count, long time) {
        if (isLoggable()) {
            StringBuilder buf = new StringBuilder();

            if (count == 1) {
                buf.append("=== returned 1 row.");
            } else {
                buf.append("=== returned ").append(count).append(" rows.");
            }

            if (time >= 0) {
                buf.append(" - took ").append(time).append(" ms.");
            }

            logger.info(buf.toString());
        }
    }

    @Override
    public void logUpdateCount(int count) {
        if (isLoggable()) {
            if (count < 0) {
                logger.info("=== updated ? rows");
            } else {
                String countStr = count == 1 ? "=== updated 1 row." : "=== updated "
                        + count + " rows.";
                logger.info(countStr);
            }
        }
    }

    @Override
    public void logBeginTransaction(String transactionLabel) {
        logger.info("--- "
                + transactionLabel);
    }

    @Override
    public void logCommitTransaction(String transactionLabel) {
        logger.info("+++ "
                + transactionLabel);
    }

    @Override
    public void logRollbackTransaction(String transactionLabel) {
        logger.info("*** "
                + transactionLabel);
    }

    @Override
    public void logQueryError(Throwable th) {
        if (isLoggable()) {
            if (th != null) {
                th = Util.unwindException(th);
            }

            logger.info("*** error.", th);

            if (th instanceof SQLException) {
                SQLException sqlException = ((SQLException) th).getNextException();
                while (sqlException != null) {
                    logger.info("*** nested SQL error.", sqlException);
                    sqlException = sqlException.getNextException();
                }
            }
        }
    }

    @Override
    public boolean isLoggable() {
        return logger.isInfoEnabled();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Lab. Nat. Hist. Iowa State Univ. 4: 70 (1896)

#### Original name
Nectria chaetostroma Ellis & T. Macbr.

### Remarks
null


text:
    <form name="publicForm" class="panel">

				<button ng-show="!viewMode" type="button" ng-click="saveDiagram()" class="btn btn-w-md btn-gap-v btn-success">Save</button>
				<button ng-click="openDiagram(false)" type="button" class="btn btn-w-md btn-gap-v btn-primary">Close</button>
				<button ng-click="onDebugDiagram()" type="button" class="btn btn-w-xs btn-gap-v btn-dark" style="min-width: 35px"></button>

							Name
							<input ng-disabled="viewMode" type="text" name="name" required class="form-control"  placeholder="Name" ng-model="public.name">

							Time zone

							<input ng-disabled="viewMode" required name="timezone" typeahead-editable="false" typeahead-focus-on-select="true" typeahead-select-on-exact="true" typeahead-on-select="onSelectTimeZone" type="text" class="form-control"  placeholder="Time zone" ng-model="public.fs_timezone"  typeahead="zone as zone.name for zone in timeZones | filter:{name:$viewValue}" >

                            Debug
                            <input ng-disabled="viewMode" type="checkbox" ng-model="public.debug">

							Disabled
							<input ng-disabled="viewMode" type="checkbox" ng-model="public.disabled">

						Number
						<tags-input type="text" class="form-group ui-tags-input" required ng-model="public.destination_number">
						</tags-input>

							<tabset>
								<tab>
									<tab-heading>
										Callflow
									</tab-heading>

								</tab>

								<tab>
									<tab-heading>
										On disconnect
									</tab-heading>

								</tab>
							</tabset>

            <button ng-show="isEdit && !viewMode" type="button" ng-disabled="publicForm.$invalid" ng-click="save()" class="btn btn-w-md btn-gap-v btn-success">Save</button>
            <button ng-show="isEdit && !isNew && !viewMode"  ng-click="cancel()" type="button" class="btn btn-w-md btn-gap-v btn-primary">Cancel</button>
			<button  type="button" ng-click="closePage()" class="btn btn-w-md btn-gap-v btn-default">Close</button>

    </form>


text:
import pytest

from cihai import exc, utils
from unihan_etl.util import merge_dict

def test_merge_dict():
    dict1 = {"hi world": 1, "innerdict": {"hey": 1}}
    dict2 = {"innerdict": {"welcome": 2}}

    expected = {"hi world": 1, "innerdict": {"hey": 1, "welcome": 2}}

    assert merge_dict(dict1, dict2) == expected

def test_import_string():
    utils.import_string("cihai")

    with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
        utils.import_string("cihai.core.nonexistingimport")

    with pytest.raises((ImportError, exc.CihaiException, exc.ImportStringError)):
        utils.import_string("cihai2")


text:
class InfosController < ApplicationController
  before_action :require_sign_in
  before_action :set_event
  before_action :set_info, only: [:edit, :update]

  def create
    info = Info.new(info_params)
    info.event = @event
    authorize! :update, @event

    if info.save
      redirect_to company_event_path(@event.company, @event), notice: "Information added to #{@event.name}."
    else
      handle @event
      render 'events/show', alert: "Something went wrong."
    end
  end

  def edit
    authorize! :update, @event
    respond_to do |format|
      format.html { redirect_to root_path, alert: "Not supported."}
      format.js {  }
    end
  end

  def update
    authorize! :update, @event
    if @info.update(info_params)
      respond_to do |format|
        format.html { redirect_to root_path, alert: "Not supported."}
        format.js {  }
      end
    else
      redirect_to root_path, alert: "Something went wrong."
    end
  end

  private

  def set_event
    @event = Event.find params[:event_id]
  end

  def set_info
    @info = Info.find params[:id]
  end

  def info_params
    params.require(:info).permit(
        :linen_colors, :napkin_colors, :napkin_fold, :placesetting, :centerpieces,
        :water_service, :coffee_service, :final_guest_count, :number_of_tables,
        :guests_per_table
      )
  end
end


text:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public IList<IList<int>> ZigzagLevelOrder(TreeNode root) {
        IList<IList<int>> res=new List<IList<int>>();
        if(root==null) return res;
        Stack<TreeNode> stack=new Stack<TreeNode>();
        stack.Push(root);
        bool zig=true;
        while(stack.Count!=0)
        {
            IList<int> item=new List<int>();
            stack=Travel(stack,zig,item);
            res.Add(item);
            zig=!zig;
        }
        return res;
    }
    private Stack<TreeNode> Travel(Stack<TreeNode> root,bool direction,IList<int> item)
    {
        Stack<TreeNode> stack=new Stack<TreeNode>();
        while(root.Count!=0)
        {
            var node=root.Peek();
            item.Add(node.val);
            if(direction)
            {
                if(node.left!=null)
                    stack.Push(node.left);
                if(node.right!=null)
                    stack.Push(node.right);
            }
            else
            {
                if(node.right!=null)
                    stack.Push(node.right);
                if(node.left!=null)
                    stack.Push(node.left);
            }
            root.Pop();
        }
        return stack;
    }
}


text:
module ClientGenerator
  VERSION = "0.1.0"
end


text:
<?php
include 'dbconfig.php';
$suppid = $_GET['id'];
//$customerid = 1;
?>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Supplier Purchases- Ambaji Optics</title>

        <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">

        <link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.5.0/css/font-awesome.min.css">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/css/ionicons.min.css">

        <link rel="stylesheet" href="dist/css/AdminLTE.min.css">

        <link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">

                    ALT

                    AmbajiOptics

                                Dashboard

                                Logout

                                CUSTOMER

                                        New Customer

                                    Search Customers

                                    Search Orders

                                SUPPLIER

                                     New Product

                                     Search Products

                                     New Supplier

                                     Search Suppliers

                                     Supplier Purchase

                                     View Inventory

                                REPORTS

                                     Supplier's Outstanding

                                     Balance Customers

                        Search Supplier Purchase

                    <form role="form" action="<?= $_SERVER['PHP_SELF']; ?>" method="post" id="main" autocomplete="off">

Search

                                            <input type="text" class="form-control" name="suppname" placeholder="Type Supplier name here">

                                                <button type="submit" name="submit" class="btn btn-primary">Show all Purchases for the Supplier</button>
                                                </form>

Search results..

                                                        Supplier Name
                                                        Product Type
                                                        Product Model
                                                        Product Brand
                                                        Product Detail
                                                        Purchase Date
                                                        Quantity
                                                        Total
                                                        Advance
                                                        Outstanding
                                                        Action

                                                    <?php
                                                    //form is empty show all customers code
                                                    //check if submit button is pressed
                                                    $sql = "SELECT supplier_master.Supplier_Name, product_master.Product_Type, product_master.Product_Model, product_master.Product_Brand, product_master.Product_Detail,supplier_purchase_detail.Purchase_ID, supplier_purchase_detail.DOP, supplier_purchase_detail.Qty, supplier_purchase_detail.Total, supplier_purchase_detail.Advance, supplier_purchase_detail.Balance
FROM supplier_purchase_detail
JOIN supplier_master
ON supplier_master.Supplier_ID = supplier_purchase_detail.Supplier_ID
JOIN product_master
ON product_master.Product_ID = supplier_purchase_detail.Product_ID
order by supplier_purchase_detail.Purchase_ID desc limit 10 ";
                                                    if ((!empty($_POST['suppname']))) {
                                                        //Show filtered list when form fields are filled in
                                                        $suppname = $_POST['suppname'];

                                                        //To protect MySQL injection for Security purpose
                                                        $suppname = stripslashes($suppname);

                                                        //$sql="SELECT * FROM customer WHERE Customer_Name LIKE '%" . $customername . "%' OR Customer_Mobile_No LIKE '%" . $mobileno  ."%'";
                                                        //$sql="SELECT * FROM customer WHERE Customer_Name Like '%".$customername."%'";
                                                        //$sql="SELECT * FROM order WHERE Customer_Name LIKE '%" . $customername . "%' AND Customer_Mobile_No LIKE '%" . $mobileno  ."%'";
                                                        $sql = "SELECT supplier_master.Supplier_Name, product_master.Product_Type, product_master.Product_Model, product_master.Product_Brand, product_master.Product_Detail, supplier_purchase_detail.Purchase_ID, supplier_purchase_detail.DOP, supplier_purchase_detail.Qty, supplier_purchase_detail.Total, supplier_purchase_detail.Advance, supplier_purchase_detail.Balance
FROM supplier_purchase_detail
JOIN supplier_master
ON supplier_master.Supplier_ID = supplier_purchase_detail.Supplier_ID
JOIN product_master
ON product_master.Product_ID = supplier_purchase_detail.Product_ID
WHERE supplier_master.Supplier_Name like '%" . $suppname . "%'";
                                                    } else {
                                                        if ((!empty($_GET['id']))) {
                                                            $sql = "SELECT supplier_master.Supplier_Name, product_master.Product_Type, product_master.Product_Model, product_master.Product_Brand, product_master.Product_Detail, supplier_purchase_detail.* FROM supplier_purchase_detail
JOIN supplier_master
ON supplier_master.Supplier_ID = supplier_purchase_detail.Supplier_ID
JOIN product_master
ON product_master.Product_ID = supplier_purchase_detail.Product_ID
WHERE supplier_purchase_detail.Purchase_ID = '$suppid'";
                                                        }
                                                    }

                                                    $result = '';
                                                    $result = mysql_query($sql, $conn);
                                                    while ($row = mysql_fetch_array($result)) {
                                                        $suppname = $row['Supplier_Name'];
                                                        $type = $row['Product_Type'];
                                                        $model = $row['Product_Model'];
                                                        $brand = $row['Product_Brand'];
                                                        $detail = $row['Product_Detail'];
                                                        $dop = $row['DOP'];
                                                        $dopphp = date("d-m-Y", strtotime($dop));
                                                        $qty = $row['Qty'];
                                                        $total = $row['Total'];
                                                        $advance = $row['Advance'];
                                                        $balance = $row['Balance'];
                                                        $purchaseid = $row['Purchase_ID'];

                                                        // $suppid = $row['Supplier_ID'];
                                                        //  $purchaseid = $row['Purchase_ID'];

                                                        echo "
";
                                                        //echo ("" . '' . $row['Customer_ID'] . ''. "	");
                                                        echo "" . $row['Supplier_Name'] . "	";
                                                        //echo ("" . '' . $row['Purchase_ID'] . '' . "	");
                                                        //echo "" . $row['Customer_Name'] . "	";
                                                        //echo "" . $suppid . "	";
                                                        echo "" . $type . "	";
                                                        echo "" . $model . "	";
                                                        echo "" . $brand . "	";
                                                        echo "" . $detail . "	";
                                                        echo "" . $dopphp . "	";
                                                        echo "" . $qty . "	";
                                                        echo "" . $total . "	";
                                                        echo "" . $advance . "	";
                                                        echo "" . $balance . "	";
                                                        ?>

                                                                <?php
                                                                echo ('' . "Cancel Purchase" . '');
                                                                ?>

                                                    <?php
                                                    //echo "" . $row['nooforders'] . "	";
                                                    echo "
";
                                                }
                                                ?>

                                                        Supplier Name
                                                        Product Type
                                                        Product Model
                                                        Product Brand
                                                        Product Detail
                                                        Purchase Date
                                                        Quantity
                                                        Total
                                                        Advance
                                                        Outstanding
                                                        Action


text:
from __future__ import unicode_literals
from ..confounds import FramewiseDisplacement

def test_FramewiseDisplacement_inputs():
    input_map = dict(figdpi=dict(usedefault=True,
    ),
    figsize=dict(usedefault=True,
    ),
    ignore_exception=dict(nohash=True,
    usedefault=True,
    ),
    in_file=dict(mandatory=True,
    ),
    normalize=dict(usedefault=True,
    ),
    out_figure=dict(usedefault=True,
    ),
    out_file=dict(usedefault=True,
    ),
    parameter_source=dict(mandatory=True,
    ),
    radius=dict(usedefault=True,
    ),
    save_plot=dict(usedefault=True,
    ),
    series_tr=dict(),
    )
    inputs = FramewiseDisplacement.input_spec()

    for key, metadata in list(input_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(inputs.traits()[key], metakey) == value

def test_FramewiseDisplacement_outputs():
    output_map = dict(fd_average=dict(),
    out_figure=dict(),
    out_file=dict(),
    )
    outputs = FramewiseDisplacement.output_spec()

    for key, metadata in list(output_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(outputs.traits()[key], metakey) == value


text:
package org.nd4j.linalg.api.iter;

import org.nd4j.linalg.api.shape.Shape;
import org.nd4j.linalg.util.ArrayUtil;

import java.io.Serializable;

/**
 * Represents a cache linear index lookup
 * @author Adam Gibson
 */
public class LinearIndexLookup implements Serializable {
    private char ordering;
    private long[][] indexes;
    private long[] shape;
    private boolean[] exists;
    private long numIndexes;

    /**
     *
     * @param shape the shape of the linear index
     * @param ordering the ordering of the linear index
     */
    public LinearIndexLookup(int[] shape, char ordering) {
        this(ArrayUtil.toLongArray(shape), ordering);
    }

    public LinearIndexLookup(long[] shape, char ordering) {
        this.shape = shape;
        this.ordering = ordering;
        numIndexes = ArrayUtil.prodLong(shape);

        // FIMXE: long!
        indexes = new long[(int) numIndexes][shape.length];
        exists = new boolean[(int) numIndexes];
    }

    /**
     * Give back a sub
     * wrt the given linear index
     * @param index the index
     * @return the sub for the given index
     */
    public long[] lookup(int index) {
        if (exists[index]) {
            return indexes[index];
        } else {
            exists[index] = true;
            indexes[index] = ordering == 'c' ? Shape.ind2subC(shape, index, numIndexes)
                            : Shape.ind2sub(shape, index, numIndexes);
            return indexes[index];
        }
    }

}


text:
describe LinksController do
  describe 'GET index' do
    let(:manager) { create :manager }

    context 'with authentication' do
      context 'when tag param specified' do
        before do
          sign_in(manager)
        end

        it 'renders index template' do
          get :index, params: { tag: 'test' }

          expect(response).to render_template(:index)
          expect(response.status).to eq 200
        end
      end
    end

    context 'without authentication' do
      context 'when tag param specified' do
        let!(:first_link) { create(:link, tag_list: %w[tag first_tag]) }
        let!(:second_link) { create(:link, tag_list: %w[tag second_tag]) }
        let!(:issue) { create :issue }

        before do
          Link.without_issue.update_all(issue_id: issue.id)
          issue.update(sent_at: Time.zone.now)
        end

        it 'renders index template' do
          get :index, params: { tag: 'test' }

          expect(assigns(:links)).not_to be_nil

          expect(response).to render_template(:index)
          expect(response.status).to eq 200
        end
      end

      context 'when tag param is not specified' do
        it 'renders index template' do
          get :index, params: { tag: 'test' }

          expect(assigns(:links)).not_to be_nil

          expect(response).to render_template(:index)
          expect(response.status).to eq 200
        end
      end
    end
  end
end


text:
package net.sf.jabref.gui.groups;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import net.sf.jabref.model.entry.BibEntry;

class TransferableEntrySelection implements Transferable {

    public static final DataFlavor FLAVOR_INTERNAL;
    private static final DataFlavor FLAVOR_EXTERNAL;
    private static final DataFlavor[] FLAVORS;
    private final List<BibEntry> selectedEntries;
    private final String selectedEntriesCiteKeys;

    private boolean includeCiteKeyword;

    static {
        DataFlavor df1 = null;
        DataFlavor df2 = null;
        try {
            df1 = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType
                    + ";class=net.sf.jabref.gui.groups.TransferableEntrySelection");
            df2 = DataFlavor.getTextPlainUnicodeFlavor();
        } catch (ClassNotFoundException e) {
            // never happens
        }
        FLAVOR_INTERNAL = df1;
        FLAVOR_EXTERNAL = df2;
        FLAVORS = new DataFlavor[] {TransferableEntrySelection.FLAVOR_INTERNAL, TransferableEntrySelection.FLAVOR_EXTERNAL};
    }

    public TransferableEntrySelection(List<BibEntry> list) {
        this.selectedEntries = list;
        selectedEntriesCiteKeys = String.join(",",
                this.selectedEntries.stream().map(BibEntry::getCiteKeyOptional).filter(Optional::isPresent)
                        .map(Optional::get).collect(Collectors.toList()));
    }

    @Override
    public DataFlavor[] getTransferDataFlavors() {
        return TransferableEntrySelection.FLAVORS;
    }

    @Override
    public boolean isDataFlavorSupported(DataFlavor someFlavor) {
        return someFlavor.equals(TransferableEntrySelection.FLAVOR_INTERNAL)
                || someFlavor.equals(TransferableEntrySelection.FLAVOR_EXTERNAL);
    }

    @Override
    public Object getTransferData(DataFlavor someFlavor)
            throws UnsupportedFlavorException, IOException {
        if (!isDataFlavorSupported(someFlavor)) {
            throw new UnsupportedFlavorException(someFlavor);
        }
        if (someFlavor.equals(TransferableEntrySelection.FLAVOR_INTERNAL)) {
            return this;
        }
        String s = includeCiteKeyword ?
                "\\cite{" + selectedEntriesCiteKeys + "}"
                : selectedEntriesCiteKeys;
        String charset = TransferableEntrySelection.FLAVOR_EXTERNAL.getParameter("charset");
        if (charset == null) {
            charset = "";
        }
        return new ByteArrayInputStream(s.getBytes(charset.trim()));
    }

    public List<BibEntry> getSelection() {
        return selectedEntries;
    }

    public void setIncludeCiteKeyword(boolean includeCiteKeyword) {
        this.includeCiteKeyword = includeCiteKeyword;
    }

}


text:
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

DROP PROCEDURE IF EXISTS `sp_GetPlayerFromSession`;

DELIMITER //
CREATE PROCEDURE `sp_GetPlayerFromSession`(IN player_id BIGINT(20))
BEGIN
    SELECT session_key from player where id = player_id;
END//
DELIMITER ;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;


text:
var GeoCoding = (function () {
    var _ = require('lib/underscore');
    _.mixin(require('lib/underscore.deferred'));

    var url = 'http://maps.googleapis.com/maps/api/geocode/json',
        defaultParams = {
            sensor: true,
            language: 'vi'
        };

    function geocode(_args) {
        var deferred = new _.Deferred(),
            params = _.defaults(_args, defaultParams),
            xhr = Ti.Network.createHTTPClient({
                onload: function () {
                    var json = JSON.parse(this.responseText);
                    if (json.status == 'OK') {
                        deferred.resolve(json.results);
                    } else {
                        deferred.reject(json);
                    }
                },
                onerror: function (e) {
                    deferred.reject(e.error);
                },
                timeout: 5000
            });
        xhr.open('GET', url);
        xhr.send(params);

        return deferred;
    }

    return {
        geocode: geocode
    };
})();

module.exports = GeoCoding;


text:
__author__ = 'pablolmedorado'

from unittest import TestCase
from src.Circuito import Circuito

class TestCircuito(TestCase):
    def test_str(self):
        """
        Prueba del metodo ToString

        Dados unos datos, comprueba que se crea correctamente el objeto Circuito y que muestra bien los datos

        :return: Resultado de la prueba
        :rtype: Boolean
        """
        circ = Circuito("CircuitoDePrueba", "UbDePrueba", 12345, 99)
        string = "Datos del circuito: \nNombre del circuito: " + "CircuitoDePrueba"
        string += "\nUbicacion: " + "UbDePrueba"
        string += "\nLongitud: " + "12345" + "km"
        string += "\nNumero de Vueltas: " + "99" + "\n"
        self.assertEqual(string, str(circ))