<commit_before>var rangeDef = [
  {
    "enum": [
      "width",
      "height",
      "shapes",
      "category",
      "ordinal",
      "ramp",
      "diverging",
      "heatmap"
    ]
  },
  {
    "type": "array",
    "items": {
      "oneOf": [
        {"type": "string"},
        {"type": "number"},
        {"$ref": "#/refs/signal"}
      ]
    }
  },
  {"$ref": "#/refs/signal"}
];

var schemeRangeDef = rangeDef.concat([
  {
    "type": "object",
    "properties": {
      "scheme": {"$ref": "#/refs/stringOrSignal"},
      "count": {"$ref": "#/refs/numberOrSignal"},
      "extent": {
        "oneOf": [
          {
            "type": "array",
            "items": {"$ref": "#/refs/numberOrSignal"},
            "numItems": 2
          },
          {"$ref": "#/refs/signal"}
        ]
      }
    },
    "required": ["scheme"],
    "additionalProperties": false
  }
]);

var bandRangeDef = rangeDef.concat([
  {
    "type": "object",
    "properties": {
      "step": {"$ref": "#/refs/numberOrSignal"}
    },
    "required": ["step"],
    "additionalProperties": false
  }
]);

export default {
  "refs": {
    "sortOrder": {
      "oneOf": [
        {"enum": ["ascending", "descending"]},
        {"$ref": "#/refs/signal", "additionalProperties": false}
      ]
    },
    "scaleField": {"$ref": "#/refs/stringOrSignal"},
    "scaleData": {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "data": {"type": "string"},
            "field": {"$ref": "#/refs/scaleField"},
            "sort": {
              "oneOf": [
                {"type": "boolean"},
                {
                  "type": "object",
                  "properties": {
                    "field": {"$ref": "#/refs/scaleField"},
                    "op": {"$ref": "#/refs/scaleField"},
                    "order": {"$ref": "#/refs/sortOrder"}
                  },
                  "additionalProperties": false,
                }
              ]
            }
          },
          "required": ["data", "field"],
          "additionalProperties": false
        },
        {
          "type": "object",
          "properties": {
            "data": {"type": "string"},
            "fields": {
              "type": "array",
              "items": {
                "oneOf": [
                  {
                    "type": "object",
                    "properties": {
                      "data": {"type": "string"},
                      "field": {"$ref": "#/refs/scaleField"},
                    },
                    "required": ["field"],
                    "additionalProperties": false
                  },
                  {"$ref": "#/refs/scaleField"}
                ]
              },
              "minItems": 1
            },
            "sort": {
              "oneOf": [
                {"type": "boolean"},
                {
                  "type": "object",
                  "properties": {
                    "op": {"enum": ["count"]}
                  },
                  "additionalProperties": false,
                }
              ]
            }
          },
          "required": ["data", "fields"],
          "additionalProperties": false
        },
        {
          "type": "object",
          "properties": {
            "fields": {
              "type": "array",
              "items": {
                "oneOf": [
                  {
                    "type": "object",
                    "properties": {
                      "data": {"type": "string"},
                      "field": {"$ref": "#/refs/scaleField"},
                    },
                    "required": ["data", "field"],
                    "additionalProperties": false
                  },
                  {"$ref": "#/refs/scaleField"}
                ]
              },
              "minItems": 1
            },
            "sort": {
              "oneOf": [
                {"type": "boolean"},
                {
                  "type": "object",
                  "properties": {
                    "op": {"enum": ["count"]}
                  },
                  "additionalProperties": false,
                }
              ]
            }
          },
          "required": ["fields"],
          "additionalProperties": false
        }
      ]
    }
  },

  "defs": {
    "scale": {
      "title": "Scale mapping",
      "type": "object",

      "allOf": [
        {
          "properties": {
            "name": {"type": "string"},
            "type": {"type": "string", "default": "linear"},
            "domain": {
              "oneOf": [
                {
                  "type": "array",
                  "items": {
                    "oneOf": [
                      {"type": "string"},
                      {"type": "number"},
                      {"type": "boolean"},
                      {"$ref": "#/refs/signal"}
                    ]
                  }
                },
                {"$ref": "#/refs/scaleData"},
                {"$ref": "#/refs/signal"}
              ]
            },
            "domainMin": {"$ref": "#/refs/numberOrSignal"},
            "domainMax": {"$ref": "#/refs/numberOrSignal"},
            "domainMid": {"$ref": "#/refs/numberOrSignal"},
            "domainRaw": {
              "oneOf": [
                {"type": "null"},
                {"type": "array"},
                {"$ref": "#/refs/signal"}
              ]
            },
            "reverse": {"$ref": "#/refs/booleanOrSignal"},
            "round": {"$ref": "#/refs/booleanOrSignal"}
          },
          "required": ["name"]
        },
        {
          "oneOf": [
            {
              "properties": {
                "type": {"enum": ["ordinal"]},
                "range": {
                  "oneOf": schemeRangeDef.concat({"$ref": "#/refs/scaleData"})
                }
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["band"]},
                "range": {"oneOf": bandRangeDef},
                "padding": {"$ref": "#/refs/numberOrSignal"},
                "paddingInner": {"$ref": "#/refs/numberOrSignal"},
                "paddingOuter": {"$ref": "#/refs/numberOrSignal"},
                "align": {"$ref": "#/refs/numberOrSignal"}
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["point"]},
                "range": {"oneOf": bandRangeDef},
                "padding": {"$ref": "#/refs/numberOrSignal"},
                "paddingOuter": {"$ref": "#/refs/numberOrSignal"},
                "align": {"$ref": "#/refs/numberOrSignal"}
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["sequential"]},
                "range": {"oneOf": schemeRangeDef},
                "clamp": {"$ref": "#/refs/booleanOrSignal"}
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["time", "utc"]},
                "range": {"oneOf": schemeRangeDef},
                "clamp": {"$ref": "#/refs/booleanOrSignal"},
                "nice": {
                  "oneOf": [
                    {"type": "boolean"},
                    {"enum": ["second", "minute", "hour", "day", "week", "month", "year"]},
                    {"$ref": "#/refs/signal"}
                  ]
                }
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["identity"]},
                "nice": {"$ref": "#/refs/booleanOrSignal"}
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["quantile", "quantize", "threshold"]},
                "range": {"oneOf": schemeRangeDef}
              },
              "required": ["type"]
            },
            {
              "description": "Default numeric scale",
              "not": {
                "properties": {
                  "type": {
                    "enum": [
                      "ordinal", "index", "band", "point",
                      "quantile", "quantize", "threshold",
                      "sequential", "pow", "time", "utc",
                      "identity"
                    ]
                  }
                },
                "required": ["type"]
              },
              "properties": {
                "range": {"oneOf": schemeRangeDef},
                "interpolate": {
                  "oneOf": [
                    {"type": "string"},
                    {"$ref": "#/refs/signal"},
                    {
                      "type": "object",
                      "properties": {
                        "type": {"$ref": "#/refs/stringOrSignal"},
                        "gamma": {"$ref": "#/refs/numberOrSignal"}
                      },
                      "required": ["type"]
                    }
                  ]
                },
                "clamp": {"$ref": "#/refs/booleanOrSignal"},
                "nice": {
                  "oneOf": [
                    {"type": "boolean"},
                    {"type": "number"},
                    {"$ref": "#/refs/signal"}
                  ]
                },
                "zero": {"$ref": "#/refs/booleanOrSignal"}
              }
            },
            {
              "properties": {
                "type": {"enum": ["pow"]},
                "range": {"oneOf": schemeRangeDef},
                "clamp": {"$ref": "#/refs/booleanOrSignal"},
                "exponent": {"$ref": "#/refs/numberOrSignal"},
                "nice": {
                  "oneOf": [
                    {"type": "boolean"},
                    {"type": "number"},
                    {"$ref": "#/refs/signal"}
                  ]
                },
                "zero": {"$ref": "#/refs/booleanOrSignal"}
              },
              "required": ["type"]
            }
          ]
        }
      ]
    }
  }
};
<commit_msg>Fix shapes/symbol bug in schema.<commit_after>var rangeDef = [
  {
    "enum": [
      "width",
      "height",
      "symbol",
      "category",
      "ordinal",
      "ramp",
      "diverging",
      "heatmap"
    ]
  },
  {
    "type": "array",
    "items": {
      "oneOf": [
        {"type": "string"},
        {"type": "number"},
        {"$ref": "#/refs/signal"}
      ]
    }
  },
  {"$ref": "#/refs/signal"}
];

var schemeRangeDef = rangeDef.concat([
  {
    "type": "object",
    "properties": {
      "scheme": {"$ref": "#/refs/stringOrSignal"},
      "count": {"$ref": "#/refs/numberOrSignal"},
      "extent": {
        "oneOf": [
          {
            "type": "array",
            "items": {"$ref": "#/refs/numberOrSignal"},
            "numItems": 2
          },
          {"$ref": "#/refs/signal"}
        ]
      }
    },
    "required": ["scheme"],
    "additionalProperties": false
  }
]);

var bandRangeDef = rangeDef.concat([
  {
    "type": "object",
    "properties": {
      "step": {"$ref": "#/refs/numberOrSignal"}
    },
    "required": ["step"],
    "additionalProperties": false
  }
]);

