text:
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var AutomationEvent = require('automationEvent').AutomationEvent;
var automationInternal =
    require('binding').Binding.create('automationInternal').generate();
var IsInteractPermitted =
    requireNative('automationInternal').IsInteractPermitted;

var lastError = require('lastError');
var logging = requireNative('logging');
var schema = requireNative('automationInternal').GetSchemaAdditions();
var utils = require('utils');

/**
 * A single node in the Automation tree.
 * @param {AutomationRootNodeImpl} root The root of the tree.
 * @constructor
 */
function AutomationNodeImpl(root) {
  this.rootImpl = root;
  this.childIds = [];
  this.attributes = {};
  this.listeners = {};
  this.location = { left: 0, top: 0, width: 0, height: 0 };
}

AutomationNodeImpl.prototype = {
  id: -1,
  role: '',
  state: { busy: true },
  isRootNode: false,

  get root() {
    return this.rootImpl.wrapper;
  },

  parent: function() {
    return this.rootImpl.get(this.parentID);
  },

  firstChild: function() {
    var node = this.rootImpl.get(this.childIds[0]);
    return node;
  },

  lastChild: function() {
    var childIds = this.childIds;
    var node = this.rootImpl.get(childIds[childIds.length - 1]);
    return node;
  },

  children: function() {
    var children = [];
    for (var i = 0, childID; childID = this.childIds[i]; i++) {
      logging.CHECK(this.rootImpl.get(childID));
      children.push(this.rootImpl.get(childID));
    }
    return children;
  },

  previousSibling: function() {
    var parent = this.parent();
    if (parent && this.indexInParent > 0)
      return parent.children()[this.indexInParent - 1];
    return undefined;
  },

  nextSibling: function() {
    var parent = this.parent();
    if (parent && this.indexInParent < parent.children().length)
      return parent.children()[this.indexInParent + 1];
    return undefined;
  },

  doDefault: function() {
    this.performAction_('doDefault');
  },

  focus: function() {
    this.performAction_('focus');
  },

  makeVisible: function() {
    this.performAction_('makeVisible');
  },

  setSelection: function(startIndex, endIndex) {
    this.performAction_('setSelection',
                        { startIndex: startIndex,
                          endIndex: endIndex });
  },

  addEventListener: function(eventType, callback, capture) {
    this.removeEventListener(eventType, callback);
    if (!this.listeners[eventType])
      this.listeners[eventType] = [];
    this.listeners[eventType].push({callback: callback, capture: !!capture});
  },

  // TODO(dtseng/aboxhall): Check this impl against spec.
  removeEventListener: function(eventType, callback) {
    if (this.listeners[eventType]) {
      var listeners = this.listeners[eventType];
      for (var i = 0; i < listeners.length; i++) {
        if (callback === listeners[i].callback)
          listeners.splice(i, 1);
      }
    }
  },

  dispatchEvent: function(eventType) {
    var path = [];
    var parent = this.parent();
    while (parent) {
      path.push(parent);
      // TODO(aboxhall/dtseng): handle unloaded parent node
      parent = parent.parent();
    }
    var event = new AutomationEvent(eventType, this.wrapper);

    // Dispatch the event through the propagation path in three phases:
    // - capturing: starting from the root and going down to the target's parent
    // - targeting: dispatching the event on the target itself
    // - bubbling: starting from the target's parent, going back up to the root.
    // At any stage, a listener may call stopPropagation() on the event, which
    // will immediately stop event propagation through this path.
    if (this.dispatchEventAtCapturing_(event, path)) {
      if (this.dispatchEventAtTargeting_(event, path))
        this.dispatchEventAtBubbling_(event, path);
    }
  },

  toString: function() {
    return 'node id=' + this.id +
        ' role=' + this.role +
        ' state=' + JSON.stringify(this.state) +
        ' parentID=' + this.parentID +
        ' childIds=' + JSON.stringify(this.childIds) +
        ' attributes=' + JSON.stringify(this.attributes);
  },

  dispatchEventAtCapturing_: function(event, path) {
    privates(event).impl.eventPhase = Event.CAPTURING_PHASE;
    for (var i = path.length - 1; i >= 0; i--) {
      this.fireEventListeners_(path[i], event);
      if (privates(event).impl.propagationStopped)
        return false;
    }
    return true;
  },

  dispatchEventAtTargeting_: function(event) {
    privates(event).impl.eventPhase = Event.AT_TARGET;
    this.fireEventListeners_(this.wrapper, event);
    return !privates(event).impl.propagationStopped;
  },

  dispatchEventAtBubbling_: function(event, path) {
    privates(event).impl.eventPhase = Event.BUBBLING_PHASE;
    for (var i = 0; i < path.length; i++) {
      this.fireEventListeners_(path[i], event);
      if (privates(event).impl.propagationStopped)
        return false;
    }
    return true;
  },

  fireEventListeners_: function(node, event) {
    var nodeImpl = privates(node).impl;
    var listeners = nodeImpl.listeners[event.type];
    if (!listeners)
      return;
    var eventPhase = event.eventPhase;
    for (var i = 0; i < listeners.length; i++) {
      if (eventPhase == Event.CAPTURING_PHASE && !listeners[i].capture)
        continue;
      if (eventPhase == Event.BUBBLING_PHASE && listeners[i].capture)
        continue;

      try {
        listeners[i].callback(event);
      } catch (e) {
        console.error('Error in event handler for ' + event.type +
                      'during phase ' + eventPhase + ': ' +
                      e.message + '\nStack trace: ' + e.stack);
      }
    }
  },

  performAction_: function(actionType, opt_args) {
    // Not yet initialized.
    if (this.rootImpl.processID === undefined ||
        this.rootImpl.routingID === undefined ||
        this.wrapper.id === undefined) {
      return;
    }

    // Check permissions.
    if (!IsInteractPermitted()) {
      throw new Error(actionType + ' requires {"desktop": true} or' +
          ' {"interact": true} in the "automation" manifest key.');
    }

    automationInternal.performAction({ processID: this.rootImpl.processID,
                                       routingID: this.rootImpl.routingID,
                                       automationNodeID: this.wrapper.id,
                                       actionType: actionType },
                                     opt_args || {});
  }
};

// Maps an attribute to its default value in an invalidated node.
// These attributes are taken directly from the Automation idl.
var AutomationAttributeDefaults = {
  'id': -1,
  'role': '',
  'state': {},
  'location': { left: 0, top: 0, width: 0, height: 0 }
};

var AutomationAttributeTypes = [
  'boolAttributes',
  'floatAttributes',
  'htmlAttributes',
  'intAttributes',
  'intlistAttributes',
  'stringAttributes'
];

/**
 * AutomationRootNode.
 *
 * An AutomationRootNode is the javascript end of an AXTree living in the
 * browser. AutomationRootNode handles unserializing incremental updates from
 * the source AXTree. Each update contains node data that form a complete tree
 * after applying the update.
 *
 * A brief note about ids used through this class. The source AXTree assigns
 * unique ids per node and we use these ids to build a hash to the actual
 * AutomationNode object.
 * Thus, tree traversals amount to a lookup in our hash.
 *
 * The tree itself is identified by the process id and routing id of the
 * renderer widget host.
 * @constructor
 */
function AutomationRootNodeImpl(processID, routingID) {
  AutomationNodeImpl.call(this, this);
  this.processID = processID;
  this.routingID = routingID;
  this.axNodeDataCache_ = {};
}

