text:
(function() {
  var $, AddDialog, BufferedProcess, CopyDialog, Directory, DirectoryView, File, FileView, LocalStorage, MoveDialog, ScrollView, TreeView, fs, path, shell, _, _ref,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  path = require('path');

  shell = require('shell');

  _ = require('underscore-plus');

  _ref = require('atom'), $ = _ref.$, BufferedProcess = _ref.BufferedProcess, ScrollView = _ref.ScrollView;

  fs = require('fs-plus');

  AddDialog = null;

  MoveDialog = null;

  CopyDialog = null;

  Directory = require('./directory');

  DirectoryView = require('./directory-view');

  File = require('./file');

  FileView = require('./file-view');

  LocalStorage = window.localStorage;

  module.exports = TreeView = (function(_super) {
    __extends(TreeView, _super);

    function TreeView() {
      this.resizeTreeView = __bind(this.resizeTreeView, this);
      this.resizeStopped = __bind(this.resizeStopped, this);
      this.resizeStarted = __bind(this.resizeStarted, this);
      return TreeView.__super__.constructor.apply(this, arguments);
    }

    TreeView.content = function() {
      return this.div({
        "class": 'tree-view-resizer tool-panel',
        'data-show-on-right-side': atom.config.get('tree-view.showOnRightSide')
      }, (function(_this) {
        return function() {
          _this.div({
            "class": 'tree-view-scroller',
            outlet: 'scroller'
          }, function() {
            return _this.ol({
              "class": 'tree-view full-menu list-tree has-collapsable-children focusable-panel',
              tabindex: -1,
              outlet: 'list'
            });
          });
          return _this.div({
            "class": 'tree-view-resize-handle',
            outlet: 'resizeHandle'
          });
        };
      })(this));
    };

    TreeView.prototype.initialize = function(state) {
      var focusAfterAttach, root, scrollLeftAfterAttach, scrollTopAfterAttach, selectedPath;
      TreeView.__super__.initialize.apply(this, arguments);
      focusAfterAttach = false;
      root = null;
      scrollLeftAfterAttach = -1;
      scrollTopAfterAttach = -1;
      selectedPath = null;
      this.on('dblclick', '.tree-view-resize-handle', (function(_this) {
        return function() {
          return _this.resizeToFitContent();
        };
      })(this));
      this.on('click', '.entry', (function(_this) {
        return function(e) {
          if (e.shiftKey || e.metaKey) {
            return;
          }
          return _this.entryClicked(e);
        };
      })(this));
      this.on('mousedown', '.entry', (function(_this) {
        return function(e) {
          var currentTarget, entryToSelect;
          e.stopPropagation();
          currentTarget = $(e.currentTarget);
          if (_this.multiSelectEnabled() && currentTarget.hasClass('selected') && (e.button === 2 || e.ctrlKey && process.platform === 'darwin')) {
            return;
          }
          entryToSelect = currentTarget.view();
          if (e.shiftKey) {
            _this.selectContinuousEntries(entryToSelect);
            return _this.showMultiSelectMenu();
          } else if (e.metaKey || (e.ctrlKey && process.platform !== 'darwin')) {
            _this.selectMultipleEntries(entryToSelect);
            if (_this.selectedPaths().length > 1) {
              return _this.showMultiSelectMenu();
            }
          } else {
            _this.selectEntry(entryToSelect);
            return _this.showFullMenu();
          }
        };
      })(this));
      this.off('core:move-up');
      this.off('core:move-down');
      this.on('mousedown', '.tree-view-resize-handle', (function(_this) {
        return function(e) {
          return _this.resizeStarted(e);
        };
      })(this));
      this.command('core:move-up', (function(_this) {
        return function() {
          return _this.moveUp();
        };
      })(this));
      this.command('core:move-down', (function(_this) {
        return function() {
          return _this.moveDown();
        };
      })(this));
      this.command('tree-view:expand-directory', (function(_this) {
        return function() {
          return _this.expandDirectory();
        };
      })(this));
      this.command('tree-view:collapse-directory', (function(_this) {
        return function() {
          return _this.collapseDirectory();
        };
      })(this));
      this.command('tree-view:open-selected-entry', (function(_this) {
        return function() {
          return _this.openSelectedEntry(true);
        };
      })(this));
      this.command('tree-view:move', (function(_this) {
        return function() {
          return _this.moveSelectedEntry();
        };
      })(this));
      this.command('tree-view:copy', (function(_this) {
        return function() {
          return _this.copySelectedEntries();
        };
      })(this));
      this.command('tree-view:cut', (function(_this) {
        return function() {
          return _this.cutSelectedEntries();
        };
      })(this));
      this.command('tree-view:paste', (function(_this) {
        return function() {
          return _this.pasteEntries();
        };
      })(this));
      this.command('tree-view:copy-full-path', (function(_this) {
        return function() {
          return _this.copySelectedEntryPath(false);
        };
      })(this));
      this.command('tree-view:show-in-file-manager', (function(_this) {
        return function() {
          return _this.showSelectedEntryInFileManager();
        };
      })(this));
      this.command('tree-view:copy-project-path', (function(_this) {
        return function() {
          return _this.copySelectedEntryPath(true);
        };
      })(this));
      this.command('tool-panel:unfocus', (function(_this) {
        return function() {
          return _this.unfocus();
        };
      })(this));
      this.on('tree-view:directory-modified', (function(_this) {
        return function() {
          if (_this.hasFocus()) {
            if (_this.selectedPath) {
              return _this.selectEntryForPath(_this.selectedPath);
            }
          } else {
            return _this.selectActiveFile();
          }
        };
      })(this));
      this.subscribe(atom.workspaceView, 'pane-container:active-pane-item-changed', (function(_this) {
        return function() {
          return _this.selectActiveFile();
        };
      })(this));
      this.subscribe(atom.project, 'path-changed', (function(_this) {
        return function() {
          return _this.updateRoot();
        };
      })(this));
      this.subscribe(atom.config.observe('tree-view.hideVcsIgnoredFiles', {
        callNow: false
      }, (function(_this) {
        return function() {
          return _this.updateRoot();
        };
      })(this)));
      this.subscribe(atom.config.observe('tree-view.hideIgnoredNames', {
        callNow: false
      }, (function(_this) {
        return function() {
          return _this.updateRoot();
        };
      })(this)));
      this.subscribe(atom.config.observe('core.ignoredNames', {
        callNow: false
      }, (function(_this) {
        return function() {
          if (atom.config.get('tree-view.hideIgnoredNames')) {
            return _this.updateRoot();
          }
        };
      })(this)));
      this.subscribe(atom.config.observe('tree-view.showOnRightSide', {
        callNow: false
      }, (function(_this) {
        return function(newValue) {
          return _this.onSideToggled(newValue);
        };
      })(this)));
      this.updateRoot(state.directoryExpansionStates);
      if (this.root != null) {
        this.selectEntry(this.root);
      }
      if (state.selectedPath) {
        this.selectEntryForPath(state.selectedPath);
      }
      this.focusAfterAttach = state.hasFocus;
      if (state.scrollTop) {
        this.scrollTopAfterAttach = state.scrollTop;
      }
      if (state.scrollLeft) {
        this.scrollLeftAfterAttach = state.scrollLeft;
      }
      if (state.width > 0) {
        this.width(state.width);
      }
      if (state.attached) {
        return this.attach();
      }
    };

    TreeView.prototype.afterAttach = function(onDom) {
      if (this.focusAfterAttach) {
        this.focus();
      }
      if (this.scrollLeftAfterAttach > 0) {
        this.scroller.scrollLeft(this.scrollLeftAfterAttach);
      }
      if (this.scrollTopAfterAttach > 0) {
        return this.scrollTop(this.scrollTopAfterAttach);
      }
    };

    TreeView.prototype.serialize = function() {
      var _ref1, _ref2;
      return {
        directoryExpansionStates: (_ref1 = this.root) != null ? _ref1.directory.serializeExpansionStates() : void 0,
        selectedPath: (_ref2 = this.selectedEntry()) != null ? _ref2.getPath() : void 0,
        hasFocus: this.hasFocus(),
        attached: this.hasParent(),
        scrollLeft: this.scroller.scrollLeft(),
        scrollTop: this.scrollTop(),
        width: this.width()
      };
    };

    TreeView.prototype.deactivate = function() {
      return this.remove();
    };

    TreeView.prototype.toggle = function() {
      if (this.isVisible()) {
        return this.detach();
      } else {
        return this.show();
      }
    };

    TreeView.prototype.show = function() {
      if (!this.hasParent()) {
        this.attach();
      }
      return this.focus();
    };

    TreeView.prototype.attach = function() {
      if (!atom.project.getPath()) {
        return;
      }
      if (atom.config.get('tree-view.showOnRightSide')) {
        this.removeClass('panel-left');
        this.addClass('panel-right');
        return atom.workspaceView.appendToRight(this);
      } else {
        this.removeClass('panel-right');
        this.addClass('panel-left');
        return atom.workspaceView.appendToLeft(this);
      }
    };

    TreeView.prototype.detach = function() {
      this.scrollLeftAfterAttach = this.scroller.scrollLeft();
      this.scrollTopAfterAttach = this.scrollTop();
      LocalStorage['tree-view:cutPath'] = null;
      LocalStorage['tree-view:copyPath'] = null;
      TreeView.__super__.detach.apply(this, arguments);
      return atom.workspaceView.focus();
    };

    TreeView.prototype.focus = function() {
      return this.list.focus();
    };

    TreeView.prototype.unfocus = function() {
      return atom.workspaceView.focus();
    };

    TreeView.prototype.hasFocus = function() {
      return this.list.is(':focus') || document.activeElement === this.list[0];
    };

    TreeView.prototype.toggleFocus = function() {
      if (this.hasFocus()) {
        return this.unfocus();
      } else {
        return this.show();
      }
    };

    TreeView.prototype.entryClicked = function(e) {
      var entry, _ref1, _ref2, _ref3;
      entry = $(e.currentTarget).view();
      switch ((_ref1 = (_ref2 = e.originalEvent) != null ? _ref2.detail : void 0) != null ? _ref1 : 1) {
        case 1:
          this.selectEntry(entry);
          if (entry instanceof FileView) {
            this.openSelectedEntry(false);
          }
          if (entry instanceof DirectoryView) {
            entry.toggleExpansion();
          }
          break;
        case 2:
          if (entry.is('.selected.file')) {
            if ((_ref3 = atom.workspaceView.getActiveView()) != null) {
              _ref3.focus();
            }
          } else if (entry.is('.selected.directory')) {
            entry.toggleExpansion();
          }
      }
      return false;
    };

    TreeView.prototype.resizeStarted = function() {
      $(document.body).on('mousemove', this.resizeTreeView);
      return $(document.body).on('mouseup', this.resizeStopped);
    };

    TreeView.prototype.resizeStopped = function() {
      $(document.body).off('mousemove', this.resizeTreeView);
      return $(document.body).off('mouseup', this.resizeStopped);
    };

    TreeView.prototype.resizeTreeView = function(_arg) {
      var pageX, width;
      pageX = _arg.pageX;
      if (atom.config.get('tree-view.showOnRightSide')) {
        width = $(document.body).width() - pageX;
      } else {
        width = pageX;
      }
      return this.width(width);
    };

    TreeView.prototype.resizeToFitContent = function() {
      this.width(1);
      return this.width(this.list.outerWidth());
    };

    TreeView.prototype.updateRoot = function(expandedEntries) {
      var directory, rootDirectory, _ref1;
      if (expandedEntries == null) {
        expandedEntries = {};
      }
      if ((_ref1 = this.root) != null) {
        _ref1.remove();
      }
      if (rootDirectory = atom.project.getRootDirectory()) {
        directory = new Directory({
          directory: rootDirectory,
          isExpanded: true,
          expandedEntries: expandedEntries,
          isRoot: true
        });
        this.root = new DirectoryView(directory);
        return this.list.append(this.root);
      } else {
        return this.root = null;
      }
    };

    TreeView.prototype.getActivePath = function() {
      var _ref1;
      return (_ref1 = atom.workspace.getActivePaneItem()) != null ? typeof _ref1.getPath === "function" ? _ref1.getPath() : void 0 : void 0;
    };

    TreeView.prototype.selectActiveFile = function() {
      var activeFilePath;
      if (activeFilePath = this.getActivePath()) {
        return this.selectEntryForPath(activeFilePath);
      } else {
        return this.deselect();
      }
    };

    TreeView.prototype.revealActiveFile = function() {
      var activeFilePath, activePathComponents, centeringOffset, currentPath, entry, pathComponent, _i, _len, _results;
      if (!atom.project.getPath()) {
        return;
      }
      this.attach();
      this.focus();
      if (!(activeFilePath = this.getActivePath())) {
        return;
      }
      activePathComponents = atom.project.relativize(activeFilePath).split(path.sep);
      currentPath = atom.project.getPath().replace(new RegExp("" + (_.escapeRegExp(path.sep)) + "$"), '');
      _results = [];
      for (_i = 0, _len = activePathComponents.length; _i < _len; _i++) {
        pathComponent = activePathComponents[_i];
        currentPath += path.sep + pathComponent;
        entry = this.entryForPath(currentPath);
        if (entry.hasClass('directory')) {
          _results.push(entry.expand());
        } else {
          centeringOffset = (this.scrollBottom() - this.scrollTop()) / 2;
          this.selectEntry(entry);
          _results.push(this.scrollToEntry(entry, centeringOffset));
        }
      }
      return _results;
    };

    TreeView.prototype.copySelectedEntryPath = function(relativePath) {
      var pathToCopy;
      if (relativePath == null) {
        relativePath = false;
      }
      if (pathToCopy = this.selectedPath) {
        if (relativePath) {
          pathToCopy = atom.project.relativize(pathToCopy);
        }
        return atom.clipboard.write(pathToCopy);
      }
    };

    TreeView.prototype.entryForPath = function(entryPath) {
      var fn;
      fn = function(bestMatchEntry, element) {
        var entry, _ref1;
        entry = $(element).view();
        if (entry.getPath() === entryPath) {
          return entry;
        } else if (entry.getPath().length > bestMatchEntry.getPath().length && ((_ref1 = entry.directory) != null ? _ref1.contains(entryPath) : void 0)) {
          return entry;
        } else {
          return bestMatchEntry;
        }
      };
      return this.list.find(".entry").toArray().reduce(fn, this.root);
    };

    TreeView.prototype.selectEntryForPath = function(entryPath) {
      return this.selectEntry(this.entryForPath(entryPath));
    };

    TreeView.prototype.moveDown = function() {
      var selectedEntry;
      selectedEntry = this.selectedEntry();
      if (selectedEntry) {
        if (selectedEntry.is('.expanded.directory')) {
          if (this.selectEntry(selectedEntry.find('.entry:first'))) {
            this.scrollToEntry(this.selectedEntry());
            return;
          }
        }
        while (!this.selectEntry(selectedEntry.next('.entry'))) {
          selectedEntry = selectedEntry.parents('.entry:first');
          if (!selectedEntry.length) {
            break;
          }
        }
      } else {
        this.selectEntry(this.root);
      }
      return this.scrollToEntry(this.selectedEntry());
    };

    TreeView.prototype.moveUp = function() {
      var previousEntry, selectedEntry;
      selectedEntry = this.selectedEntry();
      if (selectedEntry) {
        if (previousEntry = this.selectEntry(selectedEntry.prev('.entry'))) {
          if (previousEntry.is('.expanded.directory')) {
            this.selectEntry(previousEntry.find('.entry:last'));
          }
        } else {
          this.selectEntry(selectedEntry.parents('.directory').first());
        }
      } else {
        this.selectEntry(this.list.find('.entry').last());
      }
      return this.scrollToEntry(this.selectedEntry());
    };

    TreeView.prototype.expandDirectory = function() {
      var selectedEntry;
      selectedEntry = this.selectedEntry();
      if (selectedEntry instanceof DirectoryView) {
        return selectedEntry.view().expand();
      }
    };

    TreeView.prototype.collapseDirectory = function() {
      var directory, _ref1;
      if (directory = (_ref1 = this.selectedEntry()) != null ? _ref1.closest('.expanded.directory').view() : void 0) {
        directory.collapse();
        return this.selectEntry(directory);
      }
    };

    TreeView.prototype.openSelectedEntry = function(changeFocus) {
      var selectedEntry;
      selectedEntry = this.selectedEntry();
      if (selectedEntry instanceof DirectoryView) {
        return selectedEntry.view().toggleExpansion();
      } else if (selectedEntry instanceof FileView) {
        return atom.workspaceView.open(selectedEntry.getPath(), {
          changeFocus: changeFocus
        });
      }
    };

    TreeView.prototype.moveSelectedEntry = function() {
      var dialog, entry, oldPath;
      entry = this.selectedEntry();
      if (!(entry && entry !== this.root)) {
        return;
      }
      oldPath = entry.getPath();
      if (MoveDialog == null) {
        MoveDialog = require('./move-dialog');
      }
      dialog = new MoveDialog(oldPath);
      return dialog.attach();
    };

    TreeView.prototype.fileManagerCommandForPath = function(pathToOpen, isFile) {
      switch (process.platform) {
        case 'darwin':
          return {
            command: 'open',
            label: 'Finder',
            args: ['-R', pathToOpen]
          };
        case 'win32':
          return {
            command: 'cmd.exe',
            label: 'Explorer',
            args: ['/c', 'start', 'explorer.exe', pathToOpen]
          };
        default:
          if (isFile) {
            pathToOpen = path.dirname(pathToOpen);
          }
          return {
            command: 'xdg-open',
            label: 'File Manager',
            args: [pathToOpen]
          };
      }
    };

    TreeView.prototype.showSelectedEntryInFileManager = function() {
      var args, command, entry, errorLines, exit, label, stderr, _ref1;
      entry = this.selectedEntry();
      if (!entry) {
        return;
      }
      _ref1 = this.fileManagerCommandForPath(entry.getPath(), entry instanceof FileView), command = _ref1.command, args = _ref1.args, label = _ref1.label;
      errorLines = [];
      stderr = function(lines) {
        return errorLines.push(lines);
      };
      exit = function(code) {
        if (code !== 0) {
          return atom.confirm({
            message: "Opening " + entryType + " in " + label + " failed",
            detailedMessage: errorLines.join('\n'),
            buttons: ['OK']
          });
        }
      };
      return new BufferedProcess({
        command: command,
        args: args,
        stderr: stderr,
        exit: exit
      });
    };

    TreeView.prototype.copySelectedEntry = function() {
      var dialog, entry, oldPath;
      if (this.hasFocus()) {
        entry = this.selectedEntry();
        if (entry === root) {
          return;
        }
        oldPath = entry.getPath();
      } else {
        oldPath = this.getActivePath();
      }
      if (!oldPath) {
        return;
      }
      if (CopyDialog == null) {
        CopyDialog = require('./copy-dialog');
      }
      dialog = new CopyDialog(oldPath);
      return dialog.attach();
    };

    TreeView.prototype.removeSelectedEntries = function() {
      var activePath, selectedPaths;
      if (this.hasFocus()) {
        selectedPaths = this.selectedPaths();
      } else if (activePath = this.getActivePath()) {
        selectedPaths = [activePath];
      }
      if (!selectedPaths) {
        return;
      }
      return atom.confirm({
        message: "Are you sure you want to delete the selected " + (selectedPaths.length > 1 ? 'items' : 'item') + "?",
        detailedMessage: "You are deleting:\n" + (selectedPaths.join('\n')),
        buttons: {
          "Move to Trash": function() {
            var selectedPath, _i, _len, _results;
            _results = [];
            for (_i = 0, _len = selectedPaths.length; _i < _len; _i++) {
              selectedPath = selectedPaths[_i];
              _results.push(shell.moveItemToTrash(selectedPath));
            }
            return _results;
          },
          "Cancel": null,
          "Delete": (function(_this) {
            return function() {
              var selectedPath, _i, _len, _results;
              _results = [];
              for (_i = 0, _len = selectedPaths.length; _i < _len; _i++) {
                selectedPath = selectedPaths[_i];
                _results.push(_this.removeSync(selectedPath));
              }
              return _results;
            };
          })(this)
        }
      });
    };

    TreeView.prototype.removeSync = function(pathToRemove) {
      var error, removed, runas;
      try {
        return fs.removeSync(pathToRemove);
      } catch (_error) {
        error = _error;
        if (error.code === 'EACCES' && process.platform === 'darwin') {
          runas = require('runas');
          removed = runas('/bin/rm', ['-r', '-f', pathToRemove], {
            admin: true
          }) === 0;
          if (!removed) {
            throw error;
          }
        } else {
          throw error;
        }
      }
    };

    TreeView.prototype.copySelectedEntries = function() {
      var selectedPaths;
      selectedPaths = this.selectedPaths();
      if (!(selectedPaths && selectedPaths.length > 0)) {
        return;
      }
      LocalStorage.removeItem('tree-view:cutPath');
      return LocalStorage['tree-view:copyPath'] = JSON.stringify(selectedPaths);
    };

    TreeView.prototype.cutSelectedEntries = function() {
      var selectedPaths;
      selectedPaths = this.selectedPaths();
      if (!(selectedPaths && selectedPaths.length > 0)) {
        return;
      }
      LocalStorage.removeItem('tree-view:copyPath');
      return LocalStorage['tree-view:cutPath'] = JSON.stringify(selectedPaths);
    };

    TreeView.prototype.pasteEntries = function() {
      var basePath, copiedPaths, cutPaths, entry, entryType, fileArr, fileCounter, initialPath, initialPathIsDirectory, initialPaths, newPath, originalNewPath, _i, _len, _ref1, _results;
      entry = this.selectedEntry();
      cutPaths = LocalStorage['tree-view:cutPath'] ? JSON.parse(LocalStorage['tree-view:cutPath']) : null;
      copiedPaths = LocalStorage['tree-view:copyPath'] ? JSON.parse(LocalStorage['tree-view:copyPath']) : null;
      initialPaths = copiedPaths || cutPaths;
      _ref1 = initialPaths != null ? initialPaths : [];
      _results = [];
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        initialPath = _ref1[_i];
        initialPathIsDirectory = fs.isDirectorySync(initialPath);
        if (entry && initialPath) {
          basePath = atom.project.resolve(entry.getPath());
          entryType = entry instanceof DirectoryView ? "directory" : "file";
          if (entryType === 'file') {
            basePath = path.dirname(basePath);
          }
          newPath = path.join(basePath, path.basename(initialPath));
          if (copiedPaths) {
            fileCounter = 0;
            originalNewPath = newPath;
            while (fs.existsSync(newPath)) {
              if (initialPathIsDirectory) {
                newPath = "" + originalNewPath + (fileCounter.toString());
              } else {
                fileArr = originalNewPath.split('.');
                newPath = "" + fileArr[0] + (fileCounter.toString()) + "." + fileArr[1];
              }
              fileCounter += 1;
            }
            if (fs.isDirectorySync(initialPath)) {
              _results.push(fs.copySync(initialPath, newPath));
            } else {
              _results.push(fs.writeFileSync(newPath, fs.readFileSync(initialPath)));
            }
          } else if (cutPaths) {
            if (!(fs.existsSync(newPath) || !!newPath.match(new RegExp("^" + initialPath)))) {
              _results.push(fs.moveSync(initialPath, newPath));
            } else {
              _results.push(void 0);
            }
          } else {
            _results.push(void 0);
          }
        } else {
          _results.push(void 0);
        }
      }
      return _results;
    };

    TreeView.prototype.add = function(isCreatingFile) {
      var dialog, selectedEntry, selectedPath;
      selectedEntry = this.selectedEntry() || this.root;
      selectedPath = selectedEntry.getPath();
      if (AddDialog == null) {
        AddDialog = require('./add-dialog');
      }
      dialog = new AddDialog(selectedPath, isCreatingFile);
      dialog.on('directory-created', (function(_this) {
        return function(event, createdPath) {
          _this.entryForPath(createdPath).reload();
          _this.selectEntryForPath(createdPath);
          return false;
        };
      })(this));
      dialog.on('file-created', function(event, createdPath) {
        atom.workspace.open(createdPath);
        return false;
      });
      return dialog.attach();
    };

    TreeView.prototype.selectedEntry = function() {
      var _ref1;
      return (_ref1 = this.list.find('.selected')) != null ? _ref1.view() : void 0;
    };

    TreeView.prototype.selectEntry = function(entry) {
      entry = entry != null ? entry.view() : void 0;
      if (entry == null) {
        return false;
      }
      this.selectedPath = entry.getPath();
      this.deselect();
      return entry.addClass('selected');
    };

    TreeView.prototype.deselect = function() {
      return this.list.find('.selected').removeClass('selected');
    };

    TreeView.prototype.scrollTop = function(top) {
      if (top != null) {
        return this.scroller.scrollTop(top);
      } else {
        return this.scroller.scrollTop();
      }
    };

    TreeView.prototype.scrollBottom = function(bottom) {
      if (bottom != null) {
        return this.scroller.scrollBottom(bottom);
      } else {
        return this.scroller.scrollBottom();
      }
    };

    TreeView.prototype.scrollToEntry = function(entry, offset) {
      var bottom, displayElement, top;
      if (offset == null) {
        offset = 0;
      }
      displayElement = entry instanceof DirectoryView ? entry.header : entry;
      top = displayElement.position().top;
      bottom = top + displayElement.outerHeight();
      if (bottom > this.scrollBottom()) {
        this.scrollBottom(bottom + offset);
      }
      if (top < this.scrollTop()) {
        return this.scrollTop(top + offset);
      }
    };

    TreeView.prototype.scrollToBottom = function() {
      var lastEntry, _ref1;
      if (lastEntry = (_ref1 = this.root) != null ? _ref1.find('.entry:last').view() : void 0) {
        this.selectEntry(lastEntry);
        return this.scrollToEntry(lastEntry);
      }
    };

    TreeView.prototype.scrollToTop = function() {
      if (this.root != null) {
        this.selectEntry(this.root);
      }
      return this.scrollTop(0);
    };

    TreeView.prototype.toggleSide = function() {
      return atom.config.toggle('tree-view.showOnRightSide');
    };

    TreeView.prototype.onSideToggled = function(newValue) {
      this.detach();
      this.attach();
      return this.attr('data-show-on-right-side', newValue);
    };

    TreeView.prototype.selectedPaths = function() {
      var item, _i, _len, _ref1, _results;
      _ref1 = this.list.find('.selected');
      _results = [];
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        item = _ref1[_i];
        _results.push($(item).view().getPath());
      }
      return _results;
    };

    TreeView.prototype.selectContinuousEntries = function(entry) {
      var currentSelectedEntry, element, elements, entryIndex, i, parentContainer, selectedIndex, _i, _len;
      currentSelectedEntry = this.selectedEntry();
      parentContainer = entry.parent();
      if ($.contains(parentContainer[0], currentSelectedEntry[0])) {
        entryIndex = parentContainer.indexOf(entry);
        selectedIndex = parentContainer.indexOf(currentSelectedEntry);
        elements = (function() {
          var _i, _results;
          _results = [];
          for (i = _i = entryIndex; entryIndex <= selectedIndex ? _i <= selectedIndex : _i >= selectedIndex; i = entryIndex <= selectedIndex ? ++_i : --_i) {
            _results.push(parentContainer.children()[i]);
          }
          return _results;
        })();
        this.deselect();
        for (_i = 0, _len = elements.length; _i < _len; _i++) {
          element = elements[_i];
          $(element).addClass('selected');
        }
      }
      return elements;
    };

    TreeView.prototype.selectMultipleEntries = function(entry) {
      entry = entry != null ? entry.view() : void 0;
      if (entry == null) {
        return false;
      }
      entry.addClass('selected');
      return entry;
    };

    TreeView.prototype.showFullMenu = function() {
      return this.list.removeClass('multi-select').addClass('full-menu');
    };

    TreeView.prototype.showMultiSelectMenu = function() {
      return this.list.removeClass('full-menu').addClass('multi-select');
    };

    TreeView.prototype.multiSelectEnabled = function() {
      return this.list.hasClass('multi-select');
    };

    return TreeView;

  })(ScrollView);

}).call(this);