export default {
  "refs": {
    "sortOrder": {
      "oneOf": [
        {"enum": ["ascending", "descending"]},
        {"$ref": "#/refs/signal", "additionalProperties": false}
      ]
    },
    "scaleField": {"$ref": "#/refs/stringOrSignal"},
    "scaleData": {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "data": {"type": "string"},
            "field": {"$ref": "#/refs/scaleField"},
            "sort": {
              "oneOf": [
                {"type": "boolean"},
                {
                  "type": "object",
                  "properties": {
                    "field": {"$ref": "#/refs/scaleField"},
                    "op": {"$ref": "#/refs/scaleField"},
                    "order": {"$ref": "#/refs/sortOrder"}
                  },
                  "additionalProperties": false,
                }
              ]
            }
          },
          "required": ["data", "field"],
          "additionalProperties": false
        },
        {
          "type": "object",
          "properties": {
            "data": {"type": "string"},
            "fields": {
              "type": "array",
              "items": {
                "oneOf": [
                  {
                    "type": "object",
                    "properties": {
                      "data": {"type": "string"},
                      "field": {"$ref": "#/refs/scaleField"},
                    },
                    "required": ["field"],
                    "additionalProperties": false
                  },
                  {"$ref": "#/refs/scaleField"}
                ]
              },
              "minItems": 1
            },
            "sort": {
              "oneOf": [
                {"type": "boolean"},
                {
                  "type": "object",
                  "properties": {
                    "op": {"enum": ["count"]}
                  },
                  "additionalProperties": false,
                }
              ]
            }
          },
          "required": ["data", "fields"],
          "additionalProperties": false
        },
        {
          "type": "object",
          "properties": {
            "fields": {
              "type": "array",
              "items": {
                "oneOf": [
                  {
                    "type": "object",
                    "properties": {
                      "data": {"type": "string"},
                      "field": {"$ref": "#/refs/scaleField"},
                    },
                    "required": ["data", "field"],
                    "additionalProperties": false
                  },
                  {"$ref": "#/refs/scaleField"}
                ]
              },
              "minItems": 1
            },
            "sort": {
              "oneOf": [
                {"type": "boolean"},
                {
                  "type": "object",
                  "properties": {
                    "op": {"enum": ["count"]}
                  },
                  "additionalProperties": false,
                }
              ]
            }
          },
          "required": ["fields"],
          "additionalProperties": false
        }
      ]
    }
  },

  "defs": {
    "scale": {
      "title": "Scale mapping",
      "type": "object",

      "allOf": [
        {
          "properties": {
            "name": {"type": "string"},
            "type": {"type": "string", "default": "linear"},
            "domain": {
              "oneOf": [
                {
                  "type": "array",
                  "items": {
                    "oneOf": [
                      {"type": "string"},
                      {"type": "number"},
                      {"type": "boolean"},
                      {"$ref": "#/refs/signal"}
                    ]
                  }
                },
                {"$ref": "#/refs/scaleData"},
                {"$ref": "#/refs/signal"}
              ]
            },
            "domainMin": {"$ref": "#/refs/numberOrSignal"},
            "domainMax": {"$ref": "#/refs/numberOrSignal"},
            "domainMid": {"$ref": "#/refs/numberOrSignal"},
            "domainRaw": {
              "oneOf": [
                {"type": "null"},
                {"type": "array"},
                {"$ref": "#/refs/signal"}
              ]
            },
            "reverse": {"$ref": "#/refs/booleanOrSignal"},
            "round": {"$ref": "#/refs/booleanOrSignal"}
          },
          "required": ["name"]
        },
        {
          "oneOf": [
            {
              "properties": {
                "type": {"enum": ["ordinal"]},
                "range": {
                  "oneOf": schemeRangeDef.concat({"$ref": "#/refs/scaleData"})
                }
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["band"]},
                "range": {"oneOf": bandRangeDef},
                "padding": {"$ref": "#/refs/numberOrSignal"},
                "paddingInner": {"$ref": "#/refs/numberOrSignal"},
                "paddingOuter": {"$ref": "#/refs/numberOrSignal"},
                "align": {"$ref": "#/refs/numberOrSignal"}
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["point"]},
                "range": {"oneOf": bandRangeDef},
                "padding": {"$ref": "#/refs/numberOrSignal"},
                "paddingOuter": {"$ref": "#/refs/numberOrSignal"},
                "align": {"$ref": "#/refs/numberOrSignal"}
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["sequential"]},
                "range": {"oneOf": schemeRangeDef},
                "clamp": {"$ref": "#/refs/booleanOrSignal"}
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["time", "utc"]},
                "range": {"oneOf": schemeRangeDef},
                "clamp": {"$ref": "#/refs/booleanOrSignal"},
                "nice": {
                  "oneOf": [
                    {"type": "boolean"},
                    {"enum": ["second", "minute", "hour", "day", "week", "month", "year"]},
                    {"$ref": "#/refs/signal"}
                  ]
                }
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["identity"]},
                "nice": {"$ref": "#/refs/booleanOrSignal"}
              },
              "required": ["type"]
            },
            {
              "properties": {
                "type": {"enum": ["quantile", "quantize", "threshold"]},
                "range": {"oneOf": schemeRangeDef}
              },
              "required": ["type"]
            },
            {
              "description": "Default numeric scale",
              "not": {
                "properties": {
                  "type": {
                    "enum": [
                      "ordinal", "index", "band", "point",
                      "quantile", "quantize", "threshold",
                      "sequential", "pow", "time", "utc",
                      "identity"
                    ]
                  }
                },
                "required": ["type"]
              },
              "properties": {
                "range": {"oneOf": schemeRangeDef},
                "interpolate": {
                  "oneOf": [
                    {"type": "string"},
                    {"$ref": "#/refs/signal"},
                    {
                      "type": "object",
                      "properties": {
                        "type": {"$ref": "#/refs/stringOrSignal"},
                        "gamma": {"$ref": "#/refs/numberOrSignal"}
                      },
                      "required": ["type"]
                    }
                  ]
                },
                "clamp": {"$ref": "#/refs/booleanOrSignal"},
                "nice": {
                  "oneOf": [
                    {"type": "boolean"},
                    {"type": "number"},
                    {"$ref": "#/refs/signal"}
                  ]
                },
                "zero": {"$ref": "#/refs/booleanOrSignal"}
              }
            },
            {
              "properties": {
                "type": {"enum": ["pow"]},
                "range": {"oneOf": schemeRangeDef},
                "clamp": {"$ref": "#/refs/booleanOrSignal"},
                "exponent": {"$ref": "#/refs/numberOrSignal"},
                "nice": {
                  "oneOf": [
                    {"type": "boolean"},
                    {"type": "number"},
                    {"$ref": "#/refs/signal"}
                  ]
                },
                "zero": {"$ref": "#/refs/booleanOrSignal"}
              },
              "required": ["type"]
            }
          ]
        }
      ]
    }
  }
};
<|endoftext|>


<commit_before>import { parser as saxParser } from 'sax';
import Queue from './queue.js';

class XMLPulley {
  constructor(strict, options) {
    this.options = options;
    let queue = this.queue = new Queue();
    let parser = this.parser = saxParser(strict, options);
    let text = null;
    function flushText() {
      if(text) {
        queue.enqueue({type: 'text', data: text});
        text = null;
      }
    }
    parser.onerror = (err) => {
      throw err;
    };
    parser.ontext = parser.oncdata = (t) => {
      text = text ? text + t : t;
    };
    parser.onopentag = (tag) => {
      flushText();
      queue.enqueue({type: 'opentag', data: tag});
    };
    parser.onclosetag = (tag) => {
      flushText();
      queue.enqueue({type: 'closetag', data: tag});
    };
  }
  write(xml) {
    if(this.parser)
      this.parser.write(xml);
    else
      throw new Error("Can't write to a closed XMLPulley!");
    return this;
  }
  close() {
    if(this.parser) {
      this.parser.close();
      this.parser = null;
    }
    return this;
  }
  next() {
    return this.queue.dequeue();
  }
  expect(type) {
    let out = this.next();
    if(out === undefined) {
      throw new Error(`Expected ${type}; got end of file!`);
    } else if(out.type !== type) {
      throw new Error(`Expected ${type}; got ${out.type}!`);
    }
    return out;
  }
}

export default function xmlPulley(strict, options) {
  return new XMLPulley(strict, options);
}
<commit_msg>Added support for processing instructions and stuff<commit_after>import { parser as saxParser } from 'sax';
import Queue from './queue.js';

function isAllowedType(type) {
  switch(type) {
    case 'text': case 'opentag': case 'closetag': case 'doctype':
    case 'processinginstruction': case 'attribute': case 'comment':
    case 'opencdata': case 'closecdata': case 'opennamespace':
    case 'closenamespace': return true;
    default: return false;
  }
}

class XMLPulley {
  constructor(strict, options) {
    this.options = options = options || {};
    let types = options.types || ['opentag', 'closetag', 'text'];
    let queue = this.queue = new Queue();
    let parser = this.parser = saxParser(strict, options);
    let text = null;
    function flushText() {
      if(text) {
        queue.enqueue({type: 'text', data: text});
        text = null;
      }
    }
    parser.onerror = (err) => {
      throw err;
    };
    types.forEach((type) => {
      if(type === 'text') {
        parser.ontext = parser.oncdata = (t) => {
          text = text ? text + t : t;
        };
      } else if(isAllowedType(type)) {
        parser['on'+type] = (data) => {
          flushText();
          queue.enqueue({type: type, data: data});
        }
      } else {
        throw new Error(`${type} isn't an allowed type!`);
      }
    });
  }
  write(xml) {
    if(this.parser)
      this.parser.write(xml);
    else
      throw new Error("Can't write to a closed XMLPulley!");
    return this;
  }
  close() {
    if(this.parser) {
      this.parser.close();
      this.parser = null;
    }
    return this;
  }
  next() {
    return this.queue.dequeue();
  }
  expect(type) {
    let out = this.next();
    if(out === undefined) {
      throw new Error(`Expected ${type}; got end of file!`);
    } else if(out.type !== type) {
      throw new Error(`Expected ${type}; got ${out.type}!`);
    }
    return out;
  }
}

export default function xmlPulley(strict, options) {
  return new XMLPulley(strict, options);
}
<|endoftext|>


<commit_before>let pluginsTable;

$(document).ready(function() {
    $('.box-body').css('min-height', $('.content-wrapper').height() - $('.content-header').outerHeight() - 120);
    pluginsTable = $('#plugin-table').DataTable({
        language: trans('vendor.datatables'),
        responsive: true,
        autoWidth: false,
        processing: true,
        ordering: false,
        serverSide: false,   //未知原因，开了这个会有问题
        ajax: {
            url: '/admin/plugins-market/data',
            dataSrc: ''
        },
        createdRow: function (row, data, index) {},
        columnDefs: [
            {
                targets: 0,
                title: trans('market.market.title'),
                data: 'title'
            },
            {
                targets: 1,
                title: trans('market.market.description'),
                data: 'description',
                width: '40%'
            },
            {
                targets: 2,
                title: trans('market.market.author'),
                data: 'author',
                width: '10%'
            },
            {
                targets: 3,
                title: trans('market.market.version'),
                data: 'version',
                width: '9%',
                render: function (data, type, row, meta) {
                    options = '';
                    for (var i = data.length - 1; i >= 0; i--) {
                        options += '<option>' + data[i] + '</option>';
                    }
                    return '<select id="plugin-' + row.name + '-vers" class="form-control">' + options + '</select>';
                }
            },
            {
                targets: 4,
                title: trans('market.market.size'),
                data: 'size',
                width: '8%'
            },
            {
                targets: 5,
                title: trans('market.market.operations'),
                data: 'brief',
                width: '20%',
                render: function (data, type, row, meta) {
                    let downloadButtonClass = 'btn-primary';
                    let downloadButtonHint = '';
                    switch (row.versionStatus) {
                        case 'preview':
                            downloadButtonClass = 'btn-warning';
                            downloadButtonHint = trans('market.market.versionPre');
                            break;
                        case 'new':
                            downloadButtonClass = 'btn-success';
                            downloadButtonHint = trans('market.market.versionNew');
                            break;
                        default:
                            break;
                    }
                    let downloadButton = '<input type="button" id="plugin-' + row.name + '" class="btn ' + downloadButtonClass + ' btn-sm" title="' + downloadButtonHint + '"' +
                        ' onclick="readyToDownload(\'' + row.name + '\',\'' + row.title + '\',\'' + row.versionStatus + '\');" value="' + trans('market.market.download') + '">';
                    let briefButton = '' + trans('market.market.viewBrief') + ''
                    return downloadButton + briefButton;
                }
            }
        ]
    });
});