AutomationRootNodeImpl.prototype = {
  __proto__: AutomationNodeImpl.prototype,

  isRootNode: true,

  get: function(id) {
    if (id == undefined)
      return undefined;

    return this.axNodeDataCache_[id];
  },

  unserialize: function(update) {
    var updateState = { pendingNodes: {}, newNodes: {} };
    var oldRootId = this.id;

    if (update.nodeIdToClear < 0) {
        logging.WARNING('Bad nodeIdToClear: ' + update.nodeIdToClear);
        lastError.set('automation',
                      'Bad update received on automation tree',
                      null,
                      chrome);
        return false;
    } else if (update.nodeIdToClear > 0) {
      var nodeToClear = this.axNodeDataCache_[update.nodeIdToClear];
      if (!nodeToClear) {
        logging.WARNING('Bad nodeIdToClear: ' + update.nodeIdToClear +
                        ' (not in cache)');
        lastError.set('automation',
                      'Bad update received on automation tree',
                      null,
                      chrome);
        return false;
      }
      if (nodeToClear === this.wrapper) {
        this.invalidate_(nodeToClear);
      } else {
        var children = nodeToClear.children();
        for (var i = 0; i < children.length; i++)
          this.invalidate_(children[i]);
        privates(nodeToClear).impl.childIds = []
        updateState.pendingNodes[nodeToClear.id] = nodeToClear;
      }
    }

    for (var i = 0; i < update.nodes.length; i++) {
      if (!this.updateNode_(update.nodes[i], updateState))
        return false;
    }

    if (Object.keys(updateState.pendingNodes).length > 0) {
      logging.WARNING('Nodes left pending by the update: ' +
                   updateState.pendingNodes.join(', '));
      lastError.set('automation',
                    'Bad update received on automation tree',
                    null,
                    chrome);
      return false;
    }
    return true;
  },

  destroy: function() {
    this.dispatchEvent(schema.EventType.destroyed);
    this.invalidate_(this.wrapper);
  },

  onAccessibilityEvent: function(eventParams) {
    if (!this.unserialize(eventParams.update)) {
      logging.WARNING('unserialization failed');
      return false;
    }

    var targetNode = this.get(eventParams.targetID);
    if (targetNode) {
      var targetNodeImpl = privates(targetNode).impl;
      targetNodeImpl.dispatchEvent(eventParams.eventType);
    } else {
      logging.WARNING('Got ' + eventParams.eventType +
                      ' event on unknown node: ' + eventParams.targetID +
                      '; this: ' + this.toString());
    }
    return true;
  },

  toString: function() {
    function toStringInternal(node, indent) {
      if (!node)
        return '';
      var output =
          new Array(indent).join(' ') +
          AutomationNodeImpl.prototype.toString.call(node) +
          '\n';
      indent += 2;
      for (var i = 0; i < node.children().length; i++)
        output += toStringInternal(node.children()[i], indent);
      return output;
    }
    return toStringInternal(this, 0);
  },

  invalidate_: function(node) {
    if (!node)
      return;
    var children = node.children();

    for (var i = 0, child; child = children[i]; i++)
      this.invalidate_(child);

    // Retrieve the internal AutomationNodeImpl instance for this node.
    // This object is not accessible outside of bindings code, but we can access
    // it here.
    var nodeImpl = privates(node).impl;
    var id = node.id;
    for (var key in AutomationAttributeDefaults) {
      nodeImpl[key] = AutomationAttributeDefaults[key];
    }
    nodeImpl.childIds = [];
    nodeImpl.loaded = false;
    nodeImpl.id = id;
    delete this.axNodeDataCache_[id];
  },

  load: function(callback) {
    // TODO(dtseng/aboxhall): Implement.
    if (!this.loaded)
      throw 'Unsupported state: root node is not loaded.';

    setTimeout(callback, 0);
  },

  deleteOldChildren_: function(node, newChildIds) {
    // Create a set of child ids in |src| for fast lookup, and return false
    // if a duplicate is found;
    var newChildIdSet = {};
    for (var i = 0; i < newChildIds.length; i++) {
      var childId = newChildIds[i];
      if (newChildIdSet[childId]) {
        logging.WARNING('Node ' + node.id + ' has duplicate child id ' +
                        childId);
        lastError.set('automation',
                      'Bad update received on automation tree',
                      null,
                      chrome);
        return false;
      }
      newChildIdSet[newChildIds[i]] = true;
    }

    // Delete the old children.
    var nodeImpl = privates(node).impl;
    var oldChildIds = nodeImpl.childIds;
    for (var i = 0; i < oldChildIds.length;) {
      var oldId = oldChildIds[i];
      if (!newChildIdSet[oldId]) {
        this.invalidate_(this.axNodeDataCache_[oldId]);
        oldChildIds.splice(i, 1);
      } else {
        i++;
      }
    }
    nodeImpl.childIds = oldChildIds;

    return true;
  },

  createNewChildren_: function(node, newChildIds, updateState) {
    logging.CHECK(node);
    var success = true;
    for (var i = 0; i < newChildIds.length; i++) {
      var childId = newChildIds[i];
      var childNode = this.axNodeDataCache_[childId];
      if (childNode) {
        if (childNode.parent() != node) {
          var parentId = 0;
          if (childNode.parent()) parentId = childNode.parent().id;
          // This is a serious error - nodes should never be reparented.
          // If this case occurs, continue so this node isn't left in an
          // inconsistent state, but return failure at the end.
          logging.WARNING('Node ' + childId + ' reparented from ' +
                          parentId + ' to ' + node.id);
          lastError.set('automation',
                        'Bad update received on automation tree',
                        null,
                        chrome);
          success = false;
          continue;
        }
      } else {
        childNode = new AutomationNode(this);
        this.axNodeDataCache_[childId] = childNode;
        privates(childNode).impl.id = childId;
        updateState.pendingNodes[childNode.id] = childNode;
        updateState.newNodes[childNode.id] = childNode;
      }
      privates(childNode).impl.indexInParent = i;
      privates(childNode).impl.parentID = node.id;
    }

    return success;
  },

  setData_: function(node, nodeData) {
    var nodeImpl = privates(node).impl;
    for (var key in AutomationAttributeDefaults) {
      if (key in nodeData)
        nodeImpl[key] = nodeData[key];
      else
        nodeImpl[key] = AutomationAttributeDefaults[key];
    }
    for (var i = 0; i < AutomationAttributeTypes.length; i++) {
      var attributeType = AutomationAttributeTypes[i];
      for (var attributeName in nodeData[attributeType]) {
        nodeImpl.attributes[attributeName] =
          nodeData[attributeType][attributeName];
      }
    }
  },

  updateNode_: function(nodeData, updateState) {
    var node = this.axNodeDataCache_[nodeData.id];
    var didUpdateRoot = false;
    if (node) {
      delete updateState.pendingNodes[node.id];
    } else {
      if (nodeData.role != schema.RoleType.rootWebArea &&
          nodeData.role != schema.RoleType.desktop) {
        logging.WARNING(String(nodeData.id) +
                     ' is not in the cache and not the new root.');
        lastError.set('automation',
                      'Bad update received on automation tree',
                      null,
                      chrome);
        return false;
      }
      // |this| is an AutomationRootNodeImpl; retrieve the
      // AutomationRootNode instance instead.
      node = this.wrapper;
      didUpdateRoot = true;
      updateState.newNodes[this.id] = this.wrapper;
    }
    this.setData_(node, nodeData);

    // TODO(aboxhall): send onChanged event?
    logging.CHECK(node);
    if (!this.deleteOldChildren_(node, nodeData.childIds)) {
      if (didUpdateRoot) {
        this.invalidate_(this.wrapper);
      }
      return false;
    }
    var nodeImpl = privates(node).impl;

    var success = this.createNewChildren_(node,
                                          nodeData.childIds,
                                          updateState);
    nodeImpl.childIds = nodeData.childIds;
    this.axNodeDataCache_[node.id] = node;

    return success;
  }
};

var AutomationNode = utils.expose('AutomationNode',
                                  AutomationNodeImpl,
                                  { functions: ['parent',
                                                'firstChild',
                                                'lastChild',
                                                'children',
                                                'previousSibling',
                                                'nextSibling',
                                                'doDefault',
                                                'focus',
                                                'makeVisible',
                                                'setSelection',
                                                'addEventListener',
                                                'removeEventListener',
                                                'toString'],
                                    readonly: ['isRootNode',
                                               'id',
                                               'role',
                                               'state',
                                               'location',
                                               'attributes',
                                               'root',
                                               'toString'] });

var AutomationRootNode = utils.expose('AutomationRootNode',
                                      AutomationRootNodeImpl,
                                      { superclass: AutomationNode,
                                        functions: ['load'],
                                        readonly: ['loaded'] });

exports.AutomationNode = AutomationNode;
exports.AutomationRootNode = AutomationRootNode;


text:
A W3C WoT "current practices" compliant web client.

Static HTML5 and javascript, dependencies managed with bower.

## Basic running
Just install all frontend-deps with bower (you need node.js and ``npm -g install bower``)
```bash
bower install
```
Then you can serve the files from any HTTP (or HTTP/2) server.

Dev Example
```bash
# use any webserver - serve is just an example
npm install -g serve
serve
```
## CoAP Polyfill