text:
**Link to paper:[https://arxiv.org/pdf/1805.10408](https://arxiv.org/pdf/1805.10408 "The Singular Values of Convolutional Layers")**

Overview
======

We characterize the singular values of the linear transformation associated with a convolution applied to a two-dimensional feature map with multiple channels. Our characterization enables efficient computation of the singular values of convolutional layers used in popular deep neural network architectures. It also leads to an algorithm for projecting a convolutional layer onto the set of layers obeying a bound on the operator norm of the layer.

Here, we provide the code for

* Our new method for calculating the singular values for 2D multi-channel conovlutional layers.
* Time test comparing different methods for calculating the singular values.
* Sketching the singular values for any trained model.
* projecting a convolutional layer onto the set of layers obeying a bound on the operator norm of the layer.

### How do I get set up? ###

Requirements

+ Tensorflow
+ Numpy

## Citation ##

If you use this code, please cite our paper:

```
@article{
  sedghi2018singular,
  title={The Singular Values of Convolutional Layers},
  author={Sedghi, Hanie and Gupta, Vineet and Long, Philip M},
  journal={arXiv preprint arXiv:1805.10408},
  year={2018}
}
```

Authors
======

* Hanie Sedghi ([hsedghi@google.com](hsedghi@google.com "mailto:hsedghi@google.com"))

* Vineet Gupta ([vineet@google.com](vineet@google.com "mailto:vineet@google.com"))

* Phil Long ([plong@google.com](plong@google.com "mailto:plong@google.com"))

This is not an officially supported Google Product.

redpajama_set_name: RedPajamaGithub


text:
using namespace sectorized;

class SectorizedEntity :
	public Entity
{
private:
	sector pSector;
public:
	SectorizedEntity();
	virtual ~SectorizedEntity();
	void setSector(sector iSector);
	sector getSector();
};


text:
/*
 *  Rest client module
 */

// #region dependents

var rest = require('restler');
var _ = require('lodash');

module.exports = function init(config, log, events, scheme, errors) {
    // #region initialization

    var logger = log.getLogger(module);

    var options = {
        baseURL: config.server.url + ":" + config.server.port
    };

    var actions = {
        authorizeApp: _authorizeApp,
        userLogin: _userLogin,
        userLogout: _userLogout,
        isExistSession: _isExistSession,
        create: _create,
        update: _update,
        remove: _remove,
        read: _read,
        readAll: _readAll
    };

    var instance = { };

    return rest.service(_constructor, options, actions);

    // #region private methods

    /*
     *  Calls when proxy client instance have create.
     */
    function _constructor(appId, appSecret, storage) {
        this.defaults.appId = appId;
        this.defaults.appSecret = appSecret;
        this.defaults.storage = storage;

        instance = this;
    }

    function _authorizeApp(done) {
        var appAuthInfo = { appId: this.defaults.appId, appSecret: this.defaults.appSecret };
        var context = { data: appAuthInfo };

        sendRequest('post', 'AppAuth', context, successCallback, done);

        function successCallback(data) {
            var storage = instance.defaults.storage;

            storage.saveAppToken(data.token);
            if (data.sessions && data.sessions.length) {
                storage.init(data.sessions, "_id", "context");
            }

            logger.debug("Access token for application '" + instance.defaults.appId + "' was saved in storage.");

            if (done) done(null, data);
        }
    }

    function _userLogin(username, password, done) {
        var context = {
            data: {
                cred: { username: username, password: password }
            },
            headers: {
                appId: instance.defaults.appId,
                token: instance.defaults.storage.getAppToken()
            }
        };

        sendRequest('post', 'UserLogin', context, successCallback, done);

        function successCallback(result) {
            instance.defaults.storage.addSession(result.sessionId, result);

            logger.debug("User login session \n", result, " was saved in storage.");

            if (done) done(null, result);
        }
    }

    function _userLogout(session, done) {
        var context = {
            data: {
                cred: instance.defaults.storage.getSessionSync(session)
            },
            headers: {
                appId: instance.defaults.appId,
                token: instance.defaults.storage.getAppToken()
            }
        };

        sendRequest('post', 'UserLogout', context, successCallback, done);

        function successCallback(result) {
            instance.defaults.storage.removeSession(result.sessionId);
            logger.debug("User login session ", result, " was removed from storage.");

            if (done) done(null, result);
        }
    }

    function _isExistSession(session, done) {
        instance.defaults.storage.getSession(session, function (err, session) {
            if (err) done(err);

            if (!session) {
                return done(new errors.AuthError(401, "Session not found"));
            }

            return done(null, session);
        });
    }

    function _create(modelName, model, sessionId, done) {
        sendAuthenticatedRequest('post', modelName, { data: model }, successCallback, sessionId, done);

        function successCallback(result) {
            logger.debug(modelName, "(id = ", result.id, ") was created.");

            if (done) done(null, result);
        }
    }

    function _update(modelName, id, model, sessionId, done) {
        var context = { data: model };
        sendAuthenticatedRequest('put', modelName, context, successCallback, sessionId, done, id);

        function successCallback(result) {
            logger.debug(modelName, "(id = ", id, ") was updated.");

            if (done) done(null, result);
        }
    }

    function _remove(modelName, id, sessionId, done) {
        sendAuthenticatedRequest('del', modelName, { }, successCallback, sessionId, done, id);

        function successCallback(result) {
            logger.debug(modelName, "was deleted.");

            if (done) done(null, result);
        }
    }

    function _read(modelName, query, sessionId, done) {
        sendAuthenticatedRequest('get', modelName, { query: query }, successCallback, sessionId, done, query.id);

        function successCallback(result) {
            logger.debug("Response received successfully. \n", result);

            if (done) done(null, result);
        }
    }

    function _readAll(modelName, query, sessionId, done) {
        sendAuthenticatedRequest('get', modelName, query, successCallback, sessionId, done);

        function successCallback(result) {
            logger.debug("Response received successfully. \n", result);

            if (done) done(null, result);
        }
    }

    function sendAuthenticatedRequest(method, modelName, context, successCallback, sessionId, done, urlPart) {
        var credentials = instance.defaults.storage.getSessionSync(sessionId);
        var headers = {
            appId: instance.defaults.appId,
            token: instance.defaults.storage.getAppToken(),
            session: credentials.sessionId
        };

        context = _.extend(context, { headers: headers });

        sendRequest(method, modelName, context, successCallback, done, urlPart);
    }

    function sendRequest(method, modelName, context, successCallback, done, urlPart) {
        var eventCallbacks = _getDefaultEventCallbacks(successCallback, done);

        return _sendRequestWithCallbacks(method, modelName, context, eventCallbacks, urlPart);
    }

    function _getDefaultEventCallbacks(successCallback, done) {
        var eventCallbacks = { };
        eventCallbacks[events.Success] = successCallback;
        eventCallbacks[events.Fail] = _getFailCallback(done);

        //eventCallbacks[events.Complete] = _completeCallback; // for debug

        return eventCallbacks;
    }

    function _sendRequestWithCallbacks(method, modelName, context, eventCallbacks, urlPart) {
        var urlPath = scheme[modelName];

        var request = instance[method](urlPath + '/' + (urlPart || ''), context);

        _setCallbacksForRequest(request, eventCallbacks);

        return request;
    }

    function _setCallbacksForRequest(request, eventCallbacks) {
        _.each(eventCallbacks, function (callback, event) {
            request.on(event, callback);
        });
    }

    function _getFailCallback(callback) {
        return function failCallback(res) {
            logger.error(res.error);

            if (callback) callback(res.error);
        }
    }

    function _completeCallback(res) {
        logger.debug(res);
    }
};


text:
namespace acid {
ZipArchive::ZipArchive(const std::filesystem::path &filename) :
	archivePath(filename) {
	std::ifstream f(filename.c_str());
	if (f.good()) {
		f.close();
		Open(filename);
	} else {
		f.close();
		Create(filename);
	}
}

ZipArchive::~ZipArchive() {
	Close();
}

void ZipArchive::Create(const std::filesystem::path &filename) {
	auto filenameU8 = filename.u8string();

	// Prepare an archive file;
	mz_zip_archive archive = {};
	mz_zip_writer_init_file(&archive, filenameU8.c_str(), 0);

	// Finalize and close the temporary archive
	mz_zip_writer_finalize_archive(&archive);
	mz_zip_writer_end(&archive);

	// Validate the temporary file
	mz_zip_error errorData;
	if (!mz_zip_validate_file_archive(filenameU8.c_str(), 0, &errorData))
		ThrowException(errorData, "Archive creation failed!");

	Open(filename);
}

void ZipArchive::Open(const std::filesystem::path &filename) {
	// Open the archive file for reading.
	if (isOpen)
		mz_zip_reader_end(&archive);
	archivePath = filename;
	auto archivePathU8 = archivePath.u8string();
	if (!mz_zip_reader_init_file(&archive, archivePathU8.c_str(), 0))
		ThrowException(archive.m_last_error, "Error opening archive file " + archivePathU8 + ".");
	isOpen = true;

	// Iterate through the archive and add the entries to the internal data structure
	for (unsigned int i = 0; i < mz_zip_reader_get_num_files(&archive); i++) {
		ZipEntryInfo info;
		if (!mz_zip_reader_file_stat(&archive, i, &info))
			ThrowException(archive.m_last_error, "Failed getting entry info.");
		zipEntries.emplace_back(std::make_unique<ZipEntry>(info));
	}

	// Remove entries with identical names. The newest entries will be retained.
	auto isEqual = [](const auto &a, const auto &b) { return a->GetFilename() == b->GetFilename(); };
	std::reverse(zipEntries.begin(), zipEntries.end());
	zipEntries.erase(std::unique(zipEntries.begin(), zipEntries.end(), isEqual), zipEntries.end());
	std::reverse(zipEntries.begin(), zipEntries.end());
}

void ZipArchive::Close() {
	if (isOpen)
		mz_zip_reader_end(&archive);
	zipEntries.clear();
	archivePath = "";
}

std::vector<std::string> ZipArchive::GetEntryNames(bool includeDirs, bool includeFiles) const {
	std::vector<std::string> result;
	for (const auto &item : zipEntries) {
		if (includeDirs && item->IsDirectory()) {
			result.emplace_back(item->GetFilename());
			continue;
		}

		if (includeFiles && !item->IsDirectory()) {
			result.emplace_back(item->GetFilename());
			continue;
		}
	}
	return result;
}

std::vector<std::string> ZipArchive::GetEntryNamesInDir(const std::string &dir, bool includeDirs, bool includeFiles) const {
	auto result = GetEntryNames(includeDirs, includeFiles);

	if (dir.empty())
		return result;

	auto theDir = dir;
	if (theDir.back() != '/')
		theDir += '/';

	result.erase(std::remove_if(result.begin(), result.end(), [&](const std::string &filename) {
		return filename.substr(0, theDir.size()) != theDir || filename == theDir;
	}), result.end());

	return result;
}

std::vector<ZipEntryMetaData> ZipArchive::GetMetaData(bool includeDirs, bool includeFiles) const {
	std::vector<ZipEntryMetaData> result;
	for (const auto &item : zipEntries) {
		if (includeDirs && item->IsDirectory()) {
			result.emplace_back(ZipEntryMetaData(item->entryInfo));
			continue;
		}

		if (includeFiles && !item->IsDirectory()) {
			result.emplace_back(ZipEntryMetaData(item->entryInfo));
			continue;
		}
	}

	return result;
}

std::vector<ZipEntryMetaData> ZipArchive::GetMetaDataInDir(const std::string &dir, bool includeDirs, bool includeFiles) const {
	std::vector<ZipEntryMetaData> result;
	for (const auto &item : zipEntries) {
		if (item->GetFilename().substr(0, dir.size()) != dir)
			continue;

		if (includeDirs && item->IsDirectory()) {
			result.emplace_back(ZipEntryMetaData(item->entryInfo));
			continue;
		}

		if (includeFiles && !item->IsDirectory()) {
			result.emplace_back(ZipEntryMetaData(item->entryInfo));
			continue;
		}
	}

	return result;
}

int ZipArchive::GetNumEntries(bool includeDirs, bool includeFiles) const {
	return GetEntryNames(includeDirs, includeFiles).size();
}

int ZipArchive::GetNumEntriesInDir(const std::string &dir, bool includeDirs, bool includeFiles) const {
	return GetEntryNamesInDir(dir, includeDirs, includeFiles).size();
}

bool ZipArchive::HasEntry(const std::string &entryName) const {
	auto result = GetEntryNames(true, true);
	return std::find(result.begin(), result.end(), entryName) != result.end();
}

void ZipArchive::Write(std::filesystem::path filename) {
	if (filename.empty())
		filename = archivePath;

	// Generate a random file name with the same path as the current file
	auto tempPath = filename.parent_path() / GenerateRandomName(20);
	auto tempPathU8 = tempPath.u8string();

	// Prepare an temporary archive file with the random filename;
	mz_zip_archive tempArchive = {};
	mz_zip_writer_init_file(&tempArchive, tempPathU8.c_str(), 0);

	// Iterate through the ZipEntries and add entries to the temporary file
	for (const auto &file : zipEntries) {
		if (!file->IsModified()) {
			if (!mz_zip_writer_add_from_zip_reader(&tempArchive, &archive, file->GetIndex()))
				ThrowException(archive.m_last_error, "Failed copying archive entry.");
		} else {
			if (!mz_zip_writer_add_mem(&tempArchive, file->GetFilename().c_str(), file->entryData.data(), file->entryData.size(), MZ_DEFAULT_COMPRESSION))
				ThrowException(archive.m_last_error, "Failed adding archive entry.");
		}
	}

	// Finalize and close the temporary archive
	mz_zip_writer_finalize_archive(&tempArchive);
	mz_zip_writer_end(&tempArchive);

	// Validate the temporary file
	mz_zip_error errordata;
	if (!mz_zip_validate_file_archive(tempPathU8.c_str(), 0, &errordata))
		ThrowException(errordata, "Invalid archive");

	// Close the current archive, delete the file with input filename (if it exists), rename the temporary and call Open.
	Close();
	std::filesystem::remove(filename);
	std::filesystem::rename(tempPath, filename);
	Open(filename);

}

void ZipArchive::Write(std::ostream &stream) {
	// TODO: Implement
}

void ZipArchive::DeleteEntry(const std::string &name) {
	zipEntries.erase(std::remove_if(zipEntries.begin(), zipEntries.end(), [&](const auto &entry) {
		return name == entry->GetFilename();
	}), zipEntries.end());
}

ZipEntry *ZipArchive::GetEntry(const std::string &name) {
	// Look up ZipEntry object.
	const auto &result = std::find_if(zipEntries.begin(), zipEntries.end(), [&](const auto &entry) {
		return name == entry->GetFilename();
	});

	// Extract the data from the archive to the ZipEntry object.
	(*result)->entryData.resize(static_cast<std::size_t>((*result)->GetUncompressedSize()));
	mz_zip_reader_extract_file_to_mem(&archive, name.c_str(), (*result)->entryData.data(), (*result)->entryData.size(), 0);

	// Check that the operation was successful
	if (!(*result)->entryData.data())
		ThrowException(archive.m_last_error, "Error extracting archive entry.");

	// Return ZipEntry object with the file data.
	return (*result).get();
}

void ZipArchive::ExtractEntry(const std::string &name, const std::filesystem::path &dest) {
	// Look up ZipEntry object.
	const auto &result = std::find_if(zipEntries.begin(), zipEntries.end(), [&](const auto &entry) {
		return name == entry->GetFilename();
	});

	if (auto parentPath = dest.parent_path(); !parentPath.empty()) {
		std::filesystem::create_directories(parentPath);
	}

	auto destU8 = dest.u8string();

	// Extract the data from the archive to the ZipEntry object.
	(*result)->entryData.resize((*result)->GetUncompressedSize());
	mz_zip_reader_extract_file_to_file(&archive, name.c_str(), destU8.c_str(), 0);

	// Check that the operation was successful
	if (!(*result)->entryData.data())
		ThrowException(archive.m_last_error, "Error extracting archive entry.");
}

void ZipArchive::ExtractDir(const std::string &dir, const std::filesystem::path &dest) {
	for (const auto &entry : GetEntryNames(false)) {
		if (String::StartsWith(entry, dir))
			ExtractEntry(entry, dest / String::ReplaceFirst(entry, dir + "/", ""));
	}
}

void ZipArchive::ExtractAll(const std::filesystem::path &dest) {
	for (const auto &entry : GetEntryNames(false)) {
		ExtractEntry(entry, dest / entry);
	}
}

ZipEntry *ZipArchive::AddEntry(const std::string &name, const ZipEntryData &data) {
	// Check if an entry with the given name already exists in the archive.
	auto result = std::find_if(zipEntries.begin(), zipEntries.end(), [&](const auto &entry) {
		return name == entry->GetFilename();
	});

	// If the entry exists, replace the existing data with the new data, and return the ZipEntry object.
	if (result != zipEntries.end()) {
		(*result)->SetData(data);
		return (*result).get();
	}

	// Otherwise, add a new entry with the given name and data, and return the object.
	return zipEntries.emplace_back(std::make_unique<ZipEntry>(name, data)).get();
}

ZipEntry *ZipArchive::AddEntry(const std::string &name, const std::string &data) {
	// Check if an entry with the given name already exists in the archive.
	auto result = std::find_if(zipEntries.begin(), zipEntries.end(), [&](const auto &entry) {
		return name == entry->GetFilename();
	});

	// If the entry exists, replace the existing data with the new data, and return the ZipEntry object.
	if (result != zipEntries.end()) {
		(*result)->SetData(data);
		return (*result).get();
	}

	// Otherwise, add a new entry with the given name and data, and return the object.
	return zipEntries.emplace_back(std::make_unique<ZipEntry>(name, data)).get();
}

ZipEntry *ZipArchive::AddEntry(const std::string &name, const ZipEntry &entry) {
	// TODO: Ensure to check for self-asignment.
	// Check if an entry with the given name already exists in the archive.
	auto result = std::find_if(zipEntries.begin(), zipEntries.end(), [&](const auto &entry) {
		return name == entry->GetFilename();
	});

	// If the entry exists, replace the existing data with the new data, and return the ZipEntry object.
	if (result != zipEntries.end()) {
		(*result)->SetData(entry.GetData());
		return (*result).get();
	}

	// Otherwise, add a new entry with the given name and data, and return the object.
	return zipEntries.emplace_back(std::make_unique<ZipEntry>(name, entry.GetData())).get();
}

void ZipArchive::ThrowException(mz_zip_error error, const std::string &errorString) {
	switch (error) {
	case MZ_ZIP_UNDEFINED_ERROR:
		throw ZipExceptionUndefined(errorString);
	case MZ_ZIP_TOO_MANY_FILES:
		throw ZipExceptionTooManyFiles(errorString);
	case MZ_ZIP_FILE_TOO_LARGE:
		throw ZipExceptionFileTooLarge(errorString);
	case MZ_ZIP_UNSUPPORTED_METHOD:
		throw ZipExceptionUnsupportedMethod(errorString);
	case MZ_ZIP_UNSUPPORTED_ENCRYPTION:
		throw ZipExceptionUnsupportedEncryption(errorString);
	case MZ_ZIP_UNSUPPORTED_FEATURE:
		throw ZipExceptionUnsupportedFeature(errorString);
	case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR:
		throw ZipExceptionFailedFindingCentralDir(errorString);
	case MZ_ZIP_NOT_AN_ARCHIVE:
		throw ZipExceptionNotAnArchive(errorString);
	case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED:
		throw ZipExceptionInvalidHeader(errorString);
	case MZ_ZIP_UNSUPPORTED_MULTIDISK:
		throw ZipExceptionMultidiskUnsupported(errorString);
	case MZ_ZIP_DECOMPRESSION_FAILED:
		throw ZipExceptionDecompressionFailed(errorString);
	case MZ_ZIP_COMPRESSION_FAILED:
		throw ZipExceptionCompressionFailed(errorString);
	case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE:
		throw ZipExceptionUnexpectedDecompSize(errorString);
	case MZ_ZIP_CRC_CHECK_FAILED:
		throw ZipExceptionCrcCheckFailed(errorString);
	case MZ_ZIP_UNSUPPORTED_CDIR_SIZE:
		throw ZipExceptionUnsupportedCDirSize(errorString);
	case MZ_ZIP_ALLOC_FAILED:
		throw ZipExceptionAllocFailed(errorString);
	case MZ_ZIP_FILE_OPEN_FAILED:
		throw ZipExceptionFileOpenFailed(errorString);
	case MZ_ZIP_FILE_CREATE_FAILED:
		throw ZipExceptionFileCreateFailed(errorString);
	case MZ_ZIP_FILE_WRITE_FAILED:
		throw ZipExceptionFileWriteFailed(errorString);
	case MZ_ZIP_FILE_READ_FAILED:
		throw ZipExceptionFileReadFailed(errorString);
	case MZ_ZIP_FILE_CLOSE_FAILED:
		throw ZipExceptionFileCloseFailed(errorString);
	case MZ_ZIP_FILE_SEEK_FAILED:
		throw ZipExceptionFileSeekFailed(errorString);
	case MZ_ZIP_FILE_STAT_FAILED:
		throw ZipExceptionFileStatFailed(errorString);
	case MZ_ZIP_INVALID_PARAMETER:
		throw ZipExceptionInvalidParameter(errorString);
	case MZ_ZIP_INVALID_FILENAME:
		throw ZipExceptionInvalidFilename(errorString);
	case MZ_ZIP_BUF_TOO_SMALL:
		throw ZipExceptionBufferTooSmall(errorString);
	case MZ_ZIP_INTERNAL_ERROR:
		throw ZipExceptionInternalError(errorString);
	case MZ_ZIP_FILE_NOT_FOUND:
		throw ZipExceptionFileNotFound(errorString);
	case MZ_ZIP_ARCHIVE_TOO_LARGE:
		throw ZipExceptionArchiveTooLarge(errorString);
	case MZ_ZIP_VALIDATION_FAILED:
		throw ZipExceptionValidationFailed(errorString);
	case MZ_ZIP_WRITE_CALLBACK_FAILED:
		throw ZipExceptionWriteCallbackFailed(errorString);
	default:
		throw ZipException(errorString);
	}
}

std::string ZipArchive::GenerateRandomName(int length) {
	static std::string_view letters = "abcdefghijklmnopqrstuvwxyz0123456789";

	int32_t rangeFrom = 0;
	int32_t rangeTo = letters.size() - 1;
	std::random_device rand_dev;
	std::mt19937 generator(rand_dev());
	std::uniform_int_distribution<int32_t> distr(rangeFrom, rangeTo);

	std::string result;
	for (int i = 0; i < length; ++i) {
		result += letters[distr(generator)];
	}

	return result + ".tmp";
}
}


text:
package com.felix.zhiban.bean.book;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Series {

    @SerializedName("id")
    @Expose
    private String id;
    @SerializedName("title")
    @Expose
    private String title;

    public String getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

}


text:
<?php

namespace Jpietrzyk\VoltDbTools\Query;

/**
 * class QueryNotSupportedException
 *
 */
class QueryNotSupportedException extends \Exception {

}


text:
package org.fcrepo.server.security.xacml.pdp.data;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.fcrepo.server.security.xacml.pdp.finder.policy.PolicyReader;
import org.fcrepo.server.security.xacml.util.AttributeBean;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import org.jboss.security.xacml.sunxacml.AbstractPolicy;
import org.jboss.security.xacml.sunxacml.EvaluationCtx;
import org.jboss.security.xacml.sunxacml.ParsingException;
import org.jboss.security.xacml.sunxacml.Policy;
import org.jboss.security.xacml.sunxacml.PolicySet;
import org.jboss.security.xacml.sunxacml.attr.AttributeDesignator;
import org.jboss.security.xacml.sunxacml.attr.AttributeValue;
import org.jboss.security.xacml.sunxacml.attr.BagAttribute;
import org.jboss.security.xacml.sunxacml.cond.EvaluationResult;
import org.jboss.security.xacml.sunxacml.finder.PolicyFinder;

/**
 * Base abstract class for all PolicyIndex implementations.
 *
 * Gets the index configuration common to all implementations.
 *
 * @author Stephen Bayliss
 * @version $Id$
 */
public abstract class PolicyIndexBase
implements PolicyIndex {
    protected static final String SUBJECT_KEY = "subjectAttributes";
    protected static final String RESOURCE_KEY = "resourceAttributes";
    protected static final String ACTION_KEY = "actionAttributes";
    protected static final String ENVIRONMENT_KEY = "environmentAttributes";
    protected static final URI SUBJECT_CATEGORY_DEFAULT =
            URI.create(AttributeDesignator.SUBJECT_CATEGORY_DEFAULT);
    // used in testing - indicates if the implementation returns indexed results
    // or if false indicates that all policies are returned irrespective of the request
    public  boolean indexed = true;

    protected Map<String, Map<String, String>> indexMap = null;
    protected PolicyReader m_policyReader;

    protected static final String METADATA_POLICY_NS = "metadata";

    // xacml namespaces and prefixes
    public static final Map<String, String> namespaces = new HashMap<String, String>();
    static {
        namespaces.put("p", XACML20_POLICY_NS);
        namespaces.put("m", METADATA_POLICY_NS); // appears to dbxml specific and probably not used
    }

    protected PolicyIndexBase(PolicyReader policyReader) throws PolicyIndexException {
        m_policyReader = policyReader;
        String[] indexMapElements =
        {SUBJECT_KEY, RESOURCE_KEY,
                ACTION_KEY, ENVIRONMENT_KEY};

        indexMap = new HashMap<String, Map<String, String>>();
        for (String s : indexMapElements) {
            indexMap.put(s, new HashMap<String, String>());
        }
    }

    public void setSubjectAttributes(Map<String, String> attributeMap) {
        setAttributeMap(SUBJECT_KEY, attributeMap);
    }

    public void setResourceAttributes(Map<String, String> attributeMap) {
        setAttributeMap(RESOURCE_KEY, attributeMap);
    }

    public void setActionAttributes(Map<String, String> attributeMap) {
        setAttributeMap(ACTION_KEY, attributeMap);
    }

    public void setEnvironmentAttributes(Map<String, String> attributeMap) {
        setAttributeMap(ENVIRONMENT_KEY, attributeMap);
    }

    protected void setAttributeMap(String mapKey, Map<String, String> attributeMap) {
        indexMap.get(mapKey).putAll(attributeMap);
    }

    /**
     * This method extracts the attributes listed in the indexMap from the given
     * evaluation context.
     *
     * @param eval
     *        the Evaluation Context from which to extract Attributes
     * @return a Map of Attributes for each category (Subject, Resource, Action,
     *         Environment)
     * @throws URISyntaxException
     */
    @SuppressWarnings("unchecked")
    protected Map<String, Collection<AttributeBean>> getAttributeMap(EvaluationCtx eval) throws URISyntaxException {
        final URI defaultCategoryURI = SUBJECT_CATEGORY_DEFAULT;

        Map<String, String> im = null;
        Map<String, Collection<AttributeBean>> attributeMap =
                new HashMap<String, Collection<AttributeBean>>();
        Map<String, AttributeBean> attributeBeans = null;

        im = indexMap.get(SUBJECT_KEY);
        attributeBeans = new HashMap<String, AttributeBean>();
        for (String attributeId : im.keySet()) {
            EvaluationResult result =
                    eval.getSubjectAttribute(new URI(im.get(attributeId)),
                                             new URI(attributeId),
                                             defaultCategoryURI);
            if (result.getStatus() == null && !result.indeterminate()) {
                AttributeValue attr = result.getAttributeValue();
                if (attr.returnsBag()) {
                    Iterator<AttributeValue> i =
                            ((BagAttribute) attr).iterator();
                    if (i.hasNext()) {
                        while (i.hasNext()) {
                            AttributeValue value = i.next();
                            String attributeType = im.get(attributeId);

                            AttributeBean ab = attributeBeans.get(attributeId);
                            if (ab == null) {
                                ab = new AttributeBean();
                                ab.setId(attributeId);
                                ab.setType(attributeType);
                                attributeBeans.put(attributeId, ab);
                            }

                            ab.addValue(value.encode());
                        }
                    }
                }
            }
        }
        attributeMap.put(SUBJECT_KEY, attributeBeans.values());

        im = indexMap.get(RESOURCE_KEY);
        attributeBeans = new HashMap<String, AttributeBean>();
        for (String attributeId : im.keySet()) {
            EvaluationResult result =
                    eval.getResourceAttribute(new URI(im.get(attributeId)),
                                              new URI(attributeId),
                                              null);
            if (result.getStatus() == null && !result.indeterminate()) {
                AttributeValue attr = result.getAttributeValue();
                if (attr.returnsBag()) {
                    Iterator<AttributeValue> i =
                            ((BagAttribute) attr).iterator();
                    if (i.hasNext()) {
                        while (i.hasNext()) {
                            AttributeValue value = i.next();
                            String attributeType = im.get(attributeId);

                            AttributeBean ab = attributeBeans.get(attributeId);
                            if (ab == null) {
                                ab = new AttributeBean();
                                ab.setId(attributeId);
                                ab.setType(attributeType);
                                attributeBeans.put(attributeId, ab);
                            }

                            if (attributeId.equals(XACML_RESOURCE_ID)
                                    && value.encode().startsWith("/")) {
                                String[] components =
                                        makeComponents(value.encode());
                                if (components != null && components.length > 0) {
                                    for (String c : components) {
                                        ab.addValue(c);
                                    }
                                } else {
                                    ab.addValue(value.encode());
                                }
                            } else {
                                ab.addValue(value.encode());
                            }
                        }
                    }
                }
            }
        }
        attributeMap.put(RESOURCE_KEY, attributeBeans.values());

        im = indexMap.get(ACTION_KEY);
        attributeBeans = new HashMap<String, AttributeBean>();
        for (String attributeId : im.keySet()) {
            EvaluationResult result =
                    eval.getActionAttribute(new URI(im.get(attributeId)),
                                            new URI(attributeId),
                                            null);
            if (result.getStatus() == null && !result.indeterminate()) {
                AttributeValue attr = result.getAttributeValue();
                if (attr.returnsBag()) {
                    Iterator<AttributeValue> i =
                            ((BagAttribute) attr).iterator();
                    if (i.hasNext()) {
                        while (i.hasNext()) {
                            AttributeValue value = i.next();
                            String attributeType = im.get(attributeId);

                            AttributeBean ab = attributeBeans.get(attributeId);
                            if (ab == null) {
                                ab = new AttributeBean();
                                ab.setId(attributeId);
                                ab.setType(attributeType);
                                attributeBeans.put(attributeId, ab);
                            }

                            ab.addValue(value.encode());
                        }
                    }
                }
            }
        }
        attributeMap.put(ACTION_KEY, attributeBeans.values());

        im = indexMap.get(ENVIRONMENT_KEY);
        attributeBeans = new HashMap<String, AttributeBean>();
        for (String attributeId : im.keySet()) {
            URI imAttrId = new URI(im.get(attributeId));
            URI attrId = new URI(attributeId);
            EvaluationResult result =
                    eval.getEnvironmentAttribute(imAttrId, attrId, null);
            if (result.getStatus() == null && !result.indeterminate()) {
                AttributeValue attr = result.getAttributeValue();
                if (attr.returnsBag()) {
                    Iterator<AttributeValue> i =
                            ((BagAttribute) attr).iterator();
                    if (i.hasNext()) {
                        while (i.hasNext()) {
                            AttributeValue value = i.next();
                            String attributeType = im.get(attributeId);

                            AttributeBean ab = attributeBeans.get(attributeId);
                            if (ab == null) {
                                ab = new AttributeBean();
                                ab.setId(attributeId);
                                ab.setType(attributeType);
                                attributeBeans.put(attributeId, ab);
                            }

                            ab.addValue(value.encode());
                        }
                    }
                }
            }
        }
        attributeMap.put(ENVIRONMENT_KEY, attributeBeans.values());

        return attributeMap;
    }

    /**
     * A private method that handles reading the policy and creates the correct
     * kind of AbstractPolicy.
     * Because this makes use of the policyFinder, it cannot be reused between finders.
     * Consider moving to policyManager, which is not intended to be reused outside
     * of a policyFinderModule, which is not intended to be reused amongst PolicyFinder instances.
     */
    protected AbstractPolicy handleDocument(Document doc, PolicyFinder policyFinder) throws ParsingException {
        // handle the policy, if it's a known type
        Element root = doc.getDocumentElement();
        String name = root.getTagName();

        // see what type of policy this is
        if (name.equals("Policy")) {
            return Policy.getInstance(root);
        } else if (name.equals("PolicySet")) {
            return PolicySet.getInstance(root, policyFinder);
        } else {
            // this isn't a root type that we know how to handle
            throw new ParsingException("Unknown root document type: " + name);
        }
    }

    /**
     * Splits a XACML hierarchical resource-id value into a set of resource-id values
     * that can be matched against a policy.
     *
     *  Eg an incoming request for /res1/res2/res3/.* should match
     *  /res1/.*
     *  /res1/res2/.*
     *  /res1/res2/res3/.*
     *
     *  in policies.
     *
     * @param resourceId XACML hierarchical resource-id value
     * @return array of individual resource-id values that can be used to match against policies
     */
    protected static String[] makeComponents(String resourceId) {
        if (resourceId == null || resourceId.isEmpty()
                || !resourceId.startsWith("/")) {
            return null;
        }

        List<String> components = new ArrayList<String>();

        String[] parts = resourceId.split("\\/");

        int bufPrimer = 0;
        for (int x = 1; x < parts.length; x++) {
            bufPrimer = Math.max(bufPrimer, (parts[x].length() + 1));
            StringBuilder sb = new StringBuilder(bufPrimer);
            for (int y = 0; y < x; y++) {
                sb.append("/");
                sb.append(parts[y + 1]);
            }

            String componentBase = sb.toString();
            bufPrimer = componentBase.length() + 16;
            components.add(componentBase);

            if (x != parts.length - 1) {
                components.add(componentBase.concat("/.*"));
            } else {
                components.add(componentBase.concat("$"));
            }
        }

        return components.toArray(parts);
    }

}


text:
<?php
namespace Polidog\Todo\Module;

use BEAR\Sunday\Extension\Application\AbstractApp;

class App extends AbstractApp
{
}


text:
//
//  JSONSchemaDocument+Private.h
//  JSONSchema
//
//  Created by Andy Mroczkowski on 5/27/13.
//
//

#import "JSONSchemaDocument.h"

@interface JSONSchemaDocument ()

#pragma mark Subclasses Must Override

// if the property name on the classes differs from the property name in JSON-Schema
+ (NSDictionary*) attributeToPropertyMap;

#pragma mark Internal Helpers

/*
 @discussion returns the value for a "JSONSchemaAttribute"
 */
- (id) valueForAttribute:(NSString*)attribute;

- (BOOL) validateAndSetAttribute:(NSString*)attr fromObject:(id)object error:(NSError**)outError;

+ (NSString*) attributeNameForPropertyName:(NSString*)propertyName;

+ (NSString*) propertyNameForAttributeName:(NSString*)attributeName;

- (BOOL) validateTypeKey:(NSString*)key value:(id*)value error:(NSError**)error;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.mbh.materialdialog">

    <application/>

</manifest>


text:
macro-clean
===========

Kills unused macro definitions in latex projects.
Appropriately handles macros which use other macros.

# Inputs:

* file containing one-line macro definitions
* multiple tex files which use the macros in the above file

Finds all unused macro definitions and sends to stdout the macro
file, omitting the unused lines.

# Sample Usage:

    ghc -i macroclean.hs macros_file.sty file1.tex file2.tex > new_macros_file.sty

or

    ghc macroclean
    ./macroclean macros_file.sty file1.tex file2.tex > new_macros_file.sty

Example inputs are provided. Compare the output of

    ./macroclean sample_macros.sty sample1.tex

and

    ./macroclean sample_macros.sty sample1.tex sample2.tex


text:
extern crate log;
use rand;
#[macro_use]
extern crate serde_derive;

#[path = "../log_util.rs"]
mod log_util;
mod util;

use std::sync::Arc;
use std::thread;
use std::time::Duration;

use futures_util::{SinkExt as _, TryStreamExt as _};
use grpcio::*;
use grpcio_proto::example::route_guide::{Point, Rectangle, RouteNote};
use grpcio_proto::example::route_guide_grpc::RouteGuideClient;
use rand::{seq::SliceRandom, Rng};

fn new_point(lat: i32, lon: i32) -> Point {
    let mut point = Point::default();
    point.set_latitude(lat);
    point.set_longitude(lon);
    point
}

fn new_rect(lat1: i32, lon1: i32, lat2: i32, lon2: i32) -> Rectangle {
    let mut rect = Rectangle::default();
    rect.set_lo(new_point(lat1, lon1));
    rect.set_hi(new_point(lat2, lon2));
    rect
}

fn new_note(lat: i32, lon: i32, msg: &str) -> RouteNote {
    let mut note = RouteNote::default();
    note.set_location(new_point(lat, lon));
    note.set_message(msg.to_owned());
    note
}

async fn get_feature(client: &RouteGuideClient, point: &Point) -> Result<()> {
    let get_feature = client.get_feature_async(point)?;
    let f = get_feature.await?;
    if !f.has_location() {
        warn!("Server returns incomplete feature.");
        return Ok(());
    }
    if f.get_name().is_empty() {
        warn!("Found no feature at {}", util::format_point(point));
        return Ok(());
    }
    info!(
        "Found feature called {} at {}",
        f.get_name(),
        util::format_point(point)
    );
    Ok(())
}

async fn list_features(client: &RouteGuideClient) -> Result<()> {
    let rect = new_rect(400_000_000, -750_000_000, 420_000_000, -730_000_000);
    info!("Looking for features between 40, -75 and 42, -73");
    let mut list_features = client.list_features(&rect)?;
    while let Some(feature) = list_features.try_next().await? {
        let loc = feature.get_location();
        info!(
            "Found feature {} at {}",
            feature.get_name(),
            util::format_point(loc)
        );
    }
    info!("List feature rpc succeeded.");
    Ok(())
}

async fn record_route(client: &RouteGuideClient) -> Result<()> {
    let features = util::load_db();
    let mut rng = rand::thread_rng();
    let (mut sink, receiver) = client.record_route()?;
    for _ in 0..10usize {
        let f = features.choose(&mut rng).unwrap();
        let point = f.get_location();
        info!("Visiting {}", util::format_point(point));
        sink.send((point.to_owned(), WriteFlags::default())).await?;
        thread::sleep(Duration::from_millis(rng.gen_range(500, 1500)));
    }
    // flush
    sink.close().await?;
    let summary = receiver.await?;
    info!("Finished trip with {} points", summary.get_point_count());
    info!("Passed {} features", summary.get_feature_count());
    info!("Travelled {} meters", summary.get_distance());
    info!("It took {} seconds", summary.get_elapsed_time());
    Ok(())
}

async fn route_chat(client: &RouteGuideClient) -> Result<()> {
    let (mut sink, mut receiver) = client.route_chat()?;

    let send = async move {
        let notes = vec![
            ("First message", 0, 0),
            ("Second message", 0, 1),
            ("Third message", 1, 0),
            ("Fourth message", 0, 0),
        ];

        for (msg, lat, lon) in notes {
            let note = new_note(lat, lon, msg);
            info!("Sending message {} at {}, {}", msg, lat, lon);
            sink.send((note, WriteFlags::default())).await?;
        }
        sink.close().await?;
        Ok(()) as Result<_>
    };

    let receive = async move {
        while let Some(note) = receiver.try_next().await? {
            let location = note.get_location();
            info!(
                "Got message {} at {}, {}",
                note.get_message(),
                location.get_latitude(),
                location.get_longitude()
            );
        }
        Ok(()) as Result<_>
    };
    let (sr, rr) = futures_util::join!(send, receive);
    sr.and(rr)?;
    Ok(())
}

async fn async_main() -> Result<()> {
    let _guard = log_util::init_log(None);
    let env = Arc::new(Environment::new(2));
    let channel = ChannelBuilder::new(env).connect("127.0.0.1:50051");
    let client = RouteGuideClient::new(channel);

    info!("-------------- GetFeature --------------");
    get_feature(&client, &new_point(409_146_138, -746_188_906)).await?;
    get_feature(&client, &new_point(0, 0)).await?;

    info!("-------------- ListFeatures --------------");
    list_features(&client).await?;

    info!("-------------- RecordRoute --------------");
    record_route(&client).await?;

    info!("-------------- RouteChat --------------");
    route_chat(&client).await?;

    Ok(())
}

fn main() {
    futures_executor::block_on(async_main()).unwrap()
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using WestBlueGolfLeagueWeb.Models.Entities;

namespace WestBlueGolfLeagueWeb.Models.Admin
{
    public class AddPlayerRequest
    {
		[Required(ErrorMessage = "Player name is required.")]
		[MinLength(5, ErrorMessage = "Must be at least 5 characters.")]
		[Display(Name = "Player Name")]
        public string PlayerName { get; set; }

		[Required(ErrorMessage = "Handicap is required.")]
		[Display(Name = "Player Handicap")]
        [Range(-5, 20, ErrorMessage = "Handicap must be between -5 and 20 (inclusive)")]
        public int Handicap { get; set; }

		[Required(ErrorMessage = "Must select a team!")]
		[Display(Name = "Team")]
        public int TeamId { get; set; }

        [Display(Name = "Rookie", Description = "Should this player be treated as a rookie?")]
        public bool IsRookie { get; set; }

		public IEnumerable<team> Teams { get; set; }
    }
}


text:
/*
 * @file        exception.cpp
 * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
 * @version     1.0
 * @brief       This file is the implementation of exception system
 */
#include <stddef.h>
#include <dpl/exception.h>
#include <dpl/log/log.h>
#include <cstdio>

namespace SecurityManager {
Exception* Exception::m_lastException = NULL;
unsigned int Exception::m_exceptionCount = 0;
void (*Exception::m_terminateHandler)() = NULL;

void LogUnhandledException(const std::string &str)
{
    // Logging to console
    printf("%s\n", str.c_str());

    // Logging to dlog
    LogPedantic(str);
}

void LogUnhandledException(const std::string &str,
                           const char *filename,
                           int line,
                           const char *function)
{
    // Logging to console
    std::ostringstream msg;
    msg << "\033[1;5;31m\n=== [" << filename << ":" << line << "] " <<
    function << " ===\033[m";
    msg << str;
    printf("%s\n", msg.str().c_str());

    // Logging to dlog
    SecurityManager::Log::LogSystemSingleton::Instance().Error(
        str.c_str(), filename, line, function);
}
} // namespace SecurityManager


text:
package org.ohdsi.webapi.audittrail;

import org.springframework.batch.core.JobExecution;

public interface AuditTrailService {

    void logSuccessfulLogin(String login, String sessionId, String remoteHost);
    void logFailedLogin(String login, String remoteHost);

    void logSuccessfulLogout(String login);
    void logFailedLogout(String login);

    void logRestCall(AuditTrailEntry entry, boolean success);

    void logJobStart(JobExecution jobExecution);
    void logJobCompleted(JobExecution jobExecution);
    void logJobFailed(JobExecution jobExecution);
}


text:
package com.eixox.data.sql;

public class MySqlCommand extends DatabaseCommand {

	public MySqlCommand(Database database) {
		super(database);
	}

	@Override
	public DatabaseCommand appendString(String value) {
		text.append('\'');
		int stringLength = value.length();
		for (int i = 0; i < stringLength; ++i) {
			char c = value.charAt(i);
			switch (c) {
			case 0: /* Must be escaped for 'mysql' */
				text.append('\\');
				text.append('0');
				break;
			case '\n': /* Must be escaped for logs */
				text.append('\\');
				text.append('n');
				break;
			case '\r':
				text.append('\\');
				text.append('r');
				break;
			case '\\':
				text.append('\\');
				text.append('\\');
				break;
			case '\'':
				text.append('\'');
				text.append('\'');
				break;
			case '\032': /* This gives problems on Win32 */
				text.append('\\');
				text.append('Z');
				break;
			case '\u00a5':
			case '\u20a9':
				// escape characters interpreted as backslash by mysql
				// fall through
				break;
			default:
				text.append(c);
			}
		}
		text.append('\'');
		return this;
	}

}


text:
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
using System;

namespace UIWidgets
{
	[CanEditMultipleObjects]
	[CustomEditor(typeof(ListView), true)]
	public class ListViewEditor : Editor
	{
		Dictionary<string,SerializedProperty> serializedProperties = new Dictionary<string,SerializedProperty>();

		string[] properties = new string[]{
			"Source",
			"strings",
			//"dataSource",
			"file",

			"CommentsStartWith",
			"sort",
			"Unique",
			"AllowEmptyItems",

			"Multiple",
			"selectedIndex",

			"direction",

			"backgroundColor",
			"textColor",
			"HighlightedBackgroundColor",
			"HighlightedTextColor",
			"selectedBackgroundColor",
			"selectedTextColor",

			"Container",
			"DefaultItem",
			"scrollRect",

			"OnSelectString",
			"OnDeselectString",
		};

		protected virtual void OnEnable()
		{
			Array.ForEach(properties, x => {
				var p = serializedObject.FindProperty(x);
				serializedProperties.Add(x, p);
			});
		}

		public override void OnInspectorGUI()
		{
			serializedObject.Update();

			EditorGUILayout.PropertyField(serializedProperties["Source"]);

			EditorGUI.indentLevel++;
			if (serializedProperties["Source"].enumValueIndex==0)
			{
				var options = new GUILayoutOption[] {};
				EditorGUILayout.PropertyField(serializedProperties["strings"], new GUIContent("Items"), true, options);
				//EditorGUILayout.PropertyField(serializedProperties["dataSource"], new GUIContent("Items"), true, options);
			}
			else
			{
				EditorGUILayout.PropertyField(serializedProperties["file"]);
				EditorGUILayout.PropertyField(serializedProperties["CommentsStartWith"], true);
				EditorGUILayout.PropertyField(serializedProperties["AllowEmptyItems"]);
			}
			EditorGUI.indentLevel--;

			EditorGUILayout.PropertyField(serializedProperties["Unique"], new GUIContent("Only unique items"));
			EditorGUILayout.PropertyField(serializedProperties["sort"]);
			EditorGUILayout.PropertyField(serializedProperties["Multiple"]);
			EditorGUILayout.PropertyField(serializedProperties["selectedIndex"]);

			EditorGUILayout.PropertyField(serializedProperties["backgroundColor"]);
			EditorGUILayout.PropertyField(serializedProperties["textColor"]);
			EditorGUILayout.PropertyField(serializedProperties["HighlightedBackgroundColor"]);
			EditorGUILayout.PropertyField(serializedProperties["HighlightedTextColor"]);
			EditorGUILayout.PropertyField(serializedProperties["selectedBackgroundColor"]);
			EditorGUILayout.PropertyField(serializedProperties["selectedTextColor"]);

			EditorGUILayout.PropertyField(serializedProperties["DefaultItem"]);
			EditorGUILayout.PropertyField(serializedProperties["Container"]);
			EditorGUILayout.PropertyField(serializedProperties["scrollRect"]);

			EditorGUILayout.PropertyField(serializedProperties["OnSelectString"]);
			EditorGUILayout.PropertyField(serializedProperties["OnDeselectString"]);

			serializedObject.ApplyModifiedProperties();
		}
	}
}


text:
Deface::Override.new(:virtual_path => "spree/layouts/spree_application",
                     :name => "posts_in_header",
                     :insert_bottom => "#main-nav-bar",
                     :text => "<li class=\"<%= 'current' if request.path == posts_path %>\"><%= link_to( t('posts'), posts_path) %>
")


text:
(async function() {
  TestRunner.addResult(`Tests the Timeline API function call is not recorded for InjectedScript.eval.\n`);
  await TestRunner.loadLegacyModule('timeline'); await TestRunner.loadTestModule('performance_test_runner');
  await TestRunner.showPanel('timeline');
  await TestRunner.evaluateInPagePromise(`
      function performActions()
      {
      }
  `);

  UI.panels.timeline.disableCaptureJSProfileSetting.set(true);
  await PerformanceTestRunner.performActionsAndPrint('performActions()', 'FunctionCall');
})();


text:
from .yass import Yass
import publisher
import re


text:
module Starlighter
  class OptionsParser
    def initialize
    end
  end
end


text:
package com.tectonica.jonix.onix2;

import com.tectonica.jonix.common.JPU;
import com.tectonica.jonix.common.OnixElement;
import com.tectonica.jonix.common.codelist.Languages;
import com.tectonica.jonix.common.codelist.ProductAvailabilitys;
import com.tectonica.jonix.common.codelist.RecordSourceTypes;
import com.tectonica.jonix.common.codelist.TextCaseFlags;
import com.tectonica.jonix.common.codelist.TextFormats;
import com.tectonica.jonix.common.codelist.TransliterationSchemes;

import java.io.Serializable;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DO NOT EDIT MANUALLY
 */

/**
 *
Product availability

 *

 * An ONIX code indicating the availability of a product from a supplier. This element has been added as a preferred
 * successor to the <AvailabilityCode> element, and is intended to be used both by publishers (who should also
 * include the new <PublishingStatus> element in PR.20) and by intermediary suppliers (who may also include
 * <PublishingStatus> if they are in a position to do so. Each occurrence of the <SupplyDetail> composite
 * must carry either <AvailabilityCode> or <ProductAvailability>, or both. The element is non-repeating.
 * Recommended practise is in future to use this new element, and, where possible and appropriate, to include the
 * <PublishingStatus> element in PR.20. It is likely that the <AvailabilityCode> element will be
 * "deprecated" in due course in a future release.
 *

 *

 *

 * Format
 * Fixed-length, two numeric digits
 *

 *

 * Codelist
 * List 65
 *

 *

 * Reference name
 * <tt><ProductAvailability></tt>
 *

 *

 * Short tag
 * <tt><j396></tt>
 *

 *

 * Example
 * <tt><j396>41</j396></tt> Replaced by new product
 *

 *

 *

 * This tag may be included in the following composites:
 *

 *
<{@link SupplyDetail}>

 *

 *

 * Possible placements within ONIX message:
 *

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link SupplyDetail} ⯈ {@link ProductAvailability}

 *

 *
 * @since Onix-2.11
 */
public class ProductAvailability implements OnixElement<ProductAvailabilitys>, Serializable {
    private static final long serialVersionUID = 1L;

    public static final String refname = "ProductAvailability";
    public static final String shortname = "j396";

    /////////////////////////////////////////////////////////////////////////////////
    // ATTRIBUTES
    /////////////////////////////////////////////////////////////////////////////////

    public TextFormats textformat;

    public TextCaseFlags textcase;

    public Languages language;

    public TransliterationSchemes transliteration;

    /**
     * (type: DateOrDateTime)
     */
    public String datestamp;

    public RecordSourceTypes sourcetype;

    public String sourcename;

    /////////////////////////////////////////////////////////////////////////////////
    // VALUE MEMBER
    /////////////////////////////////////////////////////////////////////////////////

    public ProductAvailabilitys value;

    /**
     * Internal API, use the {@link #value()} method or the {@link #value} field instead
     */
    @Override
    public ProductAvailabilitys _value() {
        return value;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // SERVICES
    /////////////////////////////////////////////////////////////////////////////////

    private final boolean exists;
    public static final ProductAvailability EMPTY = new ProductAvailability();

    public ProductAvailability() {
        exists = false;
    }

    public ProductAvailability(org.w3c.dom.Element element) {
        exists = true;
        textformat = TextFormats.byCode(JPU.getAttribute(element, "textformat"));
        textcase = TextCaseFlags.byCode(JPU.getAttribute(element, "textcase"));
        language = Languages.byCode(JPU.getAttribute(element, "language"));
        transliteration = TransliterationSchemes.byCode(JPU.getAttribute(element, "transliteration"));
        datestamp = JPU.getAttribute(element, "datestamp");
        sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype"));
        sourcename = JPU.getAttribute(element, "sourcename");

        value = ProductAvailabilitys.byCode(JPU.getContentAsString(element));
    }

    /**
     * @return whether this tag (<ProductAvailability> or <j396>) is explicitly provided in the ONIX XML
     */
    @Override
    public boolean exists() {
        return exists;
    }
}


text:
RingTone-Picker-for-FirefoxOS
========================

A FirefoxOS app for set a custom ringtone (ogg file) on Firefox OS > 1.2

This is a "system" app, so you won't see an icon on the homescreen when you install it.
After installing, open the Settings app and click on Sound.
Then tap to change your ringtone and choose "Ringtone Picker".
Allow access to the sd card and choose your ringtone!

To uninstall the app use Settings -> App Permissions.

Based on https://github.com/davidflanagan/CustomFirefoxOSRingtones of [David Flanagan](https://github.com/davidflanagan)


text:
import re
from six.moves.urllib.parse import urlsplit, urlunsplit
from data_packer.checker._base import BaseChecker, CheckerWrapper, ReChecker, TypeChecker
from data_packer import err, constant
from data_packer.util import ip

class URLChecker(ReChecker):
    ul = '\u00a1-\uffff'  # unicode letters range (must be a unicode string, not a raw string)

    # IP patterns
    ipv4_re = r'(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}'
    ipv6_re = r'\[[0-9a-f:\.]+\]'  # (simple regex, validated later)

    # Host patterns
    hostname_re = r'[a-z' + ul + r'0-9](?:[a-z' + ul + r'0-9-]{0,61}[a-z' + ul + r'0-9])?'
    # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
    domain_re = r'(?:\.(?!-)[a-z' + ul + r'0-9-]{1,63}(?<!-))*'
    tld_re = (
        '\.'  # dot
        '(?!-)'  # can't start with a dash
        '(?:[a-z' + ul + '-]{2,63}'  # domain label
                         '|xn--[a-z0-9]{1,59})'  # or punycode label
                         '(?<!-)'  # can't end with a dash
                         '\.?'  # may have a trailing dot
    )
    host_re = '(' + hostname_re + domain_re + tld_re + '|localhost)'
    schemes = ['http', 'https', 'ftp', 'ftps']

    def __init__(self):
        super(URLChecker, self).__init__(
            r'^(?:[a-z0-9\.\-\+]*)://'  # scheme is validated separately
            r'(?:\S+(?::\S*)?@)?'  # user:pass authentication
            r'(?:' + self.ipv4_re + '|' + self.ipv6_re + '|' + self.host_re + ')'
            r'(?::\d{2,5})?'  # port
            r'(?:[/?#][^\s]*)?'  # resource path
            r'\Z', re.IGNORECASE
        )

    def verify(self, src_name, dst_name, value):
        # Check first if the scheme is valid
        scheme = value.split('://')[0].lower()
        if scheme not in self.schemes:
            raise err.DataPackerCheckError(
                src_name, dst_name, value, self,
                'Invalid scheme({})'.format(scheme)
            )

        # Then check full URL
        try:
            super(URLChecker, self).verify(src_name, dst_name, value)
        except err.DataPackerCheckError as e:
            # Trivial case failed. Try for possible IDN domain
            if value:
                scheme, netloc, path, query, fragment = urlsplit(value)

                try:
                    netloc = netloc.encode('idna').decode('ascii')  # IDN -> ACE
                except UnicodeError:  # invalid domain part
                    raise e
                url = urlunsplit((scheme, netloc, path, query, fragment))
                super(URLChecker, self).verify(src_name, dst_name, url)
            else:
                raise
        else:
            # Now verify IPv6 in the netloc part
            host_match = re.search(r'^\[(.+)\](?::\d{2,5})?$', urlsplit(value).netloc)
            if host_match:
                potential_ip = host_match.groups()[0]
                ipv6_checker.verify(potential_ip)
            url = value

        # The maximum length of a full host name is 253 characters per RFC 1034
        # section 3.1. It's defined to be 255 bytes or less, but this includes
        # one byte for the length of the name and one byte for the trailing dot
        # that's used to indicate absolute names in DNS.
        if len(urlsplit(value).netloc) > 253:
            raise err.DataPackerCheckError(
                src_name, dst_name, value, self,
                'netloc is too long'
            )

class EmailChecker(BaseChecker):
    user_regex = re.compile(
        r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z"  # dot-atom
        r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])*"\Z)',  # quoted-string
        re.IGNORECASE
    )
    domain_regex = re.compile(
        # max length for domain name labels is 63 characters per RFC 1034
        r'((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+)(?:[A-Z0-9-]{2,63}(?<!-))\Z',
        re.IGNORECASE)
    literal_regex = re.compile(
        # literal form, ipv4 or ipv6 address (SMTP 4.1.3)
        r'\[([A-f0-9:\.]+)\]\Z',
        re.IGNORECASE)
    domain_whitelist = ['localhost']

    def verify(self, src_name, dst_name, value):
        if not value or '@' not in value:
            raise err.DataPackerCheckError(
                src_name, dst_name, value, self,
                'email is null or NOT contain @'
            )

        user_part, domain_part = value.rsplit('@', 1)

        if not self.user_regex.match(user_part):
            raise err.DataPackerCheckError(
                src_name, dst_name, value, self,
                'Invalid user part({})'.format(user_part)
            )

        if (domain_part not in self.domain_whitelist and
                not self.validate_domain_part(domain_part)):
            # Try for possible IDN domain-part
            try:
                domain_part = domain_part.encode('idna').decode('ascii')
                if self.validate_domain_part(domain_part):
                    return
            except UnicodeError:
                pass

            raise err.DataPackerCheckError(
                src_name, dst_name, value, self,
                'Invalid domain part({})'.format(domain_part)
            )

    def validate_domain_part(self, domain_part):
        if self.domain_regex.match(domain_part):
            return True

        literal_match = self.literal_regex.match(domain_part)
        if literal_match:
            ip_address = literal_match.group(1)
            try:
                ipv46_checker.verify('', '', ip_address)
                return True
            except err.DataPackerCheckError:
                pass
        return False

class IPChecker(BaseChecker):

    def __init__(self, version):
        """

        :param version: 请使用constant.IP_VERSION.
        :type version: int
        """
        super(IPChecker, self).__init__()
        if version not in (constant.IP_VERSION.BOTH,
                           constant.IP_VERSION.IPV4,
                           constant.IP_VERSION.IPV6):
            raise err.DataPackerProgramError('Invalid ip version({})'.format(version))

        self._version = version

    def verify(self, src_name, dst_name, value):
        if self._version == constant.IP_VERSION.IPV4:
            ipv4_checker.verify(src_name, dst_name, value)
        elif self._version == constant.IP_VERSION.IPV6:
            ipv6_checker.verify(src_name, dst_name, value)
        else:  # BOTH
            try:
                ipv4_checker.verify(src_name, dst_name, value)
            except err.DataPackerCheckError:
                ipv6_checker.verify(src_name, dst_name, value)

email_checker = EmailChecker()
url_checker = URLChecker()
ipv4_checker = CheckerWrapper(lambda src_name,dst_name,value: ip.is_valid_ipv4(value))
ipv6_checker = CheckerWrapper(lambda src_name,dst_name,value: ip.is_valid_ipv6(value))
ipv46_checker = IPChecker(constant.IP_VERSION.BOTH)
text_checker = TypeChecker((str, unicode))


text:
#ifndef __ASM_MMU_H
#define __ASM_MMU_H

typedef struct {
	unsigned int id;
	raw_spinlock_t id_lock;
	void *vdso;
} mm_context_t;

#define INIT_MM_CONTEXT(name) \
   .context.id_lock = __RAW_SPIN_LOCK_UNLOCKED(name.context.id_lock),

#define ASID(mm)	((mm)->context.id & 0xffff)

extern void paging_init(void);
extern void setup_mm_for_reboot(void);
extern void __iomem *early_io_map(phys_addr_t phys, unsigned long virt);

#endif