function readyToDownload(pluginName, pluginTitle, versionStatus) {
    if (versionStatus == 'preview') {
        swal({
            title: trans('market.preview.title'),
            text: trans('market.preview.text'),
            type: 'warning',
            showCancelButton: true,
            confirmButtonText: trans('market.preview.confirmButton'),
            cancelButtonText: trans('market.preview.cancelButton')
        }).then(function () { return download(pluginName, pluginTitle); });
    } else {
        let version = $('select#plugin-' + pluginName + '-vers').val();
        return download(pluginName, pluginTitle, version);
    }
};

function download(pluginName, pluginTitle, version) {
    $('input#plugin-' + pluginName).attr({ disabled: true });
    $('input#plugin-' + pluginName).val(trans('market.downloading'));
    toastr.info(trans('market.readyToDownload', { 'plugin-name': pluginTitle }));
    $.post(
        '/admin/plugins-market/download',
        { name: pluginName, version: version },
        function (data) {
            switch (data.code) {
                case -1:
                    toastr.error(trans('market.failedDownload', { 'message': trans('market.error.requestPermission') }));
                    break;
                case 0:
                    if (data.enable) {
                        //会不会有Callback Hell啊？
                        $.post('/admin/plugins/manage', { action: 'enable', id: pluginName }, function (data) {
                            if (data.errno == 0) {
                                toastr.success(data.msg);
                                $.post('/admin/plugins-market/first-run', { id: pluginName }, function (data) {});
                            }
                        });
                    }
                    toastr.success(trans('market.completeDownload', { 'plugin-name': pluginTitle }));
                    break;
                case 1:
                    toastr.error(trans('market.failedDownload', { 'message': trans('market.error.writePermission') }));
                    break;
                case 2:
                    toastr.error(trans('market.failedDownload', { 'message': trans('market.error.connection') }));
                    break;
                case 3:
                    toastr.error(trans('market.failedDownload', { 'message': trans('market.error.download') }));
                    break;
                case 4:
                    toastr.error(trans('market.failedDownload', { 'message': trans('market.error.unzip') }));
                    break;
                default:
                    toastr.error(trans('market.error.unknown'));
                    break;
        };
        $('input#plugin-' + pluginName).attr({ disabled: false });
        $('input#plugin-' + pluginName).val(trans('market.download'));
    });
};
<commit_msg>Use name instead of id in plugin management<commit_after>let pluginsTable;

$(document).ready(function() {
    $('.box-body').css('min-height', $('.content-wrapper').height() - $('.content-header').outerHeight() - 120);
    pluginsTable = $('#plugin-table').DataTable({
        language: trans('vendor.datatables'),
        responsive: true,
        autoWidth: false,
        processing: true,
        ordering: false,
        serverSide: false,   //未知原因，开了这个会有问题
        ajax: {
            url: '/admin/plugins-market/data',
            dataSrc: ''
        },
        createdRow: function (row, data, index) {},
        columnDefs: [
            {
                targets: 0,
                title: trans('market.market.title'),
                data: 'title'
            },
            {
                targets: 1,
                title: trans('market.market.description'),
                data: 'description',
                width: '40%'
            },
            {
                targets: 2,
                title: trans('market.market.author'),
                data: 'author',
                width: '10%'
            },
            {
                targets: 3,
                title: trans('market.market.version'),
                data: 'version',
                width: '9%',
                render: function (data, type, row, meta) {
                    options = '';
                    for (var i = data.length - 1; i >= 0; i--) {
                        options += '<option>' + data[i] + '</option>';
                    }
                    return '<select id="plugin-' + row.name + '-vers" class="form-control">' + options + '</select>';
                }
            },
            {
                targets: 4,
                title: trans('market.market.size'),
                data: 'size',
                width: '8%'
            },
            {
                targets: 5,
                title: trans('market.market.operations'),
                data: 'brief',
                width: '20%',
                render: function (data, type, row, meta) {
                    let downloadButtonClass = 'btn-primary';
                    let downloadButtonHint = '';
                    switch (row.versionStatus) {
                        case 'preview':
                            downloadButtonClass = 'btn-warning';
                            downloadButtonHint = trans('market.market.versionPre');
                            break;
                        case 'new':
                            downloadButtonClass = 'btn-success';
                            downloadButtonHint = trans('market.market.versionNew');
                            break;
                        default:
                            break;
                    }
                    let downloadButton = '<input type="button" id="plugin-' + row.name + '" class="btn ' + downloadButtonClass + ' btn-sm" title="' + downloadButtonHint + '"' +
                        ' onclick="readyToDownload(\'' + row.name + '\',\'' + row.title + '\',\'' + row.versionStatus + '\');" value="' + trans('market.market.download') + '">';
                    let briefButton = '' + trans('market.market.viewBrief') + ''
                    return downloadButton + briefButton;
                }
            }
        ]
    });
});

function readyToDownload(pluginName, pluginTitle, versionStatus) {
    if (versionStatus == 'preview') {
        swal({
            title: trans('market.preview.title'),
            text: trans('market.preview.text'),
            type: 'warning',
            showCancelButton: true,
            confirmButtonText: trans('market.preview.confirmButton'),
            cancelButtonText: trans('market.preview.cancelButton')
        }).then(function () { return download(pluginName, pluginTitle); });
    } else {
        let version = $('select#plugin-' + pluginName + '-vers').val();
        return download(pluginName, pluginTitle, version);
    }
};

function download(pluginName, pluginTitle, version) {
    $('input#plugin-' + pluginName).attr({ disabled: true });
    $('input#plugin-' + pluginName).val(trans('market.downloading'));
    toastr.info(trans('market.readyToDownload', { 'plugin-name': pluginTitle }));
    $.post(
        '/admin/plugins-market/download',
        { name: pluginName, version: version },
        function (data) {
            switch (data.code) {
                case -1:
                    toastr.error(trans('market.failedDownload', { 'message': trans('market.error.requestPermission') }));
                    break;
                case 0:
                    if (data.enable) {
                        //会不会有Callback Hell啊？
                        $.post('/admin/plugins/manage', { action: 'enable', name: pluginName }, function (data) {
                            if (data.errno == 0) {
                                toastr.success(data.msg);
                                $.post('/admin/plugins-market/first-run', { id: pluginName }, function (data) {});
                            }
                        });
                    }
                    toastr.success(trans('market.completeDownload', { 'plugin-name': pluginTitle }));
                    break;
                case 1:
                    toastr.error(trans('market.failedDownload', { 'message': trans('market.error.writePermission') }));
                    break;
                case 2:
                    toastr.error(trans('market.failedDownload', { 'message': trans('market.error.connection') }));
                    break;
                case 3:
                    toastr.error(trans('market.failedDownload', { 'message': trans('market.error.download') }));
                    break;
                case 4:
                    toastr.error(trans('market.failedDownload', { 'message': trans('market.error.unzip') }));
                    break;
                default:
                    toastr.error(trans('market.error.unknown'));
                    break;
        };
        $('input#plugin-' + pluginName).attr({ disabled: false });
        $('input#plugin-' + pluginName).val(trans('market.download'));
    });
};
<|endoftext|>


<commit_before>const Joi = require('joi');

module.exports = Joi.alternatives().try(
  Joi.date().format('YYYY-MM-DD'),
  Joi.date().format('YYYY-MM'),
  Joi.date().format('YYYY')
);
<commit_msg>delete unsused date schema, #654<commit_after><|endoftext|>


<commit_before>var app = new AnyPlay.Plugin('sample')
var json = fetch('https://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/f.json')
.then(res => res.json())
.then(data => data.categories[0])

app.route('/', values => {
  return json.then(data => {
    let links = data.videos.map((video, index) => {
      return {
        src: '/' + index.toString(),
        poster: data.images + video['image-480x270'],
        title: video.title,
        description: video.subtitle
      }
    });

    return {
      title: 'Chrome cast example videos',
      links: links
    }
  })
})

app.route('/:pid', values => {
  return json.then(data => {
    let video = data.videos[parseInt(values.pid)]

    return {
      title: video.title,
      video: {
        poster: data.images + video['image-480x270'],
        source: video.sources.map(source => ({
          type: source.mime.replace('videos/mp4', 'video/mp4'),
          src: data[source.type] + source.url
        }))
      }
    }
  })
})
<commit_msg>request on demand<commit_after>var app = new AnyPlay.Plugin('sample')

function getJson() {
  var p = fetch('https://commondatastorage.googleapis.com/gtv-videos-bucket/CastVideos/f.json')
  .then(res => res.json())
  .then(data => data.categories[0])
  getJson = () => p
  return p
}

app.route('/', values => {
  return getJson().then(data => {
    let links = data.videos.map((video, index) => {
      return {
        src: '/' + index.toString(),
        poster: data.images + video['image-480x270'],
        title: video.title,
        description: video.subtitle
      }
    });

    return {
      title: 'Chrome cast example videos',
      links: links
    }
  })
}, 'cacheOnly')

app.route('/:pid', values => {
  return getJson().then(data => {
    let video = data.videos[parseInt(values.pid)]

    return {
      title: video.title,
      video: {
        poster: data.images + video['image-480x270'],
        source: video.sources.map(source => ({
          type: source.mime.replace('videos/mp4', 'video/mp4'),
          src: data[source.type] + source.url
        }))
      }
    }
  })
}, 'cacheOnly')
<|endoftext|>


<commit_before>const util = require('util');

const TaskCollection = require('./task_collection.js');
const InvocationList = require('./invocation_list.js').InvocationList;
/**
 * This file contains functions and object related to the loading of the jakefile
 */
const debug = false;

exports.Task = Task;
function Task(name, description, prerequisites, action)
{
    let obj;
    if( ! (this instanceof Task) )
    {
        obj = new Task(name, description, prerequisites, action);
        return obj;
    }
    this._name = name;
    this._description = description;
    this._prerequisites = prerequisites.slice();
    this._action = action;

    this.name = function()
    {
    	return this._name;
    }
    this.description = function()
    {
    	return this._description;
    }
    this.prerequisites = function()
    {
    	return this._prerequisites.slice();
    }
    this.action = function()
    {
    	return this._action;
    }
    this.toString = function()
    {
    	return `name:${this._name} description:${this._description} prerequisites:${util.inspect(this._prerequisites)} action:${this._action}`
    }
    this.display = function()
    {
    	console.log(`Task: ${this.toString()}`);
    }
}
exports.invokeTask = invokeTask;
function invokeTask(taskCollection, task)
{
	let loopsList = InvocationList();
	let alreadyDoneList = InvocationList();
	_invokeTask(taskCollection, loopsList, alreadyDoneList, task);
}

/**
 * invokeTask - invokes all the prerequisites for a task and then invokes the target
 * 				task by calling its action property
 *
 * @param {TaskCollection} 	taskCollection, collection of defined tasks
 * @param {InvocationList}	loopsList, a structure for keeping track of
 * 							ancestors in the Depth First scan of tasks
 * 							so that loops in the dependency graph can be detected
 * @param {InvocationList}	prereqsList - a structure fro keeping track of
 * 							prereqs already executed so that we done run a prereq twice.
 *
 * @param {Task}			task - the task to invoke
 *
 */