For CoAP support, please run the [CoAP polyfill](https://github.com/ynh/coap-polyfill) from YNH (runnable jar in this repo)

```bash
java -jar coap-polyfill-1.0.0-M3.jar
```

## Minified build / optimizations
This project is meant as an explorative prototype / reference implementation - not for productive use.

if you are certain you need an optimized build, install dev-dependencies with NPM
and use gulp (you need node.js and ``npm -g install gulp-cli``) to run optimizers.

The shrinked page is availiable in /dist.

```bash
npm install
gulp
```

## License
MIT

## Authors
Johannes Hund (@horus), Daniel Peintner (@danielpeintner) and the Thingweb community

redpajama_set_name: RedPajamaGithub


text:
namespace urde {
CScannableObjectInfo::CScannableObjectInfo(CInputStream& in, CAssetId resId) : x0_scannableObjectId(resId) {
  u32 version = in.readUint32Big();
  Load(in, version);

  for (u32 i = 0; i < x14_buckets.size(); ++i) {
    x14_buckets[i].x4_appearanceRange *= x8_totalDownloadTime;
  }

  float appearanceOffset = g_tweakGui->GetScanAppearanceDuration();
  for (u32 i = 0; i < x14_buckets.size(); ++i) {
    if (x14_buckets[i].x8_imagePos != -1) {
      x8_totalDownloadTime += appearanceOffset;
      for (u32 j = i; j < x14_buckets.size(); j++)
        x14_buckets[j].x4_appearanceRange += appearanceOffset;
    }
  }

  for (u32 i = 0; i < x14_buckets.size() - 1; ++i) {
    for (u32 j = i + 1; j < x14_buckets.size(); ++j) {
      if (x14_buckets[i].x8_imagePos == x14_buckets[j].x8_imagePos && x14_buckets[i].x8_imagePos != -1)
        x14_buckets[j].x8_imagePos = -1;
    }
  }
}

void CScannableObjectInfo::Load(CInputStream& in, u32 version) {
  in.readUint32Big();
  in.readUint32Big();
  x4_stringId = in.readUint32Big();
  if (version < 4)
    x8_totalDownloadTime = in.readFloatBig();
  else {
    u32 scanSpeed = in.readUint32Big();
    x8_totalDownloadTime = g_tweakGui->GetScanSpeed(scanSpeed);
  }
  xc_category = in.readUint32Big();
  if (version > 4)
    x10_important = in.readBool();

  for (u32 i = 0; i < 4; i++)
    x14_buckets.emplace_back(in, version);
}

CScannableObjectInfo::SBucket::SBucket(CInputStream& in, u32 version) {
  x0_texture = in.readUint32Big();
  x4_appearanceRange = in.readFloatBig();
  x8_imagePos = in.readUint32Big();
  if (version > 1) {
    xc_size.x = in.readUint32Big();
    xc_size.y = in.readUint32Big();
    x14_interval = in.readFloatBig();
    if (version >= 3)
      x18_fadeDuration = in.readFloatBig();
  }
}

CFactoryFnReturn FScannableObjectInfoFactory(const SObjectTag& tag, CInputStream& in, const CVParamTransfer&,
                                             CObjectReference* selfRef) {
  return TToken<CScannableObjectInfo>::GetIObjObjectFor(std::make_unique<CScannableObjectInfo>(in, tag.id));
}
} // namespace urde


text:
namespace extensions {

InstallTracker::InstallTracker(content::BrowserContext* browser_context,
                               extensions::ExtensionPrefs* prefs)
    : extension_registry_observer_(this) {
  registrar_.Add(this,
                 extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED,
                 content::Source<content::BrowserContext>(browser_context));
  registrar_.Add(this,
                 chrome::NOTIFICATION_APP_INSTALLED_TO_APPLIST,
                 content::Source<content::BrowserContext>(browser_context));
  extension_registry_observer_.Add(ExtensionRegistry::Get(browser_context));

  // Prefs may be null in tests.
  if (prefs) {
    AppSorting* sorting = prefs->app_sorting();
    registrar_.Add(this,
                   chrome::NOTIFICATION_APP_LAUNCHER_REORDERED,
                   content::Source<AppSorting>(sorting));
    pref_change_registrar_.Init(prefs->pref_service());
    pref_change_registrar_.Add(
        pref_names::kExtensions,
        base::Bind(&InstallTracker::OnAppsReordered, base::Unretained(this)));
  }
}

InstallTracker::~InstallTracker() {
}

// static
InstallTracker* InstallTracker::Get(content::BrowserContext* context) {
  return InstallTrackerFactory::GetForBrowserContext(context);
}

void InstallTracker::AddObserver(InstallObserver* observer) {
  observers_.AddObserver(observer);
}

void InstallTracker::RemoveObserver(InstallObserver* observer) {
  observers_.RemoveObserver(observer);
}

const ActiveInstallData* InstallTracker::GetActiveInstall(
    const std::string& extension_id) const {
  ActiveInstallsMap::const_iterator install_data =
      active_installs_.find(extension_id);
  if (install_data == active_installs_.end())
    return NULL;
  else
    return &(install_data->second);
}

void InstallTracker::AddActiveInstall(const ActiveInstallData& install_data) {
  DCHECK(!install_data.extension_id.empty());
  DCHECK(active_installs_.find(install_data.extension_id) ==
         active_installs_.end());
  active_installs_.insert(
      std::make_pair(install_data.extension_id, install_data));
}

void InstallTracker::RemoveActiveInstall(const std::string& extension_id) {
  active_installs_.erase(extension_id);
}

void InstallTracker::OnBeginExtensionInstall(
    const InstallObserver::ExtensionInstallParams& params) {
  ActiveInstallsMap::iterator install_data =
      active_installs_.find(params.extension_id);
  if (install_data == active_installs_.end()) {
    ActiveInstallData install_data(params.extension_id);
    install_data.is_ephemeral = params.is_ephemeral;
    active_installs_.insert(std::make_pair(params.extension_id, install_data));
  }

  FOR_EACH_OBSERVER(InstallObserver, observers_,
                    OnBeginExtensionInstall(params));
}

void InstallTracker::OnBeginExtensionDownload(const std::string& extension_id) {
  FOR_EACH_OBSERVER(
      InstallObserver, observers_, OnBeginExtensionDownload(extension_id));
}

void InstallTracker::OnDownloadProgress(const std::string& extension_id,
                                        int percent_downloaded) {
  ActiveInstallsMap::iterator install_data =
      active_installs_.find(extension_id);
  if (install_data != active_installs_.end()) {
    install_data->second.percent_downloaded = percent_downloaded;
  } else {
    NOTREACHED();
  }

  FOR_EACH_OBSERVER(InstallObserver, observers_,
                    OnDownloadProgress(extension_id, percent_downloaded));
}

void InstallTracker::OnBeginCrxInstall(const std::string& extension_id) {
  FOR_EACH_OBSERVER(
      InstallObserver, observers_, OnBeginCrxInstall(extension_id));
}

void InstallTracker::OnFinishCrxInstall(const std::string& extension_id,
                                        bool success) {
  FOR_EACH_OBSERVER(
      InstallObserver, observers_, OnFinishCrxInstall(extension_id, success));
}

void InstallTracker::OnInstallFailure(
    const std::string& extension_id) {
  RemoveActiveInstall(extension_id);
  FOR_EACH_OBSERVER(InstallObserver, observers_,
                    OnInstallFailure(extension_id));
}

void InstallTracker::Shutdown() {
  FOR_EACH_OBSERVER(InstallObserver, observers_, OnShutdown());
}

void InstallTracker::Observe(int type,
                             const content::NotificationSource& source,
                             const content::NotificationDetails& details) {
  switch (type) {
    case extensions::NOTIFICATION_EXTENSION_UPDATE_DISABLED: {
      const Extension* extension =
          content::Details<const Extension>(details).ptr();
      FOR_EACH_OBSERVER(
          InstallObserver, observers_, OnDisabledExtensionUpdated(extension));
      break;
    }
    case chrome::NOTIFICATION_APP_LAUNCHER_REORDERED: {
      FOR_EACH_OBSERVER(InstallObserver, observers_, OnAppsReordered());
      break;
    }
    case chrome::NOTIFICATION_APP_INSTALLED_TO_APPLIST: {
      const std::string& extension_id(
          *content::Details<const std::string>(details).ptr());
      FOR_EACH_OBSERVER(InstallObserver, observers_,
                        OnAppInstalledToAppList(extension_id));
      break;
    }
    default:
      NOTREACHED();
  }
}

void InstallTracker::OnExtensionInstalled(
    content::BrowserContext* browser_context,
    const Extension* extension,
    bool is_update) {
  RemoveActiveInstall(extension->id());
}

void InstallTracker::OnAppsReordered() {
  FOR_EACH_OBSERVER(InstallObserver, observers_, OnAppsReordered());
}

}  // namespace extensions


text:
<?php
namespace Payum\Payex\Tests\Request\Api;

class InitializeOrderTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function shouldBeSubClassOfGeneric()
    {
        $rc = new \ReflectionClass('Payum\Payex\Request\Api\InitializeOrder');

        $this->assertTrue($rc->isSubclassOf('Payum\Core\Request\Generic'));
    }
}


text:
<?php

namespace Magento\User\Test\Block\Adminhtml\Role;

use Magento\Backend\Test\Block\Widget\FormTabs;

/**
 * Class RoleForm
 * Role edit form page
 */
class RoleForm extends FormTabs
{
    //
}


text:
var Generator = require('./generator'),
  EJSON = require('mongodb-extended-json'),
  es = require('event-stream'),
  stream = require('stream');

module.exports = function(size, schema){
  var dest = new Generator({size: size}),
    src = new stream.Readable({objectMode: true});

  src.push(schema);
  src.push(null);
  return src.pipe(dest);
};

module.exports.stringify = function(opts){
  opts = opts || {};
  opts.spaces = opts.spaces || undefined;
  var i = 0;
  return es.through(function(data){
    var s = EJSON.stringify(data, null, opts.spaces);
    var msg = i === 0 ? '[' + s : ',\n' + s;
    i++;
    this.emit('data', msg);
  }, function() {
    this.emit('data', ']\n');
    this.emit('end');
  });
};

module.exports.createGeneratorStream = function(opts){
  return new Generator(opts);
};


text:
#ifndef TENSORFLOW_COMPILER_XLA_SERVICE_CPU_ELEMENTAL_IR_EMITTER_H_
#define TENSORFLOW_COMPILER_XLA_SERVICE_CPU_ELEMENTAL_IR_EMITTER_H_

#include "external/llvm/include/llvm/IR/IRBuilder.h"
#include "external/llvm/include/llvm/IR/Module.h"
#include "external/llvm/include/llvm/IR/Value.h"
#include "tensorflow/compiler/xla/service/elemental_ir_emitter.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/statusor.h"

namespace xla {
namespace cpu {

class CpuElementalIrEmitter : public ElementalIrEmitter {
 public:
  CpuElementalIrEmitter(const HloModuleConfig& module_config,
                        llvm::IRBuilder<>* ir_builder, llvm::Module* module)
      : ElementalIrEmitter(module_config, module, ir_builder) {}

 protected:
  StatusOr<llvm::Value*> EmitFloatUnaryOp(
      const HloInstruction* op, llvm::Value* operand_value) const override;
};

}  // namespace cpu
}  // namespace xla

#endif  // TENSORFLOW_COMPILER_XLA_SERVICE_CPU_ELEMENTAL_IR_EMITTER_H_


text:
<?xml version="1.0" encoding="ISO-8859-1"?>

<screensaver name="cubestorm" _label="CubeStorm" gl="yes">

  <command arg="-root"/>

  <number id="delay" type="slider" arg="-delay %"
          _label="Frame rate" _low-label="Low" _high-label="High"
          low="0" high="100000" default="30000"
          convert="invert"/>

  <number id="speed" type="slider" arg="-speed %"
          _label="Speed" _low-label="Slow" _high-label="Fast"
          low="0.01" high="5.0" default="1.0"/>

  <number id="count" type="slider" arg="-count %"
          _label="Cubes" _low-label="Few" _high-label="Many"
          low="1" high="20" default="4"/>

  <number id="thickness" type="slider" arg="-thickness %"
          _label="Struts" _low-label="Thin" _high-label="Thick"
          low="0.01" high="1.0" default="0.06"/>

  <hgroup>
   <boolean id="wander" _label="Wander"    arg-unset="-no-wander"/>
   <boolean id="spin"   _label="Spin"      arg-unset="-no-spin"/>
   <boolean id="wire"   _label="Wireframe" arg-set="-wireframe"/>
  </hgroup>

  <boolean id="showfps" _label="Show frame rate" arg-set="-fps"/>

  <xscreensaver-updater />

  <_description>
Draws a series of rotating 3D boxes that intersect each other and
eventually fill space.

Written by Jamie Zawinski; 2003.
  </_description>
</screensaver>


text:
#!/usr/bin/env node

module.exports = function(context) {

    /** @external */
    var fs = context.requireCordovaModule('fs'),
        path = context.requireCordovaModule('path'),
        deferral = context.requireCordovaModule('q').defer(),
        ConfigParser = context.requireCordovaModule("cordova-lib/src/configparser/ConfigParser"),
        XmlHelpers = context.requireCordovaModule("cordova-lib/src/util/xml-helpers"),
        et = context.requireCordovaModule('elementtree');

    /** @defaults */
    var androidPlatformDir = path.join(context.opts.projectRoot,
            'platforms', 'android'),
        projectConfigurationFile = path.join(androidPlatformDir,
            'res', 'xml', 'config.xml'),
        projectManifestFile = path.join(androidPlatformDir,
            'AndroidManifest.xml');

    /** Init */
    var CordovaConfig = new ConfigParser(projectConfigurationFile);

    var addPermission = function() {
        var projectManifestXmlRoot = XmlHelpers.parseElementtreeSync(projectManifestFile);
        var child = et.XML('<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />');
        XmlHelpers.graftXML(projectManifestXmlRoot, [child], '/manifest');
        fs.writeFileSync(projectManifestFile, projectManifestXmlRoot.write({indent: 4}), 'utf-8');
    }

    /** Main method */
    var main = function() {
        if (CordovaConfig.getGlobalPreference('xwalkMode') == 'shared') {
            // Add the permission of write_external_storage in shared mode
            addPermission();
        }

        deferral.resolve();
    };

    main();

    return deferral.promise;

};


text:
package main

import (
	"fmt"
	"gopkg.in/BlueDragonX/go-hash.v1"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"text/template"
)

// Describes a template as part of a watcher.
type Template struct {
	Src  string
	Dest string
}

// Return true if one file differs from another.
func (t *Template) differs(fileA, fileB string) bool {
	var err error
	var hashA, hashB string
	if hashA, err = hash.File(fileA); err != nil {
		logger.Debugf("unable to hash file %s", fileA)
		return true
	}
	if hashB, err = hash.File(fileB); err != nil {
		logger.Debugf("unable to hash file %s", fileB)
		return true
	}
	return hashA != hashB
}

// Render the template to a temporary and return true if the original was changed.
func (t *Template) Render(context interface{}) (changed bool, err error) {
	// create the destination directory
	dir := filepath.Dir(t.Dest)
	if err = os.MkdirAll(dir, 0777); err != nil {
		return
	}

	// create a temp file to write
	var tmp *os.File
	prefix := fmt.Sprintf(".%s-", filepath.Base(t.Dest))
	if tmp, err = ioutil.TempFile(dir, prefix); err != nil {
		return
	}
	defer func() {
		tmp.Close()
		if !changed || err != nil {
			os.Remove(tmp.Name())
		}
	}()

	// add functions to the templates
	funcs := template.FuncMap{
		"replace":     strings.Replace,
		"addrHost":    AddrHost,
		"addrPort":    AddrPort,
		"urlScheme":   URLScheme,
		"urlUsername": URLUsername,
		"urlPassword": URLPassword,
		"urlHost":     URLHost,
		"urlPath":     URLPath,
		"urlRawQuery": URLRawQuery,
		"urlQuery":    URLQuery,
		"urlFragment": URLFragment,
		"json":        JSON,
	}

	// render the template to the temp file
	var tpl *template.Template
	name := filepath.Base(t.Src)
	if tpl, err = template.New(name).Funcs(funcs).ParseFiles(t.Src); err != nil {
		return
	}
	if err = tpl.Execute(tmp, context); err != nil {
		return
	}
	tmp.Close()

	// return if the old and new files are the same
	changed = t.differs(t.Dest, tmp.Name())
	if !changed {
		return
	}

	// replace the old file with the new one
	err = os.Rename(tmp.Name(), t.Dest)
	return
}


text:
package ipara.core.request;

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;

import ipara.core.Constants;
import ipara.core.CoreRequest;
import ipara.core.Helper;
import ipara.core.RestHttpCaller;
import ipara.core.Settings;
import ipara.core.entity.Product;
import ipara.core.entity.Purchaser;
import ipara.core.response.ThreeDPaymentCompleteResponse;

// 3D Secure ile ödeme 2. Adımında gerekli olan 3D servis girdi parametrelerini temsil eder.
@XmlRootElement(name = "auth")
public class ThreeDPaymentCompleteRequest extends CoreRequest {

	@XmlElement(name = "threeD")
	public String threeD;

	@XmlElement(name = "orderId")
	public String orderId;

	@XmlElement(name = "amount")
	public String amount;

	@XmlElement(name = "cardOwnerName")
	public String cardOwnerName;

	@XmlElement(name = "cardNumber")
	public String cardNumber;