exports._invokeTask = _invokeTask;
function _invokeTask(taskCollection, loopsList, alreadyDoneList, task)
{
	const debug = false;
	if(debug) console.log(`invokeTask: ${util.inspect(task)}`);
	if(debug) console.log(`invokeTask: name: ${task.name()}`);

	const prereqs = task.prerequisites();

	if( loopsList.hasTask(task) )
	{
		throw new Error(`circular dependency - task:${task.name()} has already been seen`);
	}
	else
	{
		loopsList.addTask(task);
		if( prereqs.length > 0 )
		{
			if(debug) console.log(`invokeTasks prereqs 1 length:${prereqs.length}`);
			prereqs.forEach((el, idx, ar) =>
			{
				if(debug) console.log(`invokeTasks prereqs ${el}`);
				let t = taskCollection.getByName(el);
				if( t === undefined )
				{
					throw new Error(`unknown task ${el} is prerequisite of ${task.name()}`);
				}
				else
				{
					if(debug) console.log(`invokeTask: prereqs ${t.name()}`);
					_invokeTask(taskCollection, loopsList, alreadyDoneList, t)
				}
			});
		}
		if( ! alreadyDoneList.hasTask(task))
		{
			(task.action())();
			alreadyDoneList.addTask(task);
		}
		loopsList.removeTask(task);
	}
}

exports.normalizeArguments = normalizeArguments;
function normalizeArguments()
{
	let a = arguments;
	if(debug) console.log(`normalizeArguments: arguments:${util.inspect(arguments)}`)
	if(debug) console.log(`normalizeArguments: a0: ${a[0]} a1:${a[1]} a2:${a[2]} a3:${a[3]}`)
	if(debug) console.log(`normalizeArguments: a0: ${typeof a[0]} a1:${typeof a[1]} a2:${typeof a[2]} a3:${typeof a[3]}`)
	if(debug) console.log(`normalizeArguments: a0: ${typeof a[0]} a1:${typeof a[1]} a2:${Array.isArray(a[2])} a3:${typeof a[3]}`)
	let args = {
		name: '',
		description:'',
		prereqs:[],
		action: function(){},

	};
	if( (a.length == 4)
		&& (typeof a[3] === 'function')
		&& (Array.isArray(a[2]))
		&& (typeof a[1] === 'string')
		&&( typeof a[0] === 'string'))
	{
		// all 4 arguments provided and of the correct type
		args.name = a[0];
		args.description = a[1];
		args.prereqs = a[2];
		args.action = a[3];
	}
	else if( (a.length === 3)
		&& (typeof a[2] === 'function')
		&& (Array.isArray(a[1] ))
		&&( typeof a[0] === 'string'))
	{
		// only 3 arguments types string, array, function
		args.name = a[0];
		args.prereqs = a[1];
		args.action = a[2];
	}
	else if( (a.length === 3)
		&& (typeof a[2] === 'function')
		&& (typeof a[1] === 'string')
		&&( typeof a[0] === 'string'))
	{
		// only 3 arguments types string string, function
		args.name = a[0];
		args.description = a[1];
		args.action = a[2];
	}
	else if( (a.length === 2)
		&& (typeof a[1] === 'function')
		&&( typeof a[0] === 'string'))
	{
		// only 2 arguments - they must be -  types string, function
		args.name = a[0];
		args.action = a[1];
	}
	else
	{
		args = void 0;
	}
	return args;
}

// exports.TaskCollection = TaskCollection;
// function TaskCollection()
// {

// }

/**
 * loadTaskFromArray - loads a set of tasks from a cfg structure
 * @param {array of task definitions}	- ar task definition structure
 * @parame {TaskCollection}				- taskCollection - collection into which tasks will be placed
 * @return {TaskCollection}				- the updated singelton TaskCollection
 *
 * @global - updates singelton TaskCollection
 *
 */
exports.loadTasksFromArray = loadTasksFromArray;
function loadTasksFromArray(ar, taskCollection)
{
	ar.forEach( (el, index, _ar)=>
	{
		let task = new Task(el.name, el.description, el.prerequisites, el.action);
		taskCollection.addTask(task);
	});
	return taskCollection;
}

exports.loadPreloadedTasks = loadPreloadedTasks;
function loadPreloadedTasks(taskCollection)
{
	const preloadedTasks = [
	{
		name: 'help',
		description: 'list all tasks',
		prerequisites: [],
		action: function action_help()
		{
			console.log('this is the help task running ');
		},
	}];
	loadTasksFomrArray(preloadedTasks, taskCollection)
}

/**
 * Loads tasks from a yakefile into taskCollection and returns the updated taskCollection
 * @param {string} 				yakefile - full path to yakefile - assume it exists
 * @parame {TaskCollection}		taskCollection - collection into which tasks will be placed
 * @return {TaskCollection}		update taskCollection
 */
exports.requireTasks = requireTasks;
function requireTasks(yakefile, taskCollection)
{
	const debug = false;
	// let taskCollection = TaskCollection.getInstance();
	if(debug) console.log(`loadTasks: called ${jakefile}`);
	require(jakefile);
	return taskCollection; // no copy - untidy functional programming
}

exports.defineTask = defineTask;
function defineTask(name, description, prereqs, action)
{
	const debug = false;

	if(debug) console.log(`defineTask: ${name} ${description} ${util.inspect(prereqs)} ${util.inspect(action)}`);
	const task = Task(name, description, prereqs, action);
	let taskCollection = TaskCollection.getInstance();
	taskCollection.addTask(task);
	if(debug) console.log(`defineTask: task: ${util.inspect(task)}`);
	// add task to task collection
}<commit_msg>first<commit_after>const util = require('util');

const TaskCollection = require('./task_collection.js');
const InvocationList = require('./invocation_list.js').InvocationList;
/**
 * This file contains functions and object related to the loading of the jakefile
 */
const debug = false;

exports.Task = Task;
function Task(name, description, prerequisites, action)
{
    let obj;
    if( ! (this instanceof Task) )
    {
        obj = new Task(name, description, prerequisites, action);
        return obj;
    }
    this._name = name;
    this._description = description;
    this._prerequisites = prerequisites.slice();
    this._action = action;

    this.name = function()
    {
    	return this._name;
    }
    this.description = function()
    {
    	return this._description;
    }
    this.prerequisites = function()
    {
    	return this._prerequisites.slice();
    }
    this.action = function()
    {
    	return this._action;
    }
    this.toString = function()
    {
    	return `name:${this._name} description:${this._description} prerequisites:${util.inspect(this._prerequisites)} action:${this._action}`
    }
    this.display = function()
    {
    	console.log(`Task: ${this.toString()}`);
    }
}
exports.invokeTask = invokeTask;
function invokeTask(taskCollection, task)
{
	let loopsList = InvocationList();
	let alreadyDoneList = InvocationList();
	_invokeTask(taskCollection, loopsList, alreadyDoneList, task);
}

/**
 * invokeTask - invokes all the prerequisites for a task and then invokes the target
 * 				task by calling its action property
 *
 * @param {TaskCollection} 	taskCollection, collection of defined tasks
 * @param {InvocationList}	loopsList, a structure for keeping track of
 * 							ancestors in the Depth First scan of tasks
 * 							so that loops in the dependency graph can be detected
 * @param {InvocationList}	prereqsList - a structure fro keeping track of
 * 							prereqs already executed so that we done run a prereq twice.
 *
 * @param {Task}			task - the task to invoke
 *
 */
exports._invokeTask = _invokeTask;
function _invokeTask(taskCollection, loopsList, alreadyDoneList, task)
{
	const debug = false;
	if(debug) console.log(`invokeTask: ${util.inspect(task)}`);
	if(debug) console.log(`invokeTask: name: ${task.name()}`);

	const prereqs = task.prerequisites();

	if( loopsList.hasTask(task) )
	{
		throw new Error(`circular dependency - task:${task.name()} has already been seen`);
	}
	else
	{
		loopsList.addTask(task);
		if( prereqs.length > 0 )
		{
			if(debug) console.log(`invokeTasks prereqs 1 length:${prereqs.length}`);
			prereqs.forEach((el, idx, ar) =>
			{
				if(debug) console.log(`invokeTasks prereqs ${el}`);
				let t = taskCollection.getByName(el);
				if( t === undefined )
				{
					throw new Error(`unknown task ${el} is prerequisite of ${task.name()}`);
				}
				else
				{
					if(debug) console.log(`invokeTask: prereqs ${t.name()}`);
					_invokeTask(taskCollection, loopsList, alreadyDoneList, t)
				}
			});
		}
		if( ! alreadyDoneList.hasTask(task))
		{
			(task.action())();
			alreadyDoneList.addTask(task);
		}
		loopsList.removeTask(task);
	}
}

exports.normalizeArguments = normalizeArguments;
function normalizeArguments()
{
	let a = arguments;
	if(debug) console.log(`normalizeArguments: arguments:${util.inspect(arguments)}`)
	if(debug) console.log(`normalizeArguments: a0: ${a[0]} a1:${a[1]} a2:${a[2]} a3:${a[3]}`)
	if(debug) console.log(`normalizeArguments: a0: ${typeof a[0]} a1:${typeof a[1]} a2:${typeof a[2]} a3:${typeof a[3]}`)
	if(debug) console.log(`normalizeArguments: a0: ${typeof a[0]} a1:${typeof a[1]} a2:${Array.isArray(a[2])} a3:${typeof a[3]}`)
	let args = {
		name: '',
		description:'',
		prereqs:[],
		action: function(){},

	};
	if( (a.length == 4)
		&& (typeof a[3] === 'function')
		&& (Array.isArray(a[2]))
		&& (typeof a[1] === 'string')
		&&( typeof a[0] === 'string'))
	{
		// all 4 arguments provided and of the correct type
		args.name = a[0];
		args.description = a[1];
		args.prereqs = a[2];
		args.action = a[3];
	}
	else if( (a.length === 3)
		&& (typeof a[2] === 'function')
		&& (Array.isArray(a[1] ))
		&&( typeof a[0] === 'string'))
	{
		// only 3 arguments types string, array, function
		args.name = a[0];
		args.prereqs = a[1];
		args.action = a[2];
	}
	else if( (a.length === 3)
		&& (typeof a[2] === 'function')
		&& (typeof a[1] === 'string')
		&&( typeof a[0] === 'string'))
	{
		// only 3 arguments types string string, function
		args.name = a[0];
		args.description = a[1];
		args.action = a[2];
	}
	else if( (a.length === 2)
		&& (typeof a[1] === 'function')
		&&( typeof a[0] === 'string'))
	{
		// only 2 arguments - they must be -  types string, function
		args.name = a[0];
		args.action = a[1];
	}
	else
	{
		args = void 0;
	}
	return args;
}

// exports.TaskCollection = TaskCollection;
// function TaskCollection()
// {

// }

/**
 * loadTaskFromArray - loads a set of tasks from a cfg structure
 * @param {array of task definitions}	- ar task definition structure
 * @parame {TaskCollection}				- taskCollection - collection into which tasks will be placed
 * @return {TaskCollection}				- the updated singelton TaskCollection
 *
 * @global - updates singelton TaskCollection
 *
 */