	@XmlElement(name = "cardExpireMonth")
	public String cardExpireMonth;

	@XmlElement(name = "cardExpireYear")
	public String cardExpireYear;

	@XmlElement(name = "installment")
	public String installment;

	@XmlElement(name = "cardCvc")
	public String cvc;

	@XmlElement(name = "vendorId")
	public String vendorId;

	@XmlElement(name = "userId")
	public String userId;

	@XmlElement(name = "cardId")
	public String cardId;

	@XmlElement(name = "threeDSecureCode")
	public String threeDSecureCode;

	@XmlElementWrapper(name = "products")
	@XmlElement(name = "product")
	public List<Product> products;

	@XmlElement(name = "purchaser")
	public Purchaser purchaser;

	/*
	 *	3D Secure 2. Adımında ödeme onayı sağlanarak tahsilat gerçekleştirilmesi için gerekli olan servis isteğini temsil eder.
	 *	@request Ödeme Onayı sağlamak için gerekli olan girdilerin olduğu sınıfı temsil eder.
	 *	options Kullanıcıya özel olarak belirlenen ayarları temsil eder.
	*/
	public static ThreeDPaymentCompleteResponse execute(ThreeDPaymentCompleteRequest request, Settings settings) throws Exception {

        settings.transactionDate = Helper.getTransactionDateString();
        settings.hashString = settings.privateKey
                + request.orderId
                + request.amount
                + request.mode
                + request.threeDSecureCode
                + settings.transactionDate;
        return RestHttpCaller.getInstance().postXML(settings.baseUrl + "rest/payment/auth",
                Helper.getHttpHeaders(settings, Constants.ContentTypes.APPLICATION_XML_UTF8),
                request, ThreeDPaymentCompleteResponse.class);

    }

}


text:
WDIR=`pwd`
sudo apt-get update -y
sudo apt-get install -y npm git wget
#install npm
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.31.1/install.sh| sh
source ~/.nvm/nvm.sh
nvm install stable
nvm use stable
cd $WDIR
git clone https://github.com/babel/babel
cd $WDIR/babel/packages/babel-preset-react
npm install
# no tests


text:
./train_pushed.py --num-train 100 --num-val 40 --num-test 100 --batch-size 64\
    --network Inception --lr 1e-5 --feature-size 64 --reg 2e-3 --epochs 60 \
    --results-freq 10 --val-freq 2 --num-batches 10\
    --normalize-features  --num-clusters 1 --loss Soft
./train_pushed.py --num-train 100 --num-val 40 --num-test 100 --batch-size 64\
    --network Inception --lr 1e-5 --feature-size 64 --reg 1e-3 --epochs 60 \
    --results-freq 10 --val-freq 2 --num-batches 10\
    --normalize-features  --num-clusters 3 --loss Soft
#
#./train_pushed.py --num-train 100 --num-val 40 --num-test 100 --batch-size 64\
#    --network Inception --lr 1e-5 --feature-size 64 --reg 1e-3 --epochs 60 \
#    --results-freq 10 --val-freq 2 --num-batches 10\
#    --normalize-features  --num-clusters 3 --local-sampling
#./train_pushed.py --num-train 100 --num-val 40 --num-test 100 --batch-size 64\
#    --network Inception --lr 1e-6 --feature-size 64 --reg 1e-3 --epochs 60 \
#    --results-freq 10 --val-freq 2 --num-batches 10\
#    --normalize-features  --num-clusters 3 --loss Square  --local-sampling
./train_pushed.py --num-train 100 --num-val 40 --num-test 100 --batch-size 64\
    --network Inception --lr 1e-5 --feature-size 64 --reg 1e-3 --epochs 60 \
    --results-freq 10 --val-freq 2 --num-batches 10\
    --normalize-features  --num-clusters 3 --loss Soft  --local-sampling


text:
#include "mitab.h"
#include "mitab_utils.h"

#include <ctype.h>      /* isspace() */

/*=====================================================================
 *                      class TABSeamless
 *
 * Support for seamless vector datasets.
 *
 * The current implementation has some limitations (base assumptions):
 *  - Read-only
 *  - Base tables can only be of type TABFile
 *  - Feature Ids are build using the id of the base table in the main
 *    index table and the actual feature id of each object inside the base
 *    tables.  Since we are limited to 32 bits for feature ids, this implies
 *    a limit on the (number of base tables) * (features/table)
 *    The current implementation can support up to 2047 (0x7ff) base tables
 *    and a max of 1048575 (0xfffff) features per base table.
 *  - Only relative paths are supported for base tables names.
 *
 *====================================================================*/

/**********************************************************************
 *                   TABSeamless::TABSeamless()
 *
 * Constructor.
 **********************************************************************/
TABSeamless::TABSeamless()
{
    m_pszFname = NULL;
    m_pszPath = NULL;
    m_eAccessMode = TABRead;
    m_poFeatureDefnRef = NULL;
    m_poCurFeature = NULL;
    m_nCurFeatureId = -1;

    m_poIndexTable = NULL;
    m_nIndexTableFIDBits = 0;
    m_nIndexTableFIDMask = 0;
    m_nTableNameField = -1;
    m_nCurBaseTableId = -1;
    m_poCurBaseTable = NULL;
    m_bEOF = FALSE;
}

/**********************************************************************
 *                   TABSeamless::~TABSeamless()
 *
 * Destructor.
 **********************************************************************/
TABSeamless::~TABSeamless()
{
    Close();
}

void TABSeamless::ResetReading()
{
    if (m_poIndexTable)
        OpenBaseTable(-1);  // Asking for first table resets everything

    // Reset m_nCurFeatureId so that next pass via GetNextFeatureId()
    // will start from the beginning
    m_nCurFeatureId = -1;
}

/**********************************************************************
 *                   TABSeamless::Open()
 *
 * Open a seamless .TAB dataset and initialize the structures to be ready
 * to read features from it.
 *
 * Seamless .TAB files are composed of a main .TAB file in which each
 * feature is the MBR of a base table.
 *
 * Set bTestOpenNoError=TRUE to silently return -1 with no error message
 * if the file cannot be opened.  This is intended to be used in the
 * context of a TestOpen() function.  The default value is FALSE which
 * means that an error is reported if the file cannot be opened.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABSeamless::Open(const char *pszFname, const char *pszAccess,
                      GBool bTestOpenNoError /*= FALSE*/ )
{
    char nStatus = 0;

    if (m_poIndexTable)
    {
        CPLError(CE_Failure, CPLE_AssertionFailed,
                 "Open() failed: object already contains an open file");
        return -1;
    }

    /*-----------------------------------------------------------------
     * Validate access mode and call the right open method
     *----------------------------------------------------------------*/
    if (EQUALN(pszAccess, "r", 1))
    {
        m_eAccessMode = TABRead;
        nStatus = (char)OpenForRead(pszFname, bTestOpenNoError);
    }
    else
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "Open() failed: access mode \"%s\" not supported", pszAccess);
        return -1;
    }

    return nStatus;
}

/**********************************************************************
 *                   TABSeamless::OpenForRead()
 *
 * Open for reading
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABSeamless::OpenForRead(const char *pszFname,
                             GBool bTestOpenNoError /*= FALSE*/ )
{
    int nFnameLen = 0;

    m_eAccessMode = TABRead;

    /*-----------------------------------------------------------------
     * Read main .TAB (text) file
     *----------------------------------------------------------------*/
    m_pszFname = CPLStrdup(pszFname);

#ifndef _WIN32
    /*-----------------------------------------------------------------
     * On Unix, make sure extension uses the right cases
     * We do it even for write access because if a file with the same
     * extension already exists we want to overwrite it.
     *----------------------------------------------------------------*/
    TABAdjustFilenameExtension(m_pszFname);
#endif

    /*-----------------------------------------------------------------
     * Open .TAB file... since it's a small text file, we will just load
     * it as a stringlist in memory.
     *----------------------------------------------------------------*/
    char **papszTABFile = TAB_CSLLoad(m_pszFname);
    if (papszTABFile == NULL)
    {
        if (!bTestOpenNoError)
        {
            CPLError(CE_Failure, CPLE_FileIO,
                     "Failed opening %s.", m_pszFname);
        }

        CPLFree(m_pszFname);
        CSLDestroy(papszTABFile);
        return -1;
    }

    /*-------------------------------------------------------------
     * Look for a metadata line with "\IsSeamless" = "TRUE".
     * If there is no such line, then we may have a valid .TAB file,
     * but we do not support it in this class.
     *------------------------------------------------------------*/
    GBool bSeamlessFound = FALSE;
    for (int i=0; !bSeamlessFound && papszTABFile && papszTABFile[i]; i++)
    {
        const char *pszStr = papszTABFile[i];
        while(*pszStr != '\0' && isspace((unsigned char)*pszStr))
            pszStr++;
        if (EQUALN(pszStr, "\"\\IsSeamless\" = \"TRUE\"", 21))
            bSeamlessFound = TRUE;
    }
    CSLDestroy(papszTABFile);

    if ( !bSeamlessFound )
    {
        if (!bTestOpenNoError)
            CPLError(CE_Failure, CPLE_NotSupported,
                     "%s does not appear to be a Seamless TAB File.  "
                     "This type of .TAB file cannot be read by this library.",
                     m_pszFname);
        else
            CPLErrorReset();

        CPLFree(m_pszFname);

        return -1;
    }

    /*-----------------------------------------------------------------
     * OK, this appears to be a valid seamless TAB dataset...
     * Extract the path component from the main .TAB filename
     * to build the filename of the base tables
     *----------------------------------------------------------------*/
    m_pszPath = CPLStrdup(m_pszFname);
    nFnameLen = strlen(m_pszPath);
    for( ; nFnameLen > 0; nFnameLen--)
    {
        if (m_pszPath[nFnameLen-1] == '/' ||
            m_pszPath[nFnameLen-1] == '\\' )
        {
            break;
        }
        m_pszPath[nFnameLen-1] = '\0';
    }

    /*-----------------------------------------------------------------
     * Open the main Index table and look for the "Table" field that
     * should contain the path to the base table for each rectangle MBR
     *----------------------------------------------------------------*/
    m_poIndexTable = new TABFile;
    if (m_poIndexTable->Open(m_pszFname, "rb", bTestOpenNoError) != 0)
    {
        // Open Failed... an error has already been reported, just return.
        if (bTestOpenNoError)
            CPLErrorReset();
        Close();
        return -1;
    }

    OGRFeatureDefn *poDefn = m_poIndexTable->GetLayerDefn();
    if (poDefn == NULL ||
        (m_nTableNameField = poDefn->GetFieldIndex("Table")) == -1)
    {
        if (!bTestOpenNoError)
            CPLError(CE_Failure, CPLE_NotSupported,
                     "Open Failed: Field 'Table' not found in Seamless "
                     "Dataset '%s'.  This is type of file not currently "
                     "supported.",
                     m_pszFname);
        Close();
        return -1;
    }

    /* Set the number of bits required to encode features for this index
     * table. (Based of the number of features)
     */
    int s=0, numFeatures = m_poIndexTable->GetFeatureCount(FALSE);
    do s++, numFeatures>>=1; while(numFeatures);
    m_nIndexTableFIDBits= s+1;

    /*-----------------------------------------------------------------
     * We need to open the first table to get its FeatureDefn
     *----------------------------------------------------------------*/
    if (OpenBaseTable(-1, bTestOpenNoError) != 0 )
    {
        // Open Failed... an error has already been reported, just return.
        if (bTestOpenNoError)
            CPLErrorReset();
        Close();
        return -1;
    }

    CPLAssert(m_poCurBaseTable);
    m_poFeatureDefnRef = m_poCurBaseTable->GetLayerDefn();
    m_poFeatureDefnRef->Reference();

    return 0;
}

/**********************************************************************
 *                   TABSeamless::Close()
 *
 * Close current file, and release all memory used.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABSeamless::Close()
{
    if (m_poIndexTable)
        delete m_poIndexTable;  // Automatically closes.
    m_poIndexTable = NULL;

    if (m_poFeatureDefnRef && m_poFeatureDefnRef->Dereference() == 0)
        delete m_poFeatureDefnRef;
    m_poFeatureDefnRef = NULL;

    if (m_poCurFeature)
        delete m_poCurFeature;
    m_poCurFeature = NULL;
    m_nCurFeatureId = -1;

    CPLFree(m_pszFname);
    m_pszFname = NULL;

    CPLFree(m_pszPath);
    m_pszPath = NULL;

    m_nTableNameField = -1;
    m_nCurBaseTableId = -1;

    if (m_poCurBaseTable)
        delete m_poCurBaseTable;
    m_poCurBaseTable = NULL;

    return 0;
}

/**********************************************************************
 *                   TABSeamless::OpenBaseTable()
 *
 * Open the base table for specified IndexFeature.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABSeamless::OpenBaseTable(TABFeature *poIndexFeature,
                               GBool bTestOpenNoError /*=FALSE*/)
{
    CPLAssert(poIndexFeature);

    /*-----------------------------------------------------------------
     * Fetch table id.  We actually use the index feature's ids as the
     * base table ids.
     *----------------------------------------------------------------*/
    int nTableId = poIndexFeature->GetFID();

    if (m_nCurBaseTableId == nTableId && m_poCurBaseTable != NULL)
    {
        // The right table is already opened.  Not much to do!
        m_poCurBaseTable->ResetReading();
        return 0;
    }

    // Close current base table
    if (m_poCurBaseTable)
        delete m_poCurBaseTable;
    m_nCurBaseTableId = -1;

    m_bEOF = FALSE;

    /*-----------------------------------------------------------------
     * Build full path to the table and open it.
     * __TODO__ For now we assume that all table filename paths are relative
     *          but we may have to deal with absolute filenames as well.
     *----------------------------------------------------------------*/
    const char *pszName = poIndexFeature->GetFieldAsString(m_nTableNameField);
    char *pszFname = CPLStrdup(CPLSPrintf("%s%s", m_pszPath, pszName));

#ifndef _WIN32
    // On Unix, replace any '\\' in path with '/'
    char *pszPtr = pszFname;
    while((pszPtr = strchr(pszPtr, '\\')) != NULL)
    {
        *pszPtr = '/';
        pszPtr++;
    }
#endif

    m_poCurBaseTable = new TABFile;
    if (m_poCurBaseTable->Open(pszFname, "rb", bTestOpenNoError) != 0)
    {
        // Open Failed... an error has already been reported, just return.
        if (bTestOpenNoError)
            CPLErrorReset();
        delete m_poCurBaseTable;
        m_poCurBaseTable = NULL;
        CPLFree(pszFname);
        return -1;
    }

    /* Set the number of bits required to encode feature id for this base
     * table. (Based of the number of features) This will be used for
     * encode and extract feature ID.
     */
    int s=0, nCurBaseTableFIDBits = 0,
        numFeatures = m_poCurBaseTable->GetFeatureCount(FALSE);
    do s++, numFeatures>>=1; while(numFeatures);
    nCurBaseTableFIDBits = s;

    /* Check if we can encode feature IDs in 32 bits to avoid overflow */
    if (nCurBaseTableFIDBits + m_nIndexTableFIDBits > 32)
    {
        CPLError(CE_Failure, CPLE_NotSupported,
                 "Open() failed: feature ids cannot be encoded in 32 bits "
                 "for the index table (%s) and the base table (%s).",
                 m_pszFname, pszName);
        if (bTestOpenNoError)
            CPLErrorReset();
        delete m_poCurBaseTable;
        m_poCurBaseTable = NULL;
        CPLFree(pszFname);
        return -1;
    }

    m_nIndexTableFIDMask = (32-m_nIndexTableFIDBits);

    // Set the spatial filter to the new table
    if( m_poFilterGeom != NULL &&  m_poCurBaseTable )
    {
        m_poCurBaseTable->SetSpatialFilter( m_poFilterGeom );
    }

    m_nCurBaseTableId = nTableId;
    CPLFree(pszFname);

    return 0;
}

/**********************************************************************
 *                   TABSeamless::OpenBaseTable()
 *
 * Open the base table for specified IndexFeature.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABSeamless::OpenBaseTable(int nTableId, GBool bTestOpenNoError /*=FALSE*/)
{

    if (nTableId == -1)
    {
        // Open first table from dataset
        m_poIndexTable->ResetReading();
        if (OpenNextBaseTable(bTestOpenNoError) != 0)
        {
            // Open Failed... an error has already been reported.
            if (bTestOpenNoError)
                CPLErrorReset();
            return -1;
        }
    }
    else if (nTableId == m_nCurBaseTableId && m_poCurBaseTable != NULL)
    {
        // The right table is already opened.  Not much to do!
        m_poCurBaseTable->ResetReading();
        return 0;
    }
    else
    {
        TABFeature *poIndexFeature = m_poIndexTable->GetFeatureRef(nTableId);

        if (poIndexFeature)
        {
            if (OpenBaseTable(poIndexFeature, bTestOpenNoError) != 0)
            {
                // Open Failed... an error has already been reported.
                if (bTestOpenNoError)
                    CPLErrorReset();
                return -1;
            }
        }
    }

    return 0;
}