exports.loadTasksFromArray = loadTasksFromArray;
function loadTasksFromArray(ar, taskCollection)
{
	ar.forEach( (el, index, _ar)=>
	{
		let task = new Task(el.name, el.description, el.prerequisites, el.action);
		taskCollection.addTask(task);
	});
	return taskCollection;
}

exports.loadPreloadedTasks = loadPreloadedTasks;
function loadPreloadedTasks(taskCollection)
{
	const preloadedTasks = [
	{
		name: 'help',
		description: 'list all tasks',
		prerequisites: [],
		action: function action_help()
		{
			console.log('this is the help task running ');
		},
	}];
	let collection = loadTasksFomrArray(preloadedTasks, taskCollection)
	return collection;
}

/**
 * Loads tasks from a yakefile into taskCollection and returns the updated taskCollection
 * @param {string} 				yakefile - full path to yakefile - assume it exists
 * @parame {TaskCollection}		taskCollection - collection into which tasks will be placed
 * @return {TaskCollection}		update taskCollection
 */
exports.requireTasks = requireTasks;
function requireTasks(yakefile, taskCollection)
{
	const debug = false;
	// let taskCollection = TaskCollection.getInstance();
	if(debug) console.log(`loadTasks: called ${jakefile}`);
	require(jakefile);
	return taskCollection; // no copy - untidy functional programming
}

exports.defineTask = defineTask;
function defineTask(name, description, prereqs, action)
{
	const debug = false;

	if(debug) console.log(`defineTask: ${name} ${description} ${util.inspect(prereqs)} ${util.inspect(action)}`);
	const task = Task(name, description, prereqs, action);
	let taskCollection = TaskCollection.getInstance();
	taskCollection.addTask(task);
	if(debug) console.log(`defineTask: task: ${util.inspect(task)}`);
	// add task to task collection
}<|endoftext|>


<commit_before>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 10/01/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/whizkydee/webtwic

*/