/**********************************************************************
 *                   TABSeamless::OpenNextBaseTable()
 *
 * Open the next base table in the dataset, using GetNextFeature() so that
 * the spatial filter is respected.
 *
 * m_bEOF will be set if there are no more base tables to read.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABSeamless::OpenNextBaseTable(GBool bTestOpenNoError /*=FALSE*/)
{
    CPLAssert(m_poIndexTable);

    TABFeature *poIndexFeature = (TABFeature*)m_poIndexTable->GetNextFeature();

    if (poIndexFeature)
    {
        if (OpenBaseTable(poIndexFeature, bTestOpenNoError) != 0)
        {
            // Open Failed... an error has already been reported.
            if (bTestOpenNoError)
                CPLErrorReset();
            delete poIndexFeature;
            return -1;
        }
        delete poIndexFeature;
        m_bEOF = FALSE;
    }
    else
    {
        // Reached EOF
        m_bEOF = TRUE;
    }

    return 0;
}

/**********************************************************************
 *                   TABSeamless::EncodeFeatureId()
 *
 * Combine the table id + feature id into a single feature id that should
 * be unique amongst all base tables in this seamless dataset.
 *
 * We reserve some bits in the feature id for the table id based on the
 * number of features in the index table.  This reduces the available range
 * of feature ids for each base table... for instance, if the index contains
 * 65000 entries, then each base table will be limited to 65535 features.
 *
 * If the number of features in a base table exceeds the number of bits
 * available (e.g. 65535 inthe above example) then the feature ids will
 * wrap for this table and thus it will be impossible to access some of
 * the features unless the caller uses only calls to GetNextFeature() and
 * avoids calls to GetFeatureRef().
 **********************************************************************/
int TABSeamless::EncodeFeatureId(int nTableId, int nBaseFeatureId)
{
    if (nTableId == -1 || nBaseFeatureId == -1)
        return -1;

    /* Feature encoding is now based on the numbers of bits on the number
       of features in the index table. */

    return ((nTableId<<m_nIndexTableFIDMask) + nBaseFeatureId);
}

int TABSeamless::ExtractBaseTableId(int nEncodedFeatureId)
{
    if (nEncodedFeatureId == -1)
        return -1;

    return ((nEncodedFeatureId>>m_nIndexTableFIDMask));
}

int TABSeamless::ExtractBaseFeatureId(int nEncodedFeatureId)
{
    if (nEncodedFeatureId == -1)
        return -1;

    return (nEncodedFeatureId & (1<<m_nIndexTableFIDMask)-1);
}

/**********************************************************************
 *                   TABSeamless::GetNextFeatureId()
 *
 * Returns feature id that follows nPrevId, or -1 if it is the
 * last feature id.  Pass nPrevId=-1 to fetch the first valid feature id.
 **********************************************************************/
int TABSeamless::GetNextFeatureId(int nPrevId)
{
    if (m_poIndexTable == NULL)
        return -1; // File is not opened yet

    if (nPrevId == -1 || m_nCurBaseTableId != ExtractBaseTableId(nPrevId))
    {
        if (OpenBaseTable(ExtractBaseTableId(nPrevId)) != 0)
            return -1;
    }

    int nId = ExtractBaseFeatureId(nPrevId);
    do
    {
        nId = m_poCurBaseTable->GetNextFeatureId(nId);
        if (nId != -1)
            return EncodeFeatureId(m_nCurBaseTableId, nId);  // Found one!
        else
            OpenNextBaseTable();  // Skip to next tile and loop again

    } while (nId == -1 && !m_bEOF && m_poCurBaseTable);

    return -1;
}

/**********************************************************************
 *                   TABSeamless::GetFeatureRef()
 *
 * Fill and return a TABFeature object for the specified feature id.
 *
 * The returned pointer is a reference to an object owned and maintained
 * by this TABSeamless object.  It should not be altered or freed by the
 * caller and its contents is guaranteed to be valid only until the next
 * call to GetFeatureRef() or Close().
 *
 * Returns NULL if the specified feature id does not exist of if an
 * error happened.  In any case, CPLError() will have been called to
 * report the reason of the failure.
 **********************************************************************/
TABFeature *TABSeamless::GetFeatureRef(int nFeatureId)
{
    if (m_poIndexTable == NULL)
        return NULL; // File is not opened yet

    if (nFeatureId == m_nCurFeatureId && m_poCurFeature)
        return m_poCurFeature;

    if (m_nCurBaseTableId != ExtractBaseTableId(nFeatureId))
    {
        if (OpenBaseTable(ExtractBaseTableId(nFeatureId)) != 0)
            return NULL;
    }

    if (m_poCurBaseTable)
    {
        if (m_poCurFeature)
            delete m_poCurFeature;

        m_poCurFeature = (TABFeature*)m_poCurBaseTable->GetFeature(ExtractBaseFeatureId(nFeatureId));
        m_nCurFeatureId = nFeatureId;

        m_poCurFeature->SetFID(nFeatureId);

        return m_poCurFeature;
    }

    return NULL;
}

/**********************************************************************
 *                   TABSeamless::GetLayerDefn()
 *
 * Returns a reference to the OGRFeatureDefn that will be used to create
 * features in this dataset.
 *
 * Returns a reference to an object that is maintained by this TABSeamless
 * object (and thus should not be modified or freed by the caller) or
 * NULL if the OGRFeatureDefn has not been initialized yet (i.e. no file
 * opened yet)
 **********************************************************************/
OGRFeatureDefn *TABSeamless::GetLayerDefn()
{
    return m_poFeatureDefnRef;
}

/**********************************************************************
 *                   TABSeamless::GetNativeFieldType()
 *
 * Returns the native MapInfo field type for the specified field.
 *
 * Returns TABFUnknown if file is not opened, or if specified field index is
 * invalid.
 *
 * Note that field ids are positive and start at 0.
 **********************************************************************/
TABFieldType TABSeamless::GetNativeFieldType(int nFieldId)
{
    if (m_poCurBaseTable)
        return m_poCurBaseTable->GetNativeFieldType(nFieldId);

    return TABFUnknown;
}

/**********************************************************************
 *                   TABSeamless::IsFieldIndexed()
 *
 * Returns TRUE if field is indexed, or FALSE otherwise.
 **********************************************************************/
GBool TABSeamless::IsFieldIndexed(int nFieldId)
{
    if (m_poCurBaseTable)
        return m_poCurBaseTable->IsFieldIndexed(nFieldId);

    return FALSE;
}

/**********************************************************************
 *                   TABSeamless::IsFieldUnique()
 *
 * Returns TRUE if field is in the Unique table, or FALSE otherwise.
 **********************************************************************/
GBool TABSeamless::IsFieldUnique(int nFieldId)
{
    if (m_poCurBaseTable)
        return m_poCurBaseTable->IsFieldUnique(nFieldId);

    return FALSE;
}

/**********************************************************************
 *                   TABSeamless::GetBounds()
 *
 * Fetch projection coordinates bounds of a dataset.
 *
 * The bForce flag has no effect on TAB files since the bounds are
 * always in the header.
 *
 * Returns 0 on success, -1 on error.
 **********************************************************************/
int TABSeamless::GetBounds(double &dXMin, double &dYMin,
                       double &dXMax, double &dYMax,
                       GBool bForce /*= TRUE*/)
{
    if (m_poIndexTable == NULL)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
             "GetBounds() can be called only after dataset has been opened.");
        return -1;
    }

    return m_poIndexTable->GetBounds(dXMin, dYMin, dXMax, dYMax, bForce);
}

/**********************************************************************
 *                   TABSeamless::GetExtent()
 *
 * Fetch extent of the data currently stored in the dataset.
 *
 * The bForce flag has no effect on TAB files since that value is
 * always in the header.
 *
 * Returns OGRERR_NONE/OGRRERR_FAILURE.
 **********************************************************************/
OGRErr TABSeamless::GetExtent (OGREnvelope *psExtent, int bForce)
{
    if (m_poIndexTable == NULL)
    {
        CPLError(CE_Failure, CPLE_AppDefined,
             "GetExtent() can be called only after dataset has been opened.");
        return OGRERR_FAILURE;
    }

    return m_poIndexTable->GetExtent(psExtent, bForce);

}

/**********************************************************************
 *                   TABSeamless::GetFeatureCountByType()
 *
 * Return number of features of each type.
 *
 * Note that the sum of the 4 returned values may be different from
 * the total number of features since features with NONE geometry
 * are not taken into account here.
 *
 * Returns 0 on success, or silently returns -1 (with no error) if this
 * information is not available.
 **********************************************************************/