jQuery(document).ready(function() {

	// Define Variables
	var is_DisabledFeatures = $("div").hasClass("dfvisible"),
	img = $("img"),
	is_noAlt = img.attr("alt", null),
	scripts = $("script"),
	is_noType = scripts.attr("type", null),
	is_noCharset = scripts.attr("charset", null);

	var $to_top = $("a.to-top"),
	is_toggle_active = $(".hamburger").hasClass("is_active"),
	height = 200;

	// Performance Fixes

	// Create function to add browser name and version to body class

	function showBrowser(b) {
		$("body").addClass(b + " " + b + parseInt(browser.version));
	}

	// Start browser detection

	browser = bowser;
	browser.ie = browser.msie;

	if (browser.webkit) {
		$("body").addClass("webkit");
	}
	if(browser.chrome) {
		showBrowser("chrome");
	}
	if(browser.msedge) {
		showBrowser("msedge");
	}
	if(browser.firefox) {
		showBrowser("firefox");
	}
	if(browser.msie) {
		showBrowser("ie");
	}
	if(browser.safari) {
		showBrowser("safari");
	}
	if(browser.opera) {
		showBrowser("opera");
	}

	// Start function to set attributes and values to elements

	function setAttr(elem, name, val) {
		$(elem, this).attr(name, val);
	}

	if(is_noAlt) {
		setAttr(img, "alt", "...");
	} else {
		return img.attr("alt");
	}

	if(is_noCharset) {
		setAttr(scripts, "charset", "utf-8");
	} else {
		return scripts.attr("charset");
	}

	if(is_noType) {
		setAttr(scripts, "type", "text/javascript");
	} else {
		return scripts.attr("type");
	}

	// Notification for disabled features
	function showDisabledFeatures() {
		$(".top-stripe").before(
			"
Certain features which affect the functionality of webtwic are disabled in your browser. Please try refreshing the page or get a better browser.
"
		);
		$(".close-button").on("click",
			function() {
				hideDisabledFeatures();
				undoSiteAdjust();
			});
	}

	function hideDisabledFeatures() {
		$("#disabledFeatures").removeClass("dfvisible");
	}
	function adjustSiteContent() {
		$(".top-stripe").addClass("adjustedMargin");
		$("#header .logo").addClass("adjustedTop");
		$(".main-menu").addClass("adjustedMargin");
		$("#header").addClass("adjustSiteContent");
	}
	function undoSiteAdjust() {
		$(".top-stripe").removeClass("adjustedMargin");
		$("#header .logo").removeClass("adjustedTop");
		$(".main-menu").removeClass("adjustedMargin");
		$("#header").removeClass("adjustSiteContent");
	}

	// Modernizr funnctions

	function resetSite() {
		showDisabledFeatures();
		adjustSiteContent();
	}

	function undoReset() {
		hideDisabledFeatures();
		undoSiteAdjust();
	}

	if (!Modernizr.flexbox || !Modernizr.inlinesvg || !Modernizr.svg || !Modernizr.svgclippaths || !Modernizr.fontface || !Modernizr.boxshadow || !Modernizr.borderradius || !Modernizr.csstransforms) {
		resetSite();
	} else {
		undoReset();
	}

	// Start Main Page

	$("nav li ul.drop-nav").hide().removeClass("dropNavFallback");

	if ( $(window).width() > 860 ) {
		$("nav li.dropdown").hover(function() {
			$("ul.drop-nav", this).stop().slideDown("fast");
		}, function() {
			$("ul.drop-nav", this).stop().slideUp("fast");
		});
	}

	$(".active-item").append(
		"<svg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><path d='M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z'></path></svg>"
	);

	$("a.hamburger").click(function(e) {
		$(this).toggleClass("is_active");

		e.preventDefault();
	});
	$(".mobile-header .mobile-nav").hide();

	$(window).scroll(function() {
		($(this).scrollTop() > height) ? $to_top.addClass("topVisible"): $to_top.removeClass("topVisible");
	});

	// Styles for homepage article-social

	$(".article .article-social a").hover(function() {
		$("span", this).eq(1).fadeIn(400);
	}, function() {
		$("span", this).eq(1).fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$(".header-follow-search .search-wrap").on("click", function() {
		openUiOverlay();
	});

	$(".header-follow-search .close-icon").on("click", function() {
		closeUiOverlay();
	});

	$(".header-follow-search .close-icon").hover(
		function() {
			$(this).addClass("spin");
		},
		function() {
			$(this).removeClass("spin");
		});

	function openUiOverlay() {
		$(".ui-overlay-search").fadeIn(400).addClass("is_open");
	}

	function closeUiOverlay() {
		$(".ui-overlay-search").fadeOut(400).removeClass("is_open");
	}

	$(".ui-overlay-search .search-input input").focus(function() {
		$(".search-input").attr("data-focused", true);
		$(".search-input input").addClass("_is-focused");
		$("#__expand").addClass("visible");
	});

	$(".ui-overlay-search .search-input input").blur(function() {
		$(".search-input").attr("data-focused", false);
		$(".search-input input").removeClass("_is-focused");
		$("#__expand").removeClass("visible");
	});

	$(".post-meta .post-meta-inner .cta-btns a.is_inactive").on("click", function(e) {
		e.preventDefault();
	});

	$(document).keydown(function(e) {
    if (e.keyCode == 27) {
        closeUiOverlay();
    } else {
		 return;
	 }});

	 $(".mobile-nav").hide();

	// Functions for more-posts button click

	function addLoader() {
		$(".secondary-category-section .category-posts-column [data-clicked='false']").attr("data-clicked", "true").append("");
	}
	$(".secondary-category-section .category-posts-column [data-clicked='false']").on("click", function(e) {
		$(this).css({
			"background": "#50ABF1",
			"color": "#fff"
		});
		addLoader();
		e.preventDefault();
	});

	$to_top.on("click", function(e) {
		$("body,html").animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<commit_msg>Create Webtwic object<commit_after>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 10/01/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/whizkydee/webtwic

*/

jQuery(document).ready(function() {

	// Define Variables
	var Webtwic = {};
	var is_DisabledFeatures = $("div").hasClass("dfvisible"),
	img = $("img"),
	is_noAlt = img.attr("alt", null),
	scripts = $("script"),
	is_noType = scripts.attr("type", null),
	is_noCharset = scripts.attr("charset", null);

	var $to_top = $("a.to-top"),
	is_toggle_active = $(".hamburger").hasClass("is_active"),
	height = 200;

	// Performance Fixes

	// Create function to add browser name and version to body class

	function showBrowser(b) {
		$("body").addClass(b + " " + b + parseInt(browser.version));
	}

	// Start browser detection

	browser = bowser;
	browser.ie = browser.msie;

	if (browser.webkit) {
		$("body").addClass("webkit");
	}
	if(browser.chrome) {
		showBrowser("chrome");
	}
	if(browser.msedge) {
		showBrowser("msedge");
	}
	if(browser.firefox) {
		showBrowser("firefox");
	}
	if(browser.msie) {
		showBrowser("ie");
	}
	if(browser.safari) {
		showBrowser("safari");
	}
	if(browser.opera) {
		showBrowser("opera");
	}

	// Start function to set attributes and values to elements

	function setAttr(elem, name, val) {
		$(elem, this).attr(name, val);
	}

	if(is_noAlt) {
		setAttr(img, "alt", "...");
	} else {
		return img.attr("alt");
	}

	if(is_noCharset) {
		setAttr(scripts, "charset", "utf-8");
	} else {
		return scripts.attr("charset");
	}

	if(is_noType) {
		setAttr(scripts, "type", "text/javascript");
	} else {
		return scripts.attr("type");
	}

	// Notification for disabled features
	function showDisabledFeatures() {
		$(".top-stripe").before(
			"
Certain features which affect the functionality of webtwic are disabled in your browser. Please try refreshing the page or get a better browser.
"
		);
		$(".close-button").on("click",
			function() {
				hideDisabledFeatures();
				undoSiteAdjust();
			});
	}

	function hideDisabledFeatures() {
		$("#disabledFeatures").removeClass("dfvisible");
	}
	function adjustSiteContent() {
		$(".top-stripe").addClass("adjustedMargin");
		$("#header .logo").addClass("adjustedTop");
		$(".main-menu").addClass("adjustedMargin");
		$("#header").addClass("adjustSiteContent");
	}
	function undoSiteAdjust() {
		$(".top-stripe").removeClass("adjustedMargin");
		$("#header .logo").removeClass("adjustedTop");
		$(".main-menu").removeClass("adjustedMargin");
		$("#header").removeClass("adjustSiteContent");
	}

	// Modernizr funnctions

	function resetSite() {
		showDisabledFeatures();
		adjustSiteContent();
	}

	function undoReset() {
		hideDisabledFeatures();
		undoSiteAdjust();
	}

	if (!Modernizr.flexbox || !Modernizr.inlinesvg || !Modernizr.svg || !Modernizr.svgclippaths || !Modernizr.fontface || !Modernizr.boxshadow || !Modernizr.borderradius || !Modernizr.csstransforms) {
		resetSite();
	} else {
		undoReset();
	}

	// Start Main Page

	$("nav li ul.drop-nav").hide().removeClass("dropNavFallback");

	if ( $(window).width() > 860 ) {
		$("nav li.dropdown").hover(function() {
			$("ul.drop-nav", this).stop().slideDown("fast");
		}, function() {
			$("ul.drop-nav", this).stop().slideUp("fast");
		});
	}

	$(".active-item").append(
		"<svg viewBox='0 0 32 32' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink'><path d='M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z'></path></svg>"
	);

	$("a.hamburger").click(function(e) {
		$(this).toggleClass("is_active");

		e.preventDefault();
	});
	$(".mobile-header .mobile-nav").hide();

	$(window).scroll(function() {
		($(this).scrollTop() > height) ? $to_top.addClass("topVisible"): $to_top.removeClass("topVisible");
	});

	// Styles for homepage article-social

	$(".article .article-social a").hover(function() {
		$("span", this).eq(1).fadeIn(400);
	}, function() {
		$("span", this).eq(1).fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$(".header-follow-search .search-wrap").on("click", function() {
		openUiOverlay();
	});

	$(".header-follow-search .close-icon").on("click", function() {
		closeUiOverlay();
	});

	$(".header-follow-search .close-icon").hover(
		function() {
			$(this).addClass("spin");
		},
		function() {
			$(this).removeClass("spin");
		});

	function openUiOverlay() {
		$(".ui-overlay-search").fadeIn(400).addClass("is_open");
	}

	function closeUiOverlay() {
		$(".ui-overlay-search").fadeOut(400).removeClass("is_open");
	}

	$(".ui-overlay-search .search-input input").focus(function() {
		$(".search-input").attr("data-focused", true);
		$(".search-input input").addClass("_is-focused");
		$("#__expand").addClass("visible");
	});

	$(".ui-overlay-search .search-input input").blur(function() {
		$(".search-input").attr("data-focused", false);
		$(".search-input input").removeClass("_is-focused");
		$("#__expand").removeClass("visible");
	});

	$(".post-meta .post-meta-inner .cta-btns a.is_inactive").on("click", function(e) {
		e.preventDefault();
	});

	$(document).keydown(function(e) {
    if (e.keyCode == 27) {
        closeUiOverlay();
    } else {
		 return;
	 }});

	 $(".mobile-nav").hide();

	// Functions for more-posts button click

	function addLoader() {
		$(".secondary-category-section .category-posts-column [data-clicked='false']").attr("data-clicked", "true").append("");
	}
	$(".secondary-category-section .category-posts-column [data-clicked='false']").on("click", function(e) {
		$(this).css({
			"background": "#50ABF1",
			"color": "#fff"
		});
		addLoader();
		e.preventDefault();
	});

	$to_top.on("click", function(e) {
		$("body,html").animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<|endoftext|>


<commit_before>// Copyright 2012 YDN Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview AVL tree suitable for async traversal and resume.
 *
 * Basically this is slight modification of @see goog.structs.AvlTree.
 * Unfortunately, the original class cannot be override since some functions
 * are not expose to superclass.
 *
 * @suppress {accessControls}
 */

goog.provide('ydn.structs.Buffer');
goog.provide('ydn.structs.Buffer.Iterator');
goog.require('goog.structs.AvlTree');
goog.require('ydn.db.KeyRange');

/**
 *
 * @param {Function=} opt_comparator Function used to order the tree's nodes.
 * @constructor
 * @extends {goog.structs.AvlTree}
 */
ydn.structs.Buffer = function(opt_comparator) {
  goog.base(this, opt_comparator);
};
goog.inherits(ydn.structs.Buffer, goog.structs.AvlTree);

/**
 * Performs an in-order traversal of the tree and calls {@code func} with each
 * traversed node, optionally starting from the smallest node with a value >= to
 * the specified start value. The traversal ends after traversing the tree's
 * maximum node or when {@code func} returns a value that evaluates to true.
 *
 * @param {function(goog.structs.AvlTree.Node)} func Function to call on each
 * traversed node.
 * @param {Object=} opt_startValue If
 * specified, traversal will begin on the node with the smallest
 * value >= opt_startValue. If AvlTree.Node, this will start immediately
 * from the node exclusive.
 */
ydn.structs.Buffer.prototype.traverse = function(func, opt_startValue) {
  // If our tree is empty, return immediately
  if (!this.root_) {
    return;
  }

  // Depth traverse the tree to find node to begin in-order traversal from
  var startNode;
  if (opt_startValue instanceof goog.structs.AvlTree.Node) {
    startNode = opt_startValue;
  } else if (opt_startValue) {
    this.traverse_(function(node) {
      var retNode = null;
      if (this.comparator_(node.value, opt_startValue) > 0) {
        retNode = node.left;
        startNode = node;
      } else if (this.comparator_(node.value, opt_startValue) < 0) {
        retNode = node.right;
      } else {
        startNode = node;
      }
      return retNode; // If null, we'll stop traversing the tree
    });
    if (!startNode) {
      return;
    }
  } else {
    startNode = this.getMinNode_();
  }

  // Traverse the tree and call func on each traversed node's value
  var node = startNode, prev = startNode.left ? startNode.left : startNode;
  while (node != null) {
    if (node.left != null && node.left != prev && node.right != prev) {
      node = node.left;
    } else {
      if (node.right != prev) {
        if (func(node)) {
          return;
        }
      }
      var temp = node;
      node = node.right != null && node.right != prev ?
          node.right :
          node.parent;
      prev = temp;
    }
  }
  func(null); // let know, no more traversal
};

/**
 * Performs a reverse-order traversal of the tree and calls {@code func} with
 * each traversed node, optionally starting from the largest node with a value
 * <= to the specified start value. The traversal ends after traversing the
 * tree's minimum node or when func returns a value that evaluates to true.
 *
 * @param {function(goog.structs.AvlTree.Node)} func Function to call on each
 * traversed node.
 * @param {Object=} opt_startValue If
 * specified, traversal will begin on the node with the smallest
 * value >= opt_startValue. If AvlTree.Node, this will start immediately
 * from the node exclusive.
 */
ydn.structs.Buffer.prototype.reverseTraverse = function(func, opt_startValue) {
  // If our tree is empty, return immediately
  if (!this.root_) {
    func();
    return;
  }

  // Depth traverse the tree to find node to begin reverse-order traversal from
  var startNode;
  if (opt_startValue instanceof goog.structs.AvlTree.Node) {
    startNode = opt_startValue;
  } else if (opt_startValue) {
    this.traverse_(goog.bind(function(node) {
      var retNode = null;
      if (this.comparator_(node.value, opt_startValue) > 0) {
        retNode = node.left;
      } else if (this.comparator_(node.value, opt_startValue) < 0) {
        retNode = node.right;
        startNode = node;
      } else {
        startNode = node;
      }
      return retNode; // If null, we'll stop traversing the tree
    }, this));
    if (!startNode) {
      func();
      return;
    }
  } else {
    startNode = this.getMaxNode_();
  }

  // Traverse the tree and call func on each traversed node's value
  var node = startNode, prev = startNode.right ? startNode.right : startNode;
  while (node != null) {
    if (node.right != null && node.right != prev && node.left != prev) {
      node = node.right;
    } else {
      if (node.left != prev) {
        if (func(node)) {
          return;
        }
      }
      var temp = node;
      node = node.left != null && node.left != prev ?
          node.left :
          node.parent;
      prev = temp;
    }
  }
  func(null); // let know, no more traversal
};

/**
 * Create a new iterator.
 * @param {ydn.db.KeyRange=} opt_key_range key range.
 * @param {boolean=} opt_reverse reverse iterating.
 * @param {boolean=} opt_unique unique traverse.
 * @return {!ydn.structs.Buffer.Iterator} iterator.
 */
ydn.structs.Buffer.prototype.iter = function(opt_key_range, opt_reverse,
                                        opt_unique) {
  return new ydn.structs.Buffer.Iterator(opt_key_range, opt_reverse,
      opt_unique);
};

/**
 * Key scanning.
 * @param {Function} func node visit callback.
 * @param {!ydn.structs.Buffer.Iterator|!ydn.db.KeyRange} iter iterator or key range.
 */
ydn.structs.Buffer.prototype.scan = function(func, iter) {
  var it = iter instanceof ydn.structs.Buffer.Iterator ? iter : this.iter(iter);

  // If our tree is empty, return immediately
  if (!this.root_) {
    func();
    return;
  }

  var startNode;
  var skip_first_node = false;
  if (it.current_) {
    startNode = it.current_;
  } else if (it.key_range_) {
    var start_value;
    if (it.reverse_ && goog.isDefAndNotNull(it.key_range_.upper)) {
      start_value = it.key_range_.upper;
      skip_first_node = !!it.key_range_.upperOpen;
    } else if (goog.isDefAndNotNull(it.key_range_.lower)) {
      start_value = it.key_range_.lower;
      skip_first_node = !!it.key_range_.lowerOpen;
    }
    this.traverse_(goog.bind(function(node) {
      var retNode = null;
      if (this.comparator_(node.value, start_value) > 0) {
        retNode = node.left;
      } else if (this.comparator_(node.value, start_value) < 0) {
        retNode = node.right;
        startNode = node;
      } else {
        startNode = node;
      }
      return retNode; // If null, we'll stop traversing the tree
    }, this));

  } else if (!startNode) {
    startNode = this.getMaxNode_();
  }
  if (!startNode) {
    it.current_ = null;
    func();
    return;
  }
  var node = startNode;
  var prev;
  // Traverse the tree and call func on each traversed node's value
  if (it.reverse_) {
    prev = startNode.right ? startNode.right : startNode;
    while (node != null) {
      if (node.right != null && node.right != prev && node.left != prev) {
        node = node.right;
      } else {
        if (node.left != prev) {
          it.current_ = node;
          if (skip_first_node) {
            skip_first_node = false;
            continue;
          }
          if (func(node.value)) {
            return;
          }
        }
        var temp = node;
        node = node.left != null && node.left != prev ?
            node.left :
            node.parent;
        prev = temp;
      }
    }
    it.current_ = null;
    func();
  } else {
    prev = startNode.left ? startNode.left : startNode;
    while (node != null) {
      if (node.left != null && node.left != prev && node.right != prev) {
        node = node.left;
      } else {
        if (node.right != prev) {
          it.current_ = node;
          if (skip_first_node) {
            skip_first_node = false;
            continue;
          }
          if (func(node.value)) {
            return;
          }
        }
        var temp = node;
        node = node.right != null && node.right != prev ?
            node.right :
            node.parent;
        prev = temp;
      }
    }
  }
};

/**
 * Union operation with other buffer.
 * @param {ydn.structs.Buffer} other
 */
ydn.structs.Buffer.prototype.union = function(other) {
  var this_node = this.getMinNode_();
  var that_node = other.getMinNode_();
  while (that_node) {

  }
};

/**
 * Iterator for buffer class.
 * @param {ydn.db.KeyRange=} opt_key_range key range.
 * @param {boolean=} opt_reverse reverse iterating.
 * @param {boolean=} opt_unique unique traverse.
 * @constructor
 */
ydn.structs.Buffer.Iterator = function(opt_key_range, opt_reverse, opt_unique) {
  /**
   * @final
   * @private
   * @type {?ydn.db.KeyRange}
   */
  this.key_range_ = opt_key_range || null;
  /**
   * @final
   * @private
   */
  this.reverse_ = !!opt_reverse;
  /**
   * @final
   * @private
   */
  this.unique_ = !!opt_unique;
  this.current_ = null;
};

/**
 * Reverse traversal.
 * @type {ydn.db.KeyRange}
 * @private
 */
ydn.structs.Buffer.Iterator.prototype.key_range_ = null;

/**
 * Reverse traversal.
 * @type {boolean}
 * @private
 */
ydn.structs.Buffer.Iterator.prototype.reverse_ = false;

/**
 * Traverse unique node only.
 * @type {boolean}
 * @private
 */
ydn.structs.Buffer.Iterator.prototype.unique_ = false;

/**
 * Current node.
 * @type {goog.structs.AvlTree.Node}
 * @private
 */
ydn.structs.Buffer.Iterator.prototype.current_ = null;
<commit_msg>Fix ydn-db#90: ada1971 only fix reverseTraverse.<commit_after>// Copyright 2012 YDN Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview AVL tree suitable for async traversal and resume.
 *
 * Basically this is slight modification of @see goog.structs.AvlTree.
 * Unfortunately, the original class cannot be override since some functions
 * are not expose to superclass.
 *
 * @suppress {accessControls}
 */

goog.provide('ydn.structs.Buffer');
goog.provide('ydn.structs.Buffer.Iterator');
goog.require('goog.structs.AvlTree');
goog.require('ydn.db.KeyRange');

/**
 *
 * @param {Function=} opt_comparator Function used to order the tree's nodes.
 * @constructor
 * @extends {goog.structs.AvlTree}
 */
ydn.structs.Buffer = function(opt_comparator) {
  goog.base(this, opt_comparator);
};
goog.inherits(ydn.structs.Buffer, goog.structs.AvlTree);

/**
 * Performs an in-order traversal of the tree and calls {@code func} with each
 * traversed node, optionally starting from the smallest node with a value >= to
 * the specified start value. The traversal ends after traversing the tree's
 * maximum node or when {@code func} returns a value that evaluates to true.
 *
 * @param {function(goog.structs.AvlTree.Node)} func Function to call on each
 * traversed node.
 * @param {Object=} opt_startValue If
 * specified, traversal will begin on the node with the smallest
 * value >= opt_startValue. If AvlTree.Node, this will start immediately
 * from the node exclusive.
 */
ydn.structs.Buffer.prototype.traverse = function(func, opt_startValue) {
  // If our tree is empty, return immediately
  if (!this.root_) {
    func(null);
    return;
  }

  // Depth traverse the tree to find node to begin in-order traversal from
  var startNode;
  if (opt_startValue instanceof goog.structs.AvlTree.Node) {
    startNode = opt_startValue;
  } else if (opt_startValue) {
    this.traverse_(function(node) {
      var retNode = null;
      if (this.comparator_(node.value, opt_startValue) > 0) {
        retNode = node.left;
        startNode = node;
      } else if (this.comparator_(node.value, opt_startValue) < 0) {
        retNode = node.right;
      } else {
        startNode = node;
      }
      return retNode; // If null, we'll stop traversing the tree
    });
    if (!startNode) {
      func(null);
      return;
    }
  } else {
    startNode = this.getMinNode_();
  }

  // Traverse the tree and call func on each traversed node's value
  var node = startNode, prev = startNode.left ? startNode.left : startNode;
  while (node != null) {
    if (node.left != null && node.left != prev && node.right != prev) {
      node = node.left;
    } else {
      if (node.right != prev) {
        if (func(node)) {
          return;
        }
      }
      var temp = node;
      node = node.right != null && node.right != prev ?
          node.right :
          node.parent;
      prev = temp;
    }
  }
  func(null); // let know, no more traversal
};

/**
 * Performs a reverse-order traversal of the tree and calls {@code func} with
 * each traversed node, optionally starting from the largest node with a value
 * <= to the specified start value. The traversal ends after traversing the
 * tree's minimum node or when func returns a value that evaluates to true.
 *
 * @param {function(goog.structs.AvlTree.Node)} func Function to call on each
 * traversed node.
 * @param {Object=} opt_startValue If
 * specified, traversal will begin on the node with the smallest
 * value >= opt_startValue. If AvlTree.Node, this will start immediately
 * from the node exclusive.
 */
ydn.structs.Buffer.prototype.reverseTraverse = function(func, opt_startValue) {
  // If our tree is empty, return immediately
  if (!this.root_) {
    func(null);
    return;
  }

  // Depth traverse the tree to find node to begin reverse-order traversal from
  var startNode;
  if (opt_startValue instanceof goog.structs.AvlTree.Node) {
    startNode = opt_startValue;
  } else if (opt_startValue) {
    this.traverse_(goog.bind(function(node) {
      var retNode = null;
      if (this.comparator_(node.value, opt_startValue) > 0) {
        retNode = node.left;
      } else if (this.comparator_(node.value, opt_startValue) < 0) {
        retNode = node.right;
        startNode = node;
      } else {
        startNode = node;
      }
      return retNode; // If null, we'll stop traversing the tree
    }, this));
    if (!startNode) {
      func(null);
      return;
    }
  } else {
    startNode = this.getMaxNode_();
  }

  // Traverse the tree and call func on each traversed node's value
  var node = startNode, prev = startNode.right ? startNode.right : startNode;
  while (node != null) {
    if (node.right != null && node.right != prev && node.left != prev) {
      node = node.right;
    } else {
      if (node.left != prev) {
        if (func(node)) {
          return;
        }
      }
      var temp = node;
      node = node.left != null && node.left != prev ?
          node.left :
          node.parent;
      prev = temp;
    }
  }
  func(null); // let know, no more traversal
};

/**
 * Create a new iterator.
 * @param {ydn.db.KeyRange=} opt_key_range key range.
 * @param {boolean=} opt_reverse reverse iterating.
 * @param {boolean=} opt_unique unique traverse.
 * @return {!ydn.structs.Buffer.Iterator} iterator.
 */
ydn.structs.Buffer.prototype.iter = function(opt_key_range, opt_reverse,
                                        opt_unique) {
  return new ydn.structs.Buffer.Iterator(opt_key_range, opt_reverse,
      opt_unique);
};

/**
 * Key scanning.
 * @param {Function} func node visit callback.
 * @param {!ydn.structs.Buffer.Iterator|!ydn.db.KeyRange} iter iterator or key range.
 */
ydn.structs.Buffer.prototype.scan = function(func, iter) {
  var it = iter instanceof ydn.structs.Buffer.Iterator ? iter : this.iter(iter);

  // If our tree is empty, return immediately
  if (!this.root_) {
    func();
    return;
  }

  var startNode;
  var skip_first_node = false;
  if (it.current_) {
    startNode = it.current_;
  } else if (it.key_range_) {
    var start_value;
    if (it.reverse_ && goog.isDefAndNotNull(it.key_range_.upper)) {
      start_value = it.key_range_.upper;
      skip_first_node = !!it.key_range_.upperOpen;
    } else if (goog.isDefAndNotNull(it.key_range_.lower)) {
      start_value = it.key_range_.lower;
      skip_first_node = !!it.key_range_.lowerOpen;
    }
    this.traverse_(goog.bind(function(node) {
      var retNode = null;
      if (this.comparator_(node.value, start_value) > 0) {
        retNode = node.left;
      } else if (this.comparator_(node.value, start_value) < 0) {
        retNode = node.right;
        startNode = node;
      } else {
        startNode = node;
      }
      return retNode; // If null, we'll stop traversing the tree
    }, this));

  } else if (!startNode) {
    startNode = this.getMaxNode_();
  }
  if (!startNode) {
    it.current_ = null;
    func();
    return;
  }
  var node = startNode;
  var prev;
  // Traverse the tree and call func on each traversed node's value
  if (it.reverse_) {
    prev = startNode.right ? startNode.right : startNode;
    while (node != null) {
      if (node.right != null && node.right != prev && node.left != prev) {
        node = node.right;
      } else {
        if (node.left != prev) {
          it.current_ = node;
          if (skip_first_node) {
            skip_first_node = false;
            continue;
          }
          if (func(node.value)) {
            return;
          }
        }
        var temp = node;
        node = node.left != null && node.left != prev ?
            node.left :
            node.parent;
        prev = temp;
      }
    }
    it.current_ = null;
    func();
  } else {
    prev = startNode.left ? startNode.left : startNode;
    while (node != null) {
      if (node.left != null && node.left != prev && node.right != prev) {
        node = node.left;
      } else {
        if (node.right != prev) {
          it.current_ = node;
          if (skip_first_node) {
            skip_first_node = false;
            continue;
          }
          if (func(node.value)) {
            return;
          }
        }
        var temp = node;
        node = node.right != null && node.right != prev ?
            node.right :
            node.parent;
        prev = temp;
      }
    }
  }
};

/**
 * Union operation with other buffer.
 * @param {ydn.structs.Buffer} other
 */
ydn.structs.Buffer.prototype.union = function(other) {
  var this_node = this.getMinNode_();
  var that_node = other.getMinNode_();
  while (that_node) {

  }
};

/**
 * Iterator for buffer class.
 * @param {ydn.db.KeyRange=} opt_key_range key range.
 * @param {boolean=} opt_reverse reverse iterating.
 * @param {boolean=} opt_unique unique traverse.
 * @constructor
 */
ydn.structs.Buffer.Iterator = function(opt_key_range, opt_reverse, opt_unique) {
  /**
   * @final
   * @private
   * @type {?ydn.db.KeyRange}
   */
  this.key_range_ = opt_key_range || null;
  /**
   * @final
   * @private
   */
  this.reverse_ = !!opt_reverse;
  /**
   * @final
   * @private
   */
  this.unique_ = !!opt_unique;
  this.current_ = null;
};

/**
 * Reverse traversal.
 * @type {ydn.db.KeyRange}
 * @private
 */
ydn.structs.Buffer.Iterator.prototype.key_range_ = null;

/**
 * Reverse traversal.
 * @type {boolean}
 * @private
 */
ydn.structs.Buffer.Iterator.prototype.reverse_ = false;

/**
 * Traverse unique node only.
 * @type {boolean}
 * @private
 */
ydn.structs.Buffer.Iterator.prototype.unique_ = false;

/**
 * Current node.
 * @type {goog.structs.AvlTree.Node}
 * @private
 */
ydn.structs.Buffer.Iterator.prototype.current_ = null;
<|endoftext|>


<commit_before>//Datos globales
var base_url = 'http://' + window.location.hostname + '/ceiba_negra/';
var lang_esp_datatables = "https://cdn.datatables.net/plug-ins/1.10.12/i18n/Spanish.json";
//Funcion FormToObject
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

//Al cargar la página
$(document).ready(function () {
    //Preconfiguración de los datatable
    $.extend( true, $.fn.dataTable.defaults, {
        "pagingType": "full_numbers",
        "language": {
            "url": lang_esp_datatables
        },
    } );
    //Estructura de Datatable para las Manzanas
    var manzanas_table = $('#manzanas').DataTable({
        "ajax": base_url + 'ajax/get_manzanas', //URL de datos
        "columns": [    //Atributos para la tabla
            { "data": "id_manzana" },
            { "data": "manzana" },
            { "data": "calle" },
            { "data": "disponibilidad" },
            { "data": "" } //Espacio extra para el boton o botones de opciones
        ],
        columnDefs: [   //Configuracion de la tabla de manzanas
            {
                "targets": 0,
                "visible": false
            },
            {
                "targets": 1,
                "className": "col-mz"
            },
            {
                "targets": -1,
                "data": null,
                "defaultContent": '<button data-toggle="modal" data-target="#edit-manzana" class="btn btn-info btn-sm"></button>'
            },
            {
                "sortable": false,
                "targets": [-1, -3]
            },
            {
                "searchable": false,
                "targets": [-2]
            }
        ]
    });
    //Obtener id del datatable de manzanas
    $('#manzanas tbody').on('click', 'button', function () {
        var manzana = manzanas_table.row($(this).parents('tr')).data();
        console.log(manzana);
        $("#frm-edit-manzanas #manzana").val(manzana.manzana);
        $("#frm-edit-manzanas #calle").val(manzana.calle);
        $("#frm-edit-manzanas #calle").val(manzana.calle);
        $("#frm-edit-manzanas #disponibilidad").val(manzana.disponibilidad);
    });
    //Datatable de Lotes
    $('#lotes').DataTable({
        "ajax": base_url + 'ajax/get_lotes_pmz',
        "language": {
            "url": lang_esp_datatables
        },
        columnDefs: [
            {
                "targets": 0,
                "visible": false
            },
            {
                "targets": [4, 5, 6],
                "className": "col-moneda"
            },
        ]
    });
    //Enmascarar formato de moneda
    $('tbody .col-moneda').mask('$ 000.000.000.000.000,00');
    //Desplegar mapa
    var mapplic = $('#mapplic').mapplic({
        source: base_url + 'ajax/get_mapa',	// Using mall.json file as map data
        sidebar: true, 			// Enable sidebar
        minimap: false, 			// Enable minimap
        markers: false, 		// Disable markers
        mapfill: true,
        fillcolor: '',
        fullscreen: false, 		// Enable fullscreen
        developer: true,
        zoom: false,
        maxscale: 0.65, 			// Setting maxscale to 3
    });
    //Herramienta para capturar las coordenadas del mapa
    mapplic.on('locationopened', function (e, location) {
        var manzana = (location.category.replace("mz", ""));
        var lote = (location.title.replace("Lote número ", ""));
        var data = {
            manzana: manzana,
            lote: lote,
            x: ($(".mapplic-coordinates-x")[0].innerHTML),
            y: $(".mapplic-coordinates-y")[0].innerHTML
        };
        console.log(data);
        $.ajax({
            url: base_url + "ajax/guardar_coordenadas/",
            type: 'post',
            asyn: true,
            data: data
        });
    });

    //Formularios
    //Formulario de manzana
    $('#frm-add-manzanas').on('submit', function (e) {
        e.preventDefault();
        var data = $(this).serializeArray(); //Serializar formulario
        var that = this; //Almacenar el formulario donde sucedio el evento submit
        //Llamada ajax
        $.ajax({
            url: base_url + "ajax/add_manzana",
            type: "post",
            data: data,
            beforeSend: function (xhr) {
                $("input[type='submit']").attr("disabled", true).next().css('visibility', 'visible');
                //Hacer que el boton tenga efeto de load
            }
        })
        .done(function(response) {
            that.reset();
            console.log(response);
            $('.modal-body').find('.container-icons.success').show(0).delay(1000).hide(0);
            // $('.modal-body').removeClass('after');
            $("input[type='submit']").attr("disabled", false).next().css('visibility','hidden');
            // alert("Datos insertados correctamente");
            // $('#add-manzana').modal('hide');
            manzanas_table.ajax.reload(null, false ); // user paging is not reset on reload
            manzanas_table.order( [ 0, 'desc' ] ).draw();
        })
        .fail(function(response) {
            console.log(response)
            $('.modal-body').find('.container-icons.error').show(0).delay(1000).hide(0);
            $("input[type='submit']").attr("disabled", false).next().css('visibility','hidden');
            var mensaje  = "Mensaje de error: " + response.responseText;
            mensaje     += "\nVerificar los datos ingresados con los registros existentes.";
            mensaje     += "\nCódigo de error: " + response.status + ".";
            mensaje     += "\nMensaje de código error: " + response.statusText + ".";
            // alert(mensaje);
        });
    });
});<commit_msg>Adelanto del update<commit_after>//Datos globales
var base_url = 'http://' + window.location.hostname + '/ceiba_negra/';
var lang_esp_datatables = "https://cdn.datatables.net/plug-ins/1.10.12/i18n/Spanish.json";
//Funcion FormToObject
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
//Preconfiguración de los datatable
$.extend( true, $.fn.dataTable.defaults, {
    "pagingType": "full_numbers",
    "language": {
        "url": lang_esp_datatables
    },
} );
//Al cargar la página
$(document).ready(function () {
    //MANZANAS
    //Estructura de Datatable para las Manzanas (La tabla de vista)
    var manzanas_table = $('#manzanas').DataTable({
        "ajax": base_url + 'ajax/get_manzanas', //URL de datos
        "columns": [    //Atributos para la tabla
            { "data": "id_manzana" },
            { "data": "manzana" },
            { "data": "calle" },
            { "data": "disponibilidad" },
            { "data": "" } //Espacio extra para el boton o botones de opciones
        ],
        columnDefs: [   //Configuracion de la tabla de manzanas
            {
                //Ocultar columna*
                "targets": 0,
                "visible": false
            },
            {
                //Añadir super clase kawai, para esta columna*
                "targets": 1,
                "className": "col-mz"
            },
            {
                //Añadir boton dinamicamente, para esta columna*
                "targets": -1,
                "data": null,
                "defaultContent": '<button data-toggle="modal" data-target="#edit-manzana" class="btn btn-info btn-sm"></button>'
            },
            {
                //Quitar ordenamiento para estas columnas
                "sortable": false,
                "targets": [-1, -3]
            },
            {
                //Quitar busqueda para esta columna
                "searchable": false,
                "targets": [-2]
            }
        ]
    });
    //Obtener id del datatable de manzanas
    var manzana;
    var fila;
    $('#manzanas tbody').on('click', 'button', function () {
        fila = $(this).parents('tr');
        manzana = manzanas_table.row(fila).data();

        //{manzana: 8907,calle:"Ola ke ace",disponibilidad:"0"}

        //Añadimos los valores al modal, inidicando el formulario debido a que los id se repiten (Eliminarlos del insert ya que ahí no se usan)
        $("#frm-edit-manzanas #manzana").val(manzana.manzana);
        $("#frm-edit-manzanas #calle").val(manzana.calle);
        $("#frm-edit-manzanas #calle").val(manzana.calle);
        $("#frm-edit-manzanas #disponibilidad").val(manzana.disponibilidad);

    });
    //manzanas_table.fnUpdate( , 1 ); // Row
    //Formulario para agregar manzana
    $('#frm-add-manzanas').on('submit', function (e) {
        e.preventDefault();
        var data = $(this).serializeArray(); //Serializar formulario
        var that = this; //Almacenar el formulario donde sucedio el evento submit
        //Llamada ajax
        $.ajax({
            url: base_url + "ajax/add_manzana",
            type: "post",
            data: data,
            beforeSend: function (xhr) {
                $("input[type='submit']").attr("disabled", true).next().css('visibility', 'visible');
                //Hacer que el boton tenga efeto de load
            }
        })
        .done(function(response) {
            that.reset();
            console.log(response);
            $('.modal-body').find('.container-icons.success').show(0).delay(1000).hide(0);
            // $('.modal-body').removeClass('after');
            $("input[type='submit']").attr("disabled", false).next().css('visibility','hidden');
            // alert("Datos insertados correctamente");
            // $('#add-manzana').modal('hide');
            manzanas_table.ajax.reload(null, false ); // user paging is not reset on reload //Cambiar por add row xD
            manzanas_table.order( [ 0, 'desc' ] ).draw();
        })
        .fail(function(response) {
            console.log(response)
            $('.modal-body').find('.container-icons.error').show(0).delay(1000).hide(0);
            $("input[type='submit']").attr("disabled", false).next().css('visibility','hidden');
            var mensaje  = "Mensaje de error: " + response.responseText;
            mensaje     += "\nVerificar los datos ingresados con los registros existentes.";
            mensaje     += "\nCódigo de error: " + response.status + ".";
            mensaje     += "\nMensaje de código error: " + response.statusText + ".";
            // alert(mensaje);
        });
    });
    //Formulario para editar manzanas
    $("#frm-edit-manzanas").on('submit',function(e){
        e.preventDefault();
        manzana.manzana = 8907;
        manzanas_table
            .row( fila )
            .data( manzana )
            .draw();
    });
    //LOTES
    //Datatable de Lotes
    $('#lotes').DataTable({
        "ajax": base_url + 'ajax/get_lotes_pmz',
        "language": {
            "url": lang_esp_datatables
        },
        columnDefs: [
            {
                "targets": 0,
                "visible": false
            },
            {
                "targets": [4, 5, 6],
                "className": "col-moneda"
            },
        ]
    });
    //DETALLES EXTRA
    //Enmascarar formato de moneda, dentro de una tabla*
    $('tbody .col-moneda').mask('$ 000.000.000.000.000,00');
    //MAPA
    //Desplegar mapa
    var mapplic = $('#mapplic').mapplic({
        source: base_url + 'ajax/get_mapa',	// Using mall.json file as map data
        sidebar: true, 			// Enable sidebar
        minimap: false, 			// Enable minimap
        markers: false, 		// Disable markers
        mapfill: true,
        fillcolor: '',
        fullscreen: false, 		// Enable fullscreen
        developer: true,
        zoom: false,
        maxscale: 0.65, 			// Setting maxscale to 3
    });
    //Herramienta para capturar las coordenadas del mapa
    mapplic.on('locationopened', function (e, location) {
        var manzana = (location.category.replace("mz", ""));
        var lote = (location.title.replace("Lote número ", ""));
        var data = {
            manzana: manzana,
            lote: lote,
            x: ($(".mapplic-coordinates-x")[0].innerHTML),
            y: $(".mapplic-coordinates-y")[0].innerHTML
        };
        console.log(data);
        $.ajax({
            url: base_url + "ajax/guardar_coordenadas/",
            type: 'post',
            asyn: true,
            data: data
        });
    });
});<|endoftext|>