int TABSeamless::GetFeatureCountByType(CPL_UNUSED int &numPoints, CPL_UNUSED int &numLines,
                                       CPL_UNUSED int &numRegions, CPL_UNUSED int &numTexts,
                                       CPL_UNUSED GBool bForce /*= TRUE*/)
{
    /*-----------------------------------------------------------------
     * __TODO__  This should be implemented to return -1 if force=false,
     * or scan all the base tables if force=true
     *----------------------------------------------------------------*/

    return -1;
}

int TABSeamless::GetFeatureCount(int bForce)
{
    /*-----------------------------------------------------------------
     * __TODO__  This should be implemented to return -1 if force=false,
     * or scan all the base tables if force=true
     *----------------------------------------------------------------*/

    return OGRLayer::GetFeatureCount(bForce);
}

/**********************************************************************
 *                   TABSeamless::GetSpatialRef()
 *
 * Returns a reference to an OGRSpatialReference for this dataset.
 * If the projection parameters have not been parsed yet, then we will
 * parse them before returning.
 *
 * The returned object is owned and maintained by this TABFile and
 * should not be modified or freed by the caller.
 *
 * Returns NULL if the SpatialRef cannot be accessed.
 **********************************************************************/
OGRSpatialReference *TABSeamless::GetSpatialRef()
{
    if (m_poIndexTable == NULL)
    {
        CPLError(CE_Failure, CPLE_AssertionFailed,
                 "GetSpatialRef() failed: file has not been opened yet.");
        return NULL;
    }

    return m_poIndexTable->GetSpatialRef();
}

/**********************************************************************
 *                   IMapInfoFile::SetSpatialFilter()
 *
 * Standard OGR SetSpatialFiltere implementation.  This methode is used
 * to set a SpatialFilter for this OGRLayer
 **********************************************************************/
void TABSeamless::SetSpatialFilter (OGRGeometry * poGeomIn )

{
    IMapInfoFile::SetSpatialFilter( poGeomIn );

    if( m_poIndexTable )
        m_poIndexTable->SetSpatialFilter( poGeomIn );

    if( m_poCurBaseTable )
        m_poCurBaseTable->SetSpatialFilter( poGeomIn );
}

/************************************************************************/
/*                           TestCapability()                           */
/************************************************************************/

int TABSeamless::TestCapability( const char * pszCap )

{
    if( EQUAL(pszCap,OLCRandomRead) )
        return TRUE;

    else if( EQUAL(pszCap,OLCSequentialWrite)
             || EQUAL(pszCap,OLCRandomWrite) )
        return FALSE;

    else if( EQUAL(pszCap,OLCFastFeatureCount) )
        return FALSE;

    else if( EQUAL(pszCap,OLCFastSpatialFilter) )
        return FALSE;

    else if( EQUAL(pszCap,OLCFastGetExtent) )
        return TRUE;

    else
        return FALSE;
}

/**********************************************************************
 *                   TABSeamless::Dump()
 *
 * Dump block contents... available only in DEBUG mode.
 **********************************************************************/
#ifdef DEBUG

void TABSeamless::Dump(FILE *fpOut /*=NULL*/)
{
    if (fpOut == NULL)
        fpOut = stdout;

    fprintf(fpOut, "----- TABSeamless::Dump() -----\n");

    if (m_poIndexTable == NULL)
    {
        fprintf(fpOut, "File is not opened.\n");
    }
    else
    {
        fprintf(fpOut, "File is opened: %s\n", m_pszFname);

    }

    fflush(fpOut);
}

#endif // DEBUG


text:
var _ = require('lodash');
var ReflectionFunction = require('./ReflectionFunction');

var ReflectionFunctionExpression = function (node) {
  ReflectionFunction.call(this, node);
  this._type = ReflectionFunction.TYPE.EXPRESSION;
};

ReflectionFunctionExpression.prototype = Object.create(ReflectionFunction.prototype);

ReflectionFunctionExpression.prototype.isAnonymous = function () {
  return _.isEmpty(_.get(this._node, 'id', null));
};

ReflectionFunctionExpression.prototype.isAssigned = function () {
  return false;
};

module.exports = ReflectionFunctionExpression;


text:
package hu.bme.mit.sette.snippets._4_generics.dependencies;

import hu.bme.mit.sette.common.annotations.SetteDependency;

/**
 * A generic collection used by the code snippets. This collection holds exactly 3 elements of the
 * specified type.
 *
 * @param <T>the
 *            type of elements in this collection
 */
@SetteDependency
public class GenericTriplet<T> {
    private final Object[] array = new Object[3];

    public GenericTriplet(T item1, T item2, T item3) {
        this.array[0] = item1;
        this.array[1] = item2;
        this.array[2] = item3;
    }

    @SuppressWarnings("unchecked")
    public T get(int index) {
        // possible bad indexing!
        return (T) this.array[index];
    }

    public T set(int index, T newItem) {
        // possible bad indexing!
        T old = this.get(index);
        this.array[index] = newItem;
        return old;
    }

    public int size() {
        return this.array.length;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearPanel
  xmlns="http://schemas.exlauncher.com/exlauncher"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://schemas.exlauncher.com/exlauncher ../../schema/screen.xsd"
  width="*"
  height="*"
  orientation="vertical">

  <LinearPanel
    width="*"
    height="38"
    orientation="horizontal">

    <Label
      width="*"
      height="38"
      layoutMargin="2 0 20 0"
      text="{categoryName}"
      textSize="24"
      textColor="white"
      font="light"
      letterCase="upper" />

    <Clock
      width="100"
      height="content"
      layoutMargin="0 0 0 20"
      layoutGravity="center_vertical"
      gravity="right"
      font="regular"
      textSize="20"
      textStyle="plain"
      type="timeShort" />

  </LinearPanel>

  <GridView
    id="inputView"
    tag="fillItems|categories={category}"
    width="*"
    height="*"
    orientation="vertical"
    itemTemplate="@theme/appTemplate.xml"
    itemWidth="77"
    itemHeight="54"
    layoutMargin="4 5 5 5"
    verticalSpacing="8"
    contentInset="0 5"
    background="#50000000">
  </GridView>
</LinearPanel>


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

namespace FileHelpers.Tests
{
    [FixedLengthRecord]
    public class OrdersFixed
    {
        [FieldFixedLength(7)]
        public int OrderID;

        [FieldFixedLength(12)]
        public string CustomerID;

        [FieldFixedLength(3)]
        public int EmployeeID;

        [FieldFixedLength(10)]
        public DateTime OrderDate;

        [FieldFixedLength(10)]
        public DateTime RequiredDate;

        [FieldFixedLength(10)]
        [FieldNullValue(typeof (DateTime), "2005-1-1")]
        public DateTime ShippedDate;

        [FieldFixedLength(3)]
        public int ShipVia;

        [FieldFixedLength(10)]
        public decimal Freight;
    }
}


text: @import "./lib/md-align";


text:
import type { SpanningCellParameters } from './spanningCellManager';
import type { RangeConfig } from './types/internal';
export declare const calculateSpanningCellWidth: (rangeConfig: RangeConfig, dependencies: SpanningCellParameters) => number;


text: docker build --tag="kurron/gradle" .


text:
#region MIT license
//
// MIT license
//
// Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using nwind;

namespace DbLinq.Mssql.Example
{
    class Program
    {
        static void Main(string[] args)
        {
            string connStr = "Data Source=.\\SQLExpress;Integrated Security=True;Initial Catalog=Northwind";
             Northwind db = new Northwind(new SqlConnection(connStr));

            var res = from cust in db.Customers
                      select cust.CompanyName;

            foreach (var r in res.ToList())
                Console.WriteLine(r);

            //var regions = db.Regions.ToList();

            //Vendor.UseBulkInsert[db.Regions] = true;
            //db.Regions.Add(new Region(-1, "tmp_region1"));
            //db.Regions.Add(new Region(-2, "tmp_region2"));

            //DbLinq.vendor.mssql.VendorMssql.UseBulkInsert[db.Shippers] = true;
            //db.Shippers.Add(new Shippers(-1, "UPS", "800-800-8888"));
            //db.Shippers.Add(new Shippers(-1, "Fedex", "900-900-9999"));
            //db.SubmitChanges();

        }
    }
}


text:
using System.Reflection;

namespace Forte.ContentfulSchema.Discovery
{
    public interface IContentTypeFieldNamingConvention
    {
        string GetFieldId(PropertyInfo property);
        string GetFieldName(PropertyInfo property);
    }
}