text:
/**
 * Base class for any Ext.Component that may contain other Components. Containers handle the basic behavior of
 * containing items, namely adding, inserting and removing items.
 *
 * The most commonly used Container classes are Ext.panel.Panel, Ext.window.Window and
 * Ext.tab.Panel. If you do not need the capabilities offered by the aforementioned classes you can create a
 * lightweight Container to be encapsulated by an HTML element to your specifications by using the
 * {@link Ext.Component#autoEl autoEl} config option.
 *
 * The code below illustrates how to explicitly create a Container:
 *
 *     @example
 *     // Explicitly create a Container
 *     Ext.create('Ext.container.Container', {
 *         layout: {
 *             type: 'hbox'
 *         },
 *         width: 400,
 *         renderTo: Ext.getBody(),
 *         border: 1,
 *         style: {borderColor:'#000000', borderStyle:'solid', borderWidth:'1px'},
 *         defaults: {
 *             labelWidth: 80,
 *             // implicitly create Container by specifying xtype
 *             xtype: 'datefield',
 *             flex: 1,
 *             style: {
 *                 padding: '10px'
 *             }
 *         },
 *         items: [{
 *             xtype: 'datefield',
 *             name: 'startDate',
 *             fieldLabel: 'Start date'
 *         },{
 *             xtype: 'datefield',
 *             name: 'endDate',
 *             fieldLabel: 'End date'
 *         }]
 *     });
 *
 * ## Layout
 *
 * Container classes delegate the rendering of child Components to a layout manager class which must be configured into
 * the Container using the `{@link #layout}` configuration property.
 *
 * When either specifying child `{@link #cfg-items}` of a Container, or dynamically {@link #method-add adding} Components to a
 * Container, remember to consider how you wish the Container to arrange those child elements, and whether those child
 * elements need to be sized using one of Ext's built-in `{@link #layout}` schemes. By default, Containers use the
 * {@link Ext.layout.container.Auto Auto} scheme which only renders child components, appending them one after the other
 * inside the Container, and **does not apply any sizing** at all.
 *
 * A common mistake is when a developer neglects to specify a `{@link #layout}` (e.g. widgets like GridPanels or
 * TreePanels are added to Containers for which no `{@link #layout}` has been specified). If a Container is left to
 * use the default {@link Ext.layout.container.Auto Auto} scheme, none of its child components will be resized, or changed in
 * any way when the Container is resized.
 *
 * Certain layout managers allow dynamic addition of child components. Those that do include
 * Ext.layout.container.Card, Ext.layout.container.Anchor, Ext.layout.container.VBox,
 * Ext.layout.container.HBox, and Ext.layout.container.Table. For example:
 *
 *     //  Create the GridPanel.
 *     var myNewGrid = Ext.create('Ext.grid.Panel', {
 *         store: myStore,
 *         headers: myHeaders,
 *         title: 'Results', // the title becomes the title of the tab
 *     });
 *
 *     myTabPanel.add(myNewGrid); // {@link Ext.tab.Panel} implicitly uses {@link Ext.layout.container.Card Card}
 *     myTabPanel.{@link Ext.tab.Panel#setActiveTab setActiveTab}(myNewGrid);
 *
 * The example above adds a newly created GridPanel to a TabPanel. Note that a TabPanel uses {@link
 * Ext.layout.container.Card} as its layout manager which means all its child items are sized to {@link
 * Ext.layout.container.Fit fit} exactly into its client area.
 *
 * **_Overnesting is a common problem_**. An example of overnesting occurs when a GridPanel is added to a TabPanel by
 * wrapping the GridPanel _inside_ a wrapping Panel (that has no `{@link #layout}` specified) and then add that
 * wrapping Panel to the TabPanel. The point to realize is that a GridPanel **is** a Component which can be added
 * directly to a Container. If the wrapping Panel has no `{@link #layout}` configuration, then the overnested
 * GridPanel will not be sized as expected.
 *
 * ## Adding via remote configuration
 *
 * A server side script can be used to add Components which are generated dynamically on the server. An example of
 * adding a GridPanel to a TabPanel where the GridPanel is generated by the server based on certain parameters:
 *
 *     // execute an Ajax request to invoke server side script:
 *     Ext.Ajax.request({
 *         url: 'gen-invoice-grid.php',
 *         // send additional parameters to instruct server script
 *         params: {
 *             startDate: Ext.getCmp('start-date').getValue(),
 *             endDate: Ext.getCmp('end-date').getValue()
 *         },
 *         // process the response object to add it to the TabPanel:
 *         success: function(xhr) {
 *             var newComponent = eval(xhr.responseText); // see discussion below
 *             myTabPanel.add(newComponent); // add the component to the TabPanel
 *             myTabPanel.setActiveTab(newComponent);
 *         },
 *         failure: function() {
 *             Ext.Msg.alert("Grid create failed", "Server communication failure");
 *         }
 *     });
 *
 * The server script needs to return a JSON representation of a configuration object, which, when decoded will return a
 * config object with an {@link Ext.Component#xtype xtype}. The server might return the following JSON:
 *
 *     {
 *         "xtype": 'grid',
 *         "title": 'Invoice Report',
 *         "store": {
 *             "model": 'Invoice',
 *             "proxy": {
 *                 "type": 'ajax',
 *                 "url": 'get-invoice-data.php',
 *                 "reader": {
 *                     "type": 'json'
 *                     "record": 'transaction',
 *                     "idProperty": 'id',
 *                     "totalRecords": 'total'
 *                 })
 *             },
 *             "autoLoad": {
 *                 "params": {
 *                     "startDate": '01/01/2008',
 *                     "endDate": '01/31/2008'
 *                 }
 *             }
 *         },
 *         "headers": [
 *             {"header": "Customer", "width": 250, "dataIndex": 'customer', "sortable": true},
 *             {"header": "Invoice Number", "width": 120, "dataIndex": 'invNo', "sortable": true},
 *             {"header": "Invoice Date", "width": 100, "dataIndex": 'date', "renderer": Ext.util.Format.dateRenderer('M d, y'), "sortable": true},
 *             {"header": "Value", "width": 120, "dataIndex": 'value', "renderer": 'usMoney', "sortable": true}
 *         ]
 *     }
 *
 * When the above code fragment is passed through the `eval` function in the success handler of the Ajax request, the
 * result will be a config object which, when added to a Container, will cause instantiation of a GridPanel. **Be sure
 * that the Container is configured with a layout which sizes and positions the child items to your requirements.**
 *
 * **Note:** since the code above is _generated_ by a server script, the `autoLoad` params for the Store, the user's
 * preferred date format, the metadata to allow generation of the Model layout, and the ColumnModel can all be generated
 * into the code since these are all known on the server.
 */
Ext.define('Ext.container.Container', {
    extend: 'Ext.container.AbstractContainer',
    alias: 'widget.container',
    alternateClassName: 'Ext.Container',

    /**
     * Return the immediate child Component in which the passed element is located.
     * @param {Ext.Element/HTMLElement/String} el The element to test (or ID of element).
     * @param {Boolean} deep If `true`, returns the deepest descendant Component which contains the passed element.
     * @return {Ext.Component} The child item which contains the passed element.
     */
    getChildByElement: function(el, deep) {
        var item,
            itemEl,
            i = 0,
            it = this.getRefItems(),
            ln = it.length;

        el = Ext.getDom(el);
        for (; i < ln; i++) {
            item = it[i];
            itemEl = item.getEl();
            if (itemEl && ((itemEl.dom === el) || itemEl.contains(el))) {
                return (deep && item.getChildByElement) ? item.getChildByElement(el, deep) : item;
            }
        }
        return null;
    }
});


text:
>   Trawl is a WebApp to analyse your behaviour on social media sites.

## License

Code is licensed under MIT. Content is licensed under CC-BY-SA 3.0. See the LICENSE file for details.

## Setup

After cloning this repo you need to run `npm install` to install all the needed dependencies.

## First start the Node Server in an own terminal instance:
```bash
    npm run start:dev
```

## Grunt Commands
```bash
    grunt serve             starts a watch task for js and scss changes
    grunt build             builds all files for deployment
```

Tasks
 - Fade in Hashtagcloud (create scroll service) [DONE]
 - Header textilate effect                      [DONE]
 - fix map design                               [DONE]
 - add activity section                         [DONE]
 - remove subpages for release                  [DONE]
 - fix routing change bug (destroy correctly)
 - create master release
 - deploy
 - create presentation

redpajama_set_name: RedPajamaGithub


text:
namespace crashpad {
namespace test {
namespace {

// Runs the RegistrationServer on a background thread.
class RunServerThread : public Thread {
 public:
  // Instantiates a thread which will invoke server->Run(pipe_name, delegate).
  RunServerThread(RegistrationServer* server,
                  const base::string16& pipe_name,
                  RegistrationServer::Delegate* delegate)
      : server_(server), pipe_name_(pipe_name), delegate_(delegate) {}
  ~RunServerThread() override {}

 private:
  // Thread:
  void ThreadMain() override { server_->Run(pipe_name_, delegate_); }

  RegistrationServer* server_;
  base::string16 pipe_name_;
  RegistrationServer::Delegate* delegate_;

  DISALLOW_COPY_AND_ASSIGN(RunServerThread);
};

class RegistrationServerTest : public RegistrationTestBase {
 public:
  RegistrationServerTest()
      : server_(), server_thread_(&server_, pipe_name(), &delegate()) {}

  RegistrationServer& server() { return server_; }
  Thread& server_thread() { return server_thread_; }

 private:
  RegistrationServer server_;
  RunServerThread server_thread_;

  DISALLOW_COPY_AND_ASSIGN(RegistrationServerTest);
};

// During destruction, ensures that the server is stopped and the background
// thread joined.
class ScopedStopServerAndJoinThread {
 public:
  explicit ScopedStopServerAndJoinThread(RegistrationServer* server,
                                         Thread* thread)
      : server_(server), thread_(thread) {}
  ~ScopedStopServerAndJoinThread() {
    server_->Stop();
    thread_->Join();
  }

 private:
  RegistrationServer* server_;
  Thread* thread_;
  DISALLOW_COPY_AND_ASSIGN(ScopedStopServerAndJoinThread);
};

TEST_F(RegistrationServerTest, Instantiate) {
}

TEST_F(RegistrationServerTest, StartAndStop) {
  server_thread().Start();
  ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread(
      &server(), &server_thread());
  ASSERT_NO_FATAL_FAILURE(delegate().WaitForStart());
}

TEST_F(RegistrationServerTest, StopWhileConnected) {
  ScopedFileHANDLE connection;
  {
    server_thread().Start();
    ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread(
        &server(), &server_thread());
    ASSERT_NO_FATAL_FAILURE(delegate().WaitForStart());
    connection = Connect();
    ASSERT_TRUE(connection.is_valid());
    // Leaving this scope causes the server to be stopped, while the connection
    // is still open.
  }
}

TEST_F(RegistrationServerTest, Register) {
  RegistrationRequest request = {0};
  RegistrationResponse response = {0};
  CrashpadInfo crashpad_info;
  request.client_process_id = GetCurrentProcessId();
  request.crashpad_info_address =
      reinterpret_cast<WinVMAddress>(&crashpad_info);

  server_thread().Start();
  ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread(
      &server(), &server_thread());

  ASSERT_NO_FATAL_FAILURE(delegate().WaitForStart());

  ASSERT_TRUE(SendRequest(Connect(), &request, sizeof(request), &response));

  ASSERT_EQ(1, delegate().registered_processes().size());
  VerifyRegistration(*delegate().registered_processes()[0], request, response);
}

TEST_F(RegistrationServerTest, ForgedClientId) {
  // Skip this test on pre-Vista as the forged PID detection is not supported
  // there.
  OSVERSIONINFO vi = {0};
  vi.dwOSVersionInfoSize = sizeof(vi);
  GetVersionEx(&vi);
  if (vi.dwMajorVersion < 6)
    return;

  RegistrationRequest request = {0};
  RegistrationResponse response = {0};
  CrashpadInfo crashpad_info;
  // Note that we forge the PID here.
  request.client_process_id = GetCurrentProcessId() + 1;
  request.crashpad_info_address =
      reinterpret_cast<WinVMAddress>(&crashpad_info);

  server_thread().Start();
  ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread(
      &server(), &server_thread());

  ASSERT_NO_FATAL_FAILURE(delegate().WaitForStart());

  ASSERT_FALSE(SendRequest(Connect(), &request, sizeof(request), &response));
  ASSERT_EQ(0, delegate().registered_processes().size());

  // Correct the PID and verify that this was the only reason we failed.
  request.client_process_id = GetCurrentProcessId();
  ASSERT_TRUE(SendRequest(Connect(), &request, sizeof(request), &response));
  ASSERT_EQ(1, delegate().registered_processes().size());
  VerifyRegistration(*delegate().registered_processes()[0], request, response);
}

TEST_F(RegistrationServerTest, RegisterClientFails) {
  RegistrationRequest request = {0};
  RegistrationResponse response = {0};
  CrashpadInfo crashpad_info;
  request.client_process_id = GetCurrentProcessId();
  request.crashpad_info_address =
      reinterpret_cast<WinVMAddress>(&crashpad_info);

  server_thread().Start();
  ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread(
      &server(), &server_thread());

  ASSERT_NO_FATAL_FAILURE(delegate().WaitForStart());

  // Simulate some failures
  delegate().set_fail_mode(true);
  for (int i = 0; i < 10; ++i) {
    ASSERT_FALSE(SendRequest(Connect(), &request, sizeof(request), &response));
    ASSERT_EQ(0, delegate().registered_processes().size());
  }

  // Now verify that a valid response may still be processed.
  delegate().set_fail_mode(false);
  ASSERT_TRUE(SendRequest(Connect(), &request, sizeof(request), &response));

  ASSERT_EQ(1, delegate().registered_processes().size());
  VerifyRegistration(*delegate().registered_processes()[0], request, response);
}

TEST_F(RegistrationServerTest, BadRequests) {
  server_thread().Start();
  ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread(
      &server(), &server_thread());
  ASSERT_NO_FATAL_FAILURE(delegate().WaitForStart());

  RegistrationRequest request = {0};
  RegistrationResponse response = {0};
  CrashpadInfo crashpad_info;
  request.client_process_id = GetCurrentProcessId();
  request.crashpad_info_address =
      reinterpret_cast<WinVMAddress>(&crashpad_info);

  // Concatenate a valid request with a single byte of garbage.
  std::vector<char> extra_long;
  extra_long.insert(extra_long.begin(),
                    reinterpret_cast<char*>(&request),
                    reinterpret_cast<char*>(&request) + sizeof(request));
  extra_long.push_back('x');

  for (int i = 0; i < 10; ++i) {
    ASSERT_FALSE(SendRequest(Connect(), "a", 1, &response));
    ASSERT_FALSE(SendRequest(
        Connect(), extra_long.data(), extra_long.size(), &response));
    ASSERT_TRUE(Connect().is_valid());
  }

  // Now verify that a valid response may still be processed.

  ASSERT_TRUE(SendRequest(Connect(), &request, sizeof(request), &response));

  ASSERT_EQ(1, delegate().registered_processes().size());
  VerifyRegistration(*delegate().registered_processes()[0], request, response);
}

TEST_F(RegistrationServerTest, OverlappingRequests) {
  server_thread().Start();
  ScopedStopServerAndJoinThread scoped_stop_server_and_join_thread(
      &server(), &server_thread());
  ASSERT_NO_FATAL_FAILURE(delegate().WaitForStart());

  RegistrationRequest request = {0};
  RegistrationResponse response_1 = {0};
  RegistrationResponse response_2 = {0};
  RegistrationResponse response_3 = {0};
  CrashpadInfo crashpad_info;
  request.client_process_id = GetCurrentProcessId();
  request.crashpad_info_address =
      reinterpret_cast<WinVMAddress>(&crashpad_info);

  ScopedFileHANDLE connection_1 = Connect();
  ASSERT_TRUE(connection_1.is_valid());
  ScopedFileHANDLE connection_2 = Connect();
  ASSERT_TRUE(connection_2.is_valid());
  ScopedFileHANDLE connection_3 = Connect();
  ASSERT_TRUE(connection_3.is_valid());

  ASSERT_FALSE(SendRequest(connection_1.Pass(), "a", 1, &response_1));

  ASSERT_TRUE(
      SendRequest(connection_2.Pass(), &request, sizeof(request), &response_2));

  ASSERT_TRUE(Connect().is_valid());

  ASSERT_TRUE(
      SendRequest(connection_3.Pass(), &request, sizeof(request), &response_3));

  ASSERT_EQ(2, delegate().registered_processes().size());
  VerifyRegistration(
      *delegate().registered_processes()[0], request, response_2);
  VerifyRegistration(
      *delegate().registered_processes()[1], request, response_3);
}

}  // namespace
}  // namespace test
}  // namespace crashpad


text:
<?php

declare(strict_types=1);

namespace DCarbone\PHPConsulAPI\ACL;

use DCarbone\PHPConsulAPI\AbstractModel;
use DCarbone\PHPConsulAPI\FakeMap;
use DCarbone\PHPConsulAPI\Transcoding;

/**
 * Class ACLLoginParams
 */
class ACLLoginParams extends AbstractModel
{
    protected const FIELDS = [
        self::FIELD_META => Transcoding::MAP_FIELD + [Transcoding::FIELD_OMITEMPTY => true],
    ];

    private const FIELD_META = 'Meta';

    /** @var string */
    public string $AuthMethod = '';
    /** @var string */
    public string $BearerToken = '';
    /** @var \DCarbone\PHPConsulAPI\FakeMap|null */
    public ?FakeMap $Meta = null;

    /**
     * @return string
     */
    public function getAuthMethod(): string
    {
        return $this->AuthMethod;
    }

    /**
     * @param string $AuthMethod
     * @return \DCarbone\PHPConsulAPI\ACL\ACLLoginParams
     */
    public function setAuthMethod(string $AuthMethod): self
    {
        $this->AuthMethod = $AuthMethod;
        return $this;
    }

    /**
     * @return string
     */
    public function getBearerToken(): string
    {
        return $this->BearerToken;
    }

    /**
     * @param string $BearerToken
     * @return \DCarbone\PHPConsulAPI\ACL\ACLLoginParams
     */
    public function setBearerToken(string $BearerToken): self
    {
        $this->BearerToken = $BearerToken;
        return $this;
    }

    /**
     * @return \DCarbone\PHPConsulAPI\FakeMap|null
     */
    public function getMeta(): ?FakeMap
    {
        return $this->Meta;
    }

    /**
     * @param mixed $Meta
     * @return \DCarbone\PHPConsulAPI\ACL\ACLLoginParams
     */
    public function setMeta($Meta): self
    {
        $this->Meta = FakeMap::parse($Meta);
        return $this;
    }
}


text:
(function(){

function registerNS(ns) {
  var nsParts = ns.split('.');
  var root = window;

  for (var i=0; i<nsParts.length; i++) {
    if (typeof root[nsParts[i]] === 'undefined') {
      root[nsParts[i]] = {};
    }
    root = root[nsParts[i]];
  }
}

registerNS("org.ellab.utils");

org.ellab.utils.isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

if (typeof XPathResult.prototype.each === 'undefined') {
  XPathResult.prototype.each = function(callback, args) {
    var i = 0;
    var length = this.snapshotLength;
    if (typeof length === 'undefined') {
      return this;
    }

    if (args) {
      for (; i < length;) {
        if (callback.apply(this.snapshotItem(i++), args) === false) {
          break;
        }
      }
    }
    else {
      for (; i < length;) {
        if (callback.call(this.snapshotItem(i), i, this.snapshotItem(i++)) === false) {
          break;
        }
      }
    }

    return this;
  };
}

org.ellab.utils.trim = function(s) {
  return (s || '').replace(/^\s+/, '').replace(/\s+$/, '');
};

org.ellab.utils.extract = function(s, prefix, suffix) {
  var i;
  if (prefix) {
    i = s.indexOf(prefix);
    if (i >= 0) {
      s = s.substring(i + prefix.length);
    }
    else {
      return '';
    }
  }

  if (suffix) {
    i = s.indexOf(suffix);
    if (i >= 0) {
      s = s.substring(0, i);
    }
    else {
      return '';
    }
  }

  return s;
};

org.ellab.utils.each = function(object, callback, args) {
  if (!object) {
    return object;
  }

  var i = 0;
  var length = object.length;
  if (typeof length === 'undefined') {
    length = object.snapshotLength;
  }

  if (typeof length === 'undefined') {
    return object;
  }

  if (args) {
    for (; i < length;) {
      if (callback.apply(object[i++], args) === false) {
        break;
      }
    }
  }
  else {
    for (; i < length;) {
      if (callback.call(object[i], i, object[i++]) === false) {
        break;
      }
    }
  }

  return object;
};

org.ellab.utils.find = function(object, callbackOrMatch) {
  var result = null;
  if (typeof callbackOrMatch === 'function') {
    org.ellab.utils.each(object, function() {
      if (callbackOrMatch.apply(this)) {
        result = this;
        return false;
      }
    });
    return result;
  }
  else {
    // by matching properties
    return org.ellab.find(object, function() {
      for (var e in callbackOrMatch) {
        if (callbackOrMatch[e] !== this[e]) {
          return false;
        }
      }
      return true;
    });
  }
};

org.ellab.utils.grep = function(object, callbackOrMatch) {
  var result = [];
  if (typeof callbackOrMatch === 'function') {
    org.ellab.utils.each(object, function() {
      if (callbackOrMatch.apply(this)) {
        result.push(this);
      }
    });
    return result;
  }
  else {
    // by matching properties
    return org.ellab.grep(object, function() {
      for (var e in callbackOrMatch) {
        if (callbackOrMatch[e] !== this[e]) {
          return false;
        }
      }
      return true;
    });
  }
};

org.ellab.utils.arr_first = function(arr) {
  if (Object.prototype.toString.call(arr) === '[object Array]' && arr.length > 0) {
    return arr[0];
  }
  else {
    return null;
  }
};

org.ellab.utils.arr_last = function(arr) {
  if (Object.prototype.toString.call(arr) === '[object Array]' && arr.length > 0) {
    return arr[arr.length - 1];
  }
  else {
    return null;
  }
};

// return the first element instead of an array if the selector is simply an id
org.ellab.utils.sizzleSmart = function(selector, context, results, seed) {
  if (selector.match(/^\s*#[a-zA-Z0-9\-_]+\s*$/)) {
    return org.ellab.utils.sizzleOne(selector, context, results, seed);
  }
  else {
    return Sizzle(selector, context, results, seed);
  }
};

// wrap the result with each()
org.ellab.utils.sizzleEach = function(selector, callback, args, context, results, seed) {
  return org.ellab.utils.each(Sizzle(selector, context, results, seed), callback, args);
};

// return the first element instead of an array, useful if the caller only want the first element
org.ellab.utils.sizzleOne = function(selector, context, results, seed) {
  var res = Sizzle(selector, context, results, seed);
  if (res && res.length > 0) {
    return res[0];
  }
  else {
    return null;
  }
};

org.ellab.utils.crossOriginXMLHttpRequest_GM = function(params) {
  GM_xmlhttpRequest({
      method: params.method,
      url: params.url,
      overrideMimeType: params.overrideMimeType,
      onload: function(response){
        if (response.status == 301 || response.status == 302 || response.status == 303) {
          var loc = /Location: ([^\n]*)\n/.exec(response.responseHeaders)[1];
          GM_xmlhttpRequest({method:params.method, overrideMimeType: params.overrideMimeType, url:loc, onload:arguments.callee});
          return;
        }
        params.onload.call(this, response);
      }
  });
};

// method
// url
// onload
org.ellab.utils.crossOriginXMLHttpRequest_Chrome = function(params) {
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        var response = {status:xhr.status, responseText:xhr.responseText};
        if (params.onload) {
          params.onload.call(this, response);
        }
      }
    }
  };

  xhr.open(params.method, params.url, true);
  xhr.send();
};

org.ellab.utils.crossOriginXMLHttpRequest = function(params) {
  if (this.isChrome) {
    this.crossOriginXMLHttpRequest_Chrome(params);
  }
  else {
    this.crossOriginXMLHttpRequest_GM(params);
  }
};

org.ellab.utils.getCookie = function(name) {
  if (document.cookie.length>0) {
    var start = document.cookie.indexOf(name + '=');
    if (start >= 0) {
      start = start + name.length + 1;
      var end = document.cookie.indexOf(';', start);
      if (end < 0) {
        end = document.cookie.length;
      }
      return unescape(document.cookie.substring(start, end));
    }
  }
  return '';
};

org.ellab.utils.setCookie = function(name, value, expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie = name + '=' + escape(value) + ((expiredays===null)?'':';expires=' + exdate.toGMTString());
};

org.ellab.utils.getSession = function(name) {
  if (window.sessionStorage && window.sessionStorage.getItem) {
    return window.sessionStorage.getItem(name);
  }
  else {
    return this.getCookie(name);
  }
};

org.ellab.utils.setSession = function(name, value) {
  if (window.sessionStorage && window.sessionStorage.setItem) {
    return window.sessionStorage.setItem(name, value);
  }
  else {
    return this.setCookie(name, value);
  }
};

org.ellab.utils.getResourceURL = function(name, file) {
  if (typeof GM_getResourceURL != 'undefined') {
    return GM_getResourceURL(name);
  }
  else if (typeof chrome != 'undefined' && typeof chrome.extension != 'undefined' && typeof chrome.extension.getURL != 'undefined') {
    return chrome.extension.getURL(file);
  }
  else {
    return file;
  }
};

org.ellab.utils.calcOffsetTop = function(node) {
  var top = 0;
  while (node) {
    if (!isNaN(node.offsetTop)) top += node.offsetTop;
    node = node.offsetParent;
  }

  return top;
};

org.ellab.utils.calcOffsetLeft = function(node) {
  var left = 0;
  while (node) {
    if (!isNaN(node.offsetLeft)) left += node.offsetLeft;
    node = node.offsetParent;
  }

  return left;
};

org.ellab.utils.detectScroll = function(callback) {
  window.addEventListener('scroll', function() {
    var st = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
    if (!st) {
      callback.call(window, 'top');
    }
    else if ((st + document.documentElement.clientHeight) >= document.documentElement.scrollHeight) {
      callback.call(window, 'bottom');
    }
  }, false);
};

org.ellab.utils.xpath = function(xpath, ele, nsResolver) {
  return document.evaluate(xpath, ele?ele:document, nsResolver, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
};

org.ellab.utils.xpathl = function(xpath, ele, nsResolver) {
  return document.evaluate(xpath, ele?ele:document, nsResolver, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
};

org.ellab.utils.getElementsByClassName = function(className, node) {
  if (!className) {
    return [];
  }
  node = node || document;
  if (node.getElementsByClassName) {
    return node.getElementsByClassName(className);
  }
  else {
    var res = document.evaluate(".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]", node, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
    var result = [];
    for (var i=0;i<res.snapshotLength;i++) {
      result.push(res.snapshotItem(i));
    }
    return result;
  }
};

org.ellab.utils.decodeHTML = function(s) {
  if (s) {
    s = s.replace('>', '>', 'g');
    s = s.replace('<', '<', 'g');
    s = s.replace('"', '"', 'g');
    s = s.replace('&', '&', 'g');
  }
  return s;
};

org.ellab.utils.encodeHTML = function(s) {
  if (s) {
    s = s.replace('&', '&', 'g');
    s = s.replace('>', '>', 'g');
    s = s.replace('<', '<', 'g');
    s = s.replace('"', '"', 'g');
  }
  return s;
};

// wrapper for parsing json, fallback to eval if not supported
org.ellab.utils.parseJSON = function(s) {
  if (typeof JSON  != 'undefined' && typeof JSON.parse != 'undefined') {
    return JSON.parse(s);
  }
  else {
    return eval(s);
  }
};

org.ellab.utils.parseXML = function(s) {
  return (new window.DOMParser()).parseFromString(s, "text/xml");
};

// iterate the parent nodes until callback return true
// iterate the parent nodes until match the tag name
org.ellab.utils.parent = function(node, tagOrCallback, immediateParentOnly) {
  if (!node) return node;

  var parentNode = node.parentNode;

  if (!parentNode || !tagOrCallback) return parentNode;

  if (typeof tagOrCallback === 'string' && parentNode.tagName && parentNode.tagName.toUpperCase() == tagOrCallback.toUpperCase()) return parentNode;

  if (typeof tagOrCallback === 'function' && tagOrCallback.apply(parentNode)) return parentNode;

  if (immediateParentOnly) {
    return null;
  }
  else {
    return this.parent(parentNode, tagOrCallback, immediateParentOnly);
  }
};

// iterate the parent nodes until match the tag name
org.ellab.utils.prevSibling = function(node, tagOrCallback, immediateSiblingOnly) {
  if (!node) return node;

  var prevSibling = node.previousSibling;

  if (!prevSibling || !tagOrCallback) return prevSibling;

  if (typeof tagOrCallback === 'string' && prevSibling.nodeType !== 3 && prevSibling.tagName && prevSibling.tagName.toUpperCase() == tagOrCallback.toUpperCase()) return prevSibling;

  if (typeof tagOrCallback === 'function' && tagOrCallback.apply(prevSibling)) return prevSibling;

  if (immediateSiblingOnly) {
    return null;
  }
  else {
    return this.prevSibling(prevSibling, tagOrCallback, immediateSiblingOnly);
  }
};

// iterate the nextSibling nodes until match the tag name
org.ellab.utils.nextSibling = function(node, tagOrCallback, immediateSiblingOnly) {
  if (!node) return node;

  var nextSibling = node.nextSibling;

  if (!nextSibling || !tagOrCallback) return nextSibling;

  if (typeof tagOrCallback === 'string' && nextSibling.nodeType !== 3 && nextSibling.tagName && nextSibling.tagName.toUpperCase() == tagOrCallback.toUpperCase()) return nextSibling;

  if (typeof tagOrCallback === 'function' && tagOrCallback.apply(nextSibling)) return nextSibling;

  if (immediateSiblingOnly) {
    return null;
  }
  else {
    return this.nextSibling(nextSibling, tagOrCallback, immediateSiblingOnly);
  }
};

org.ellab.utils.removeChild = function(node) {
  if (!node) return node;

  if (node.parentNode) {
    node.parentNode.removeChild(node);
  }

  return node;
};

// inject an javascript to the main window, useful for call the function in window
org.ellab.utils.inject = function(fn) {
  var script = document.createElement('script');
  script.setAttribute("type", "application/javascript");
  script.textContent = '(function(){' + fn + '})();';
  document.body.appendChild(script); // run the script
  document.body.removeChild(script); // clean up
};

org.ellab.utils.changeFavicon = function(img, type, id) {
  id = id || 'ellab-favicon';
  type = type || 'image/png';
  var ss = document.getElementById(id);
  if (ss) {
    ss.href = img;
  }
  else {
    var head = document.getElementsByTagName('head')[0];

    // Create this favicon
    ss = document.createElement('link');
    ss.setAttribute('id', id);
    ss.rel = 'shortcut icon';
    ss.type = type;
    ss.href = img;
    // Remove any existing favicons
    var links = head.getElementsByTagName('link');
    for (var i=0; i<links.length; i++) {
      if (links[i].href == ss.href) return;
      if (links[i].rel == "shortcut icon" || links[i].rel=="icon")
        head.removeChild(links[i]);
    }
    // Add this favicon to the head
    head.appendChild(ss);
    // Force browser to acknowledge
    var shim = document.createElement('iframe');
    shim.width = shim.height = 0;
    document.body.appendChild(shim);
    shim.src = "icon";
    document.body.removeChild(shim);
  }
};

org.ellab.utils.hasClass = function(ele, clazz) {
  var c = ele.className;
  c = org.ellab.utils.trim(c);
  return c.match(new RegExp('^' + clazz + '$')) !== null ||
         c.match(new RegExp('^' + clazz + '\\s+')) !== null ||
         c.match(new RegExp('\\s+' + clazz + '$')) !== null ||
         c.match(new RegExp('\\s+' + clazz + '\\s+')) !== null;
};

org.ellab.utils.removeClass = function(ele, clazz) {
  var c = ele.className, trimmed;
  c = trimmed = org.ellab.utils.trim(c);
  c = c.replace(new RegExp('^' + clazz + '$'), '');
  c = c.replace(new RegExp('^' + clazz + '\\s+'), '');
  c = c.replace(new RegExp('\\s+' + clazz + '$'), '');
  c = c.replace(new RegExp('\\s+' + clazz + '\\s+'), ' ');
  if (c) {
    if (c != trimmed) {
      // actually something removed
      ele.className = c;
    }
  }
  else {
    ele.removeAttribute('class');
  }
};

org.ellab.utils.addClass = function(ele, clazz) {
  org.ellab.utils.removeClass(ele, clazz);
  ele.className += (ele.className?' ':'') + clazz;
};

org.ellab.utils.toggleClass = function(ele, clazz) {
  if (org.ellab.utils.hasClass(ele, clazz)) {
    org.ellab.utils.removeClass(ele, clazz);
  }
  else{
    org.ellab.utils.addClass(ele, clazz);
  }
};

org.ellab.utils.insertBefore = function(newnode, oldnode) {
  oldnode.parentNode.insertBefore(newnode, oldnode);
};

org.ellab.utils.insertAfter = function(newnode, oldnode) {
  oldnode.parentNode.insertBefore(newnode, oldnode.nextSibling);
};

})();


text:
from tests.app_tests import BaseTestCase
from app.mod_streams.models import *
from flask import url_for

CHANNEL = 'channel'
CHANNELS = ['channel1', 'channel2', 'channel3']

class TestStreams(BaseTestCase):
    @classmethod
    def setUpClass(cls):
        cls.disable_login = True
        super().setUpClass()
        cls.url = url_for('adminpanel.configure_module', bp_name='streams')

    def add_streams(self, channels):
        if isinstance(channels, list):
            channels = ','.join(channels)
        return self.client.post(self.url, data=dict(
            channel=channels,
            add='Add'
        ))

    def remove_streams(self, channels):
        if isinstance(channels, list):
            channels = ','.join(channels)
        return self.client.post(self.url, data=dict(
            channel=channels,
            remove='Remove'
        ))

    def load_streams(self, channels):
        if isinstance(channels, list):
            channels = ','.join(channels)
        return self.client.post(self.url, data=dict(
            all_channels=channels,
            load='Load'
        ))

    def test_add(self):
        with self.client:
            # Test adding a single stream
            self.add_streams(CHANNEL)
            stream = Stream.query.filter_by(channel=CHANNEL).first()
            self.assertIsInstance(stream, Stream)
            self.assertEquals(stream.channel, CHANNEL)
            # Test adding an existing stream
            self.add_streams(CHANNEL)
            # Test adding multiple streams
            self.add_streams(CHANNELS)
            streams = Stream.query.filter(Stream.channel.in_(CHANNELS)).all()
            stream_names = []
            for stream in streams:
                stream_names.append(stream.channel)
                self.assertIsInstance(stream, Stream)
            self.assertEquals(set(stream_names), set(CHANNELS))
            # Test adding multiple existing streams
            self.add_streams(CHANNELS)
            # Test stream name requirement
            self.add_streams('')
            stream = Stream.query.filter_by(channel='').first()
            self.assertIsNone(stream)

    def test_remove(self):
        with self.client:
            # Test removing a stream
            self.add_streams(CHANNEL)
            self.remove_streams(CHANNEL)
            stream = Stream.query.filter_by(channel=CHANNEL).first()
            self.assertIsNone(stream)
            # Test removing multiple streams
            self.add_streams(CHANNELS)
            self.remove_streams(CHANNELS)
            streams = Stream.query.filter(Stream.channel.in_(CHANNELS)).all()
            self.assertEquals(streams, [])
            # Test removing non-existing stream
            self.remove_streams('kappa')
            # Test removing empty stream
            self.remove_streams('')

    def test_load(self):
        with self.client:
            # Test loading a stream
            self.add_streams(CHANNEL)
            rv = self.load_streams(CHANNEL)
            self.assertIn(CHANNEL.encode(), rv.data)
            # Test loading multiple streams
            self.add_streams(CHANNELS)
            rv = self.load_streams(CHANNELS)
            for channel in CHANNELS:
                self.assertIn(channel.encode(), rv.data)


text:
<?php

namespace ethercreative\log;

use Yii;
use yii\base\InvalidConfigException;

use Maknz\Slack\Client;

class Error extends \yii\log\Target
{
	public
		$webhook,
		$name,
		$username,
		$channel,
		$link_names = true;

	public function export()
	{
		if (!$this->webhook) throw new InvalidConfigException("Webhook is required.");
		if (!$this->name) throw new InvalidConfigException("Name is required.");
		if (!$this->username) throw new InvalidConfigException("Username is required.");
		if (!$this->channel) throw new InvalidConfigException("Channel is required.");

		$client = new Client($this->webhook, [
			'username' => $this->username,
			'channel' => $this->channel,
			'link_names' => $this->link_names,
		]);

		$url = \Yii::$app->request->absoluteUrl;

		foreach ($this->messages as $message)
		{
			$_message = $message;

			$message = $message[0];

			$statusCode = Yii::$app->response->statusCode;
			$statusText  = Yii::$app->response->statusText;

			if (is_string($message) || ((int) $statusCode < 500 && (int) $statusCode !== 0))
				continue;

			$string = $this->formatMessage($_message);

			$string = (explode("\n", $string))[0];

			$data = [
				'fallback' => 'fallback',
				'color' => 'danger',
				'fields' => [
					[
						'title' => 'Project',
						'value' => $this->name,
						'short' => true,
					],
					[
						'title' => 'URL',
						'value' => $url,
						'short' => true,
					],
					[
						'title' => 'Error',
						'value' => $statusCode . ' ' . $statusText,
						'short' => true,
					],
					[
						'title' => 'Line #',
						'value' => $message->getLine(),
						'short' => true,
					],
					[
						'title' => 'File',
						'value' => $message->getFile(),
					],
					[
						'title' => 'Text',
						'value' => $string,
					],
				],
			];

			$client->attach($data)->send();
		}
	}
}


text:
package com.thinkbiganalytics.hive.service;

import com.thinkbiganalytics.discovery.model.DefaultDatabaseMetadata;
import com.thinkbiganalytics.discovery.model.DefaultField;
import com.thinkbiganalytics.discovery.model.DefaultTableSchema;
import com.thinkbiganalytics.discovery.schema.DatabaseMetadata;
import com.thinkbiganalytics.discovery.schema.Field;
import com.thinkbiganalytics.discovery.schema.TableSchema;
import com.thinkbiganalytics.jdbc.util.DatabaseType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.MetaDataAccessException;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;
import javax.sql.DataSource;

/**
 */
@Service("hiveMetastoreService")
public class HiveMetastoreService {

    private static final Logger log = LoggerFactory.getLogger(HiveMetastoreService.class);

    @Inject
    @Qualifier("hiveMetatoreJdbcTemplate")
    private JdbcTemplate hiveMetatoreJdbcTemplate;
    private DatabaseType metastoreDatabaseType = null;

    public DataSource getDataSource() {

        return hiveMetatoreJdbcTemplate.getDataSource();
    }

    private DatabaseType getMetastoreDatabaseType() {
        if (metastoreDatabaseType == null) {
            try {
                metastoreDatabaseType = DatabaseType.fromMetaData(getDataSource());
                return metastoreDatabaseType;
            } catch (MetaDataAccessException e) {
                log.error("Unable to determine Metastore Database Type.  Using default type of " + DatabaseType.MYSQL + ". " + e.getMessage(), e);
            }
            return DatabaseType.MYSQL;
        }
        return metastoreDatabaseType;
    }

    public List<DatabaseMetadata> getTableColumns(List<String> tablesFilter) throws DataAccessException {

        String query = "SELECT d.NAME as \"DATABASE_NAME\", t.TBL_NAME, c.COLUMN_NAME "
                       + "FROM COLUMNS_V2 c "
                       + "JOIN  SDS s on s.CD_ID = c.CD_ID "
                       + "JOIN  TBLS t ON s.SD_ID = t.SD_ID "
                       + "JOIN  DBS d on d.DB_ID = t.DB_ID "
                       + "ORDER BY d.NAME, t.TBL_NAME";

        if (DatabaseType.POSTGRES.equals(getMetastoreDatabaseType())) {
            query = "SELECT d.\"NAME\" as \"DATABASE_NAME\", t.\"TBL_NAME\", c.\"COLUMN_NAME\" "
                    + "FROM \"COLUMNS_V2\" c "
                    + "JOIN  \"SDS\" s on s.\"CD_ID\" = c.\"CD_ID\" "
                    + "JOIN  \"TBLS\" t ON s.\"SD_ID\" = t.\"SD_ID\" "
                    + "JOIN  \"DBS\" d on d.\"DB_ID\" = t.\"DB_ID\" "
                    + "ORDER BY d.\"NAME\", t.\"TBL_NAME\"";
        }

        List<DatabaseMetadata> metadata = hiveMetatoreJdbcTemplate.query(query, new RowMapper<DatabaseMetadata>() {
            @Override
            public DatabaseMetadata mapRow(ResultSet rs, int i) throws SQLException {
                DefaultDatabaseMetadata row = new DefaultDatabaseMetadata();
                row.setDatabaseName(rs.getString("DATABASE_NAME"));
                row.setColumnName(rs.getString("COLUMN_NAME"));
                row.setTableName(rs.getString("TBL_NAME"));
                return row;
            }
        });

        return tablesFilter == null ? metadata : filterDatabaseMetadata(metadata, tablesFilter);

    }

    private List<DatabaseMetadata> filterDatabaseMetadata(List<DatabaseMetadata> allTables, List<String> tablesFilter) {
        List<DatabaseMetadata> results = new ArrayList<>();
        allTables.forEach(metadata -> {
            if (tablesFilter.contains(metadata.getDatabaseName() + "." + metadata.getTableName())) {
                results.add(metadata);
            }
        });
        return results;
    }

    public List<String> getAllTables(final String schema, String table) throws DataAccessException {

        String query = "SELECT d.NAME as \"DATABASE_NAME\", t.TBL_NAME FROM TBLS t JOIN DBS d on d.DB_ID = t.DB_ID"
                       + " WHERE d.NAME LIKE ? "
                       + " AND t.TBL_NAME LIKE ? "
                       + " ORDER BY t.TBL_NAME";
        if (DatabaseType.POSTGRES.equals(getMetastoreDatabaseType())) {
            query = "SELECT d.\"NAME\" as \"DATABASE_NAME\", t.\"TBL_NAME\" FROM \"TBLS\" t JOIN \"DBS\" d on d.\"DB_ID\" = t.\"DB_ID\" "
                    + " WHERE d.\"NAME\" LIKE ? "
                    + " WHERE t.\"TBL_NAME\" LIKE ? "
                    + " ORDER BY d.\"NAME\", t.\"TBL_NAME\"";
        }

        return hiveMetatoreJdbcTemplate.query(
            query,
            ps -> {
                ps.setString(1, schema == null ? "%" : schema);
                ps.setString(2, table == null ? "%" : "%" + table + "%");
            },
            (rs, i) -> {
                String dbName = rs.getString("DATABASE_NAME");
                String tableName = rs.getString("TBL_NAME");
                return dbName + "." + tableName;
            });
    }

    public List<TableSchema> getTableSchemas() throws DataAccessException {

        String query = "SELECT d.NAME as \"DATABASE_NAME\", t.TBL_NAME, c.COLUMN_NAME c.TYPE_NAME "
                       + "FROM COLUMNS_V2 c "
                       + "JOIN  SDS s on s.CD_ID = c.CD_ID "
                       + "JOIN  TBLS t ON s.SD_ID = t.SD_ID "
                       + "JOIN  DBS d on d.DB_ID = t.DB_ID "
                       + "ORDER BY d.NAME, t.TBL_NAME";
        if (DatabaseType.POSTGRES.equals(getMetastoreDatabaseType())) {
            query = "SELECT d.\"NAME\" as \"DATABASE_NAME\", t.\"TBL_NAME\", c.\"COLUMN_NAME\",c.\"TYPE_NAME\" "
                    + "FROM \"COLUMNS_V2\" c "
                    + "JOIN  \"SDS\" s on s.\"CD_ID\" = c.\"CD_ID\" "
                    + "JOIN  \"TBLS\" t ON s.\"SD_ID\" = t.\"SD_ID\" "
                    + "JOIN  \"DBS\" d on d.\"DB_ID\" = t.\"DB_ID\" ";

        }
        final List<TableSchema> metadata = new ArrayList<>();
        final Map<String, Map<String, TableSchema>> databaseTables = new HashMap<>();

        hiveMetatoreJdbcTemplate.query(query, new RowMapper<Object>() {
            @Override
            public TableSchema mapRow(ResultSet rs, int i) throws SQLException {
                String dbName = rs.getString("DATABASE_NAME");
                String columnName = rs.getString("COLUMN_NAME");
                String tableName = rs.getString("TBL_NAME");
                String columnType = rs.getString("TYPE_NAME");
                if (!databaseTables.containsKey(dbName)) {
                    databaseTables.put(dbName, new HashMap<String, TableSchema>());
                }
                Map<String, TableSchema> tables = databaseTables.get(dbName);
                if (!tables.containsKey(tableName)) {
                    DefaultTableSchema schema = new DefaultTableSchema();
                    schema.setName(tableName);
                    schema.setSchemaName(dbName);
                    schema.setFields(new ArrayList<Field>());
                    tables.put(tableName, schema);
                    metadata.add(schema);
                }
                TableSchema schema = tables.get(tableName);
                DefaultField field = new DefaultField();
                field.setName(columnName);
                field.setNativeDataType(columnType);
                field.setDerivedDataType(columnType);
                schema.getFields().add(field);
                return schema;
            }
        });

        return metadata;

    }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>CmdMessenger: ArduinoController.ArduinoController Class Reference</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />

CmdMessenger
    4.0.0

CmdMessenger is a serial port messaging library for the .Net / Mono Platform.

Main Page

Packages

Classes

Class List

Class Index

Class Hierarchy

Class Members

ArduinoController

ArduinoController

Public Member Functions

ArduinoController.ArduinoController Class Reference

List of all members.

Public Member Functions

void 	Setup (ControllerForm controllerForm)

void 	Exit ()

void 	SetLedFrequency (double ledFrequency)

void 	SetLedState (bool ledState)

The documentation for this class was generated from the following file:

D:/My Documents/Github/Arduino/Own Arduino libraries/CmdMessenger/Arduino-CmdMessenger/extras/CSharp/ArduinoController/ArduinoController.cs

<address class="footer">
Generated on Fri Apr 24 2015 23:15:51 for CmdMessenger by

 1.7.6.1
</address>


text:
module Peek
  module ActiveResource
    VERSION = "1.0.0"
  end
end


text:
module.exports = {
  extends: [
    'simplabs/configs/ember-mocha',
    'simplabs/plugins/mocha',
  ],
};


text:
'use strict';

viewModel.EventAnalysis = new Object();
var ea = viewModel.EventAnalysis;

var dataByGroup;
var dataByError;
var dataByTurbine;
var breakDownEa = "detailgroup";
var additionalFilter = {};
var realDesc = {};
var categoryLvl1;
ea.firstLoad = ko.observable(true);
ea.labelEventDetail1 = ko.observable();
ea.labelEventDetail2 = ko.observable();

ea.data = {level0: {},level1 : {}, level2:{}}

vm.currentMenu('Event Analysis ');
vm.currentTitle('Event Analysis ');
vm.breadcrumb([
    { title: "Monitoring", href: '#' },
    { title: 'Event Analysis', href: viewModel.appName + 'page/eventanalysis' }]);

var availDateAll;

ea.getDataAvailableInfo =  function(isFirstLoad){
    toolkit.ajaxPost(viewModel.appName + "analyticlossanalysis/getavaildateall", {}, function (res) {
        if (!app.isFine(res)) {
            return;
        }

        availDateAll = res.data;

        ea.setAvailableDate(true);
    })
}

ea.setAvailableDate = function(isFirstLoad) {
    setTimeout(function(){
        var tipeTab = "Alarm";

        var namaproject = $("#projectList").data("kendoDropDownList").value();
        if(namaproject == "") {
            namaproject = "Tejuva";
        }

        var startDate = kendo.toString(moment.utc(availDateAll[namaproject][tipeTab][0]).format('DD-MMM-YYYY'));
        var endDate = kendo.toString(moment.utc(availDateAll[namaproject][tipeTab][1]).format('DD-MMM-YYYY'));

        var maxDateData = new Date(availDateAll[namaproject][tipeTab][1]);

        var startDatepicker = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate() - 7, 0, 0, 0, 0));

        $('#availabledatestart').html(startDate);
        $('#availabledateend').html(endDate);

        if(isFirstLoad === true){
            $('#dateStart').data('kendoDatePicker').value(startDatepicker);
            $('#dateEnd').data('kendoDatePicker').value(endDate);
        }

    }, 500);
}
ea.checkType = function(level){
    var value = $('input[name=convert'+level+']:checked').val();
    if(value == ("tohours"+level)){
        return "hours";
    }else{
        return "percentage";
    }
}

ea.autoGenerateLevel1 = function(params = {}, type) {
    app.loading(true);
    ea.RefreshData(params, type);
}

ea.autoGenerateLevel2 = function(params = {}, type) {
    app.loading(true);
    ea.RefreshData(params, type)
}

ea.RefreshData = function(params = {}, type){
    var valid = fa.LoadData();
    if (valid) {
        var dateStart = $('#dateStart').data('kendoDatePicker').value();
        var dateEnd = new Date(moment($('#dateEnd').data('kendoDatePicker').value()).format('YYYY-MM-DD'));

        breakDownEa = params.breakDownEa == undefined ? breakDownEa : params.breakDownEa;

        additionalFilter = params.additionalfilter == undefined ? additionalFilter : params.additionalfilter;

        var param = {
            period: fa.period,
            dateStart: dateStart,
            dateEnd: dateEnd,
            turbine: fa.turbine(),
            project: fa.project,
            breakdown: breakDownEa, // parent bdgroup , lvl1 => alarmdesc, lvl2 => turbine
            additionalfilter:  additionalFilter, // lvl 1 => { detailgroup : 'Machine'} , lvl 2 => {bdgroup : 'Machine', alarmdesc : 'Sembaranglah' }
            realdesc: realDesc
        }

        var reqData = toolkit.ajaxPost(viewModel.appName + "analyticlossanalysis/geteventanalysistab", param, function (res) {
            if (!app.isFine(res)) {
                return;
            }
            var results;
            var labelAxis;

            ea.data[params.level]  = {
                hours : res.data.data,
                percentage : res.data.datapercentage
            }
            if(type == "percentage"){
                labelAxis = "%"
                results = res.data.datapercentage;
            }else{
                labelAxis = "Hours";
                results = res.data.data;
            }
            dataByGroup = _.sortBy(results, '_id');
            realDesc = res.data.realdesc;

            var chartId;

            if(params.level == "level0"){
                chartId = "chartEventAnalysis";
            }else if(params.level == "level1"){
                chartId = "chartEventAnalysisLevel1";
                ea.labelEventDetail1(additionalFilter.detailgroup);
            }else{
                chartId = "chartEventAnalysisLevel2";
                ea.labelEventDetail2(additionalFilter.alarmdesc);
            }

            ea.GenEventAnalysisChart(dataByGroup, chartId, "", labelAxis, false, "N2", params.level);
        });
    }
}

ea.refreshChart = function(type, axisLabel){
    var dataByGroup1 = _.sortBy(ea.data["level0"][type], '_id');
    var dataByGroup2 = _.sortBy(ea.data["level1"][type], '_id');
    var dataByGroup3 = _.sortBy(ea.data["level2"][type], '_id');
    ea.GenEventAnalysisChart(dataByGroup1, "chartEventAnalysis", "", axisLabel, false, "N2", "level0")
    ea.GenEventAnalysisChart(dataByGroup2, "chartEventAnalysisLevel1", "", axisLabel, false, "N2", "level1")
    ea.GenEventAnalysisChart(dataByGroup3, "chartEventAnalysisLevel2", "", axisLabel, false, "N2", "level2")
}

ea.GenEventAnalysisChart = function (dataSource,id,name,axisLabel, vislabel,format, level) {
    var CONTAINER_SIZE = 370;
    var LEGEND_SIZE = 100;
    var LEGEND_OFFSET = CONTAINER_SIZE - LEGEND_SIZE;

    // var colours = ["#ff880e","#21c4af","#b71c1c","#F0638B","#a2df53","#1c9ec4","#880d4e","#4a148c","#053872","#b1b2ac","#ffcf49","#605c5c","#b1b2ac","#ffcf49","#605c5c"];
    var colours = ["#ff9933", "#21c4af", "#ff7663", "#ffb74f", "#a2df53", "#1c9ec4", "#ff63a5", "#f44336", "#69d2e7", "#8877A9", "#9A12B3", "#26C281", "#E7505A", "#C49F47", "#ff5597", "#c3260c", "#d4735e", "#ff2ad7", "#34ac8b", "#11b2eb", "#004c79", "#ff0037", "#507ca3", "#ff6565", "#ffd664", "#72aaff", "#795548", "#383271", "#6a4795", "#bec554", "#ab5919", "#f5b1e1", "#7b3416", "#002fef", "#8d731b", "#1f8805", "#ff9900", "#9C27B0", "#6c7d8a", "#d73c1c", "#5be7a0", "#da02d4", "#afa56e", "#7e32cb", "#a2eaf7", "#9cb8f4", "#9E9E9E", "#065806", "#044082", "#18937d", "#2c787a", "#a57c0c", "#234341", "#1aae7a", "#7ac610", "#736f5f", "#4e741e", "#68349d", "#1df3b6", "#e02b09", "#d9cfab", "#6e4e52", "#f31880", "#7978ec", "#f5ace8", "#3db6ae", "#5e06b0", "#16d0b9", "#a25a5b", "#1e603a", "#4b0981", "#62975f", "#1c8f2f", "#b0c80c", "#642794", "#e2060d", "#2125f0"];

    $("#" + id).kendoChart({
        dataSource: {
            data: dataSource,
            sort: [
                { "field": "Total", "dir": "desc" }
            ],
        },
        theme: "flat",
        title: {
            text: ""
        },
        legend: {
            position: "custom",
            orientation: "horizontal",
            offsetY: LEGEND_OFFSET,
            labels: {
                // template: "#: kendo.toString(replaceString(text))#",
                align: "center",
                font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            },
        },
        // plotArea: plotArea,
        chartArea: {
            width: 330,
            height: 500,
            padding: 0,
            margin: {
                top: -200,
            },
            background:"transparent",
        },
        seriesDefaults: {
            type: "column",
            stack: true,
            labels: {
                        visible: vislabel,
                        background: "transparent",
                        template: "#= category #: \n #= kendo.format('{0:" + format + "}', value)# " + axisLabel,
                    }
        },
        series: [{
            type: "pie",
            field: "result",
            categoryField: "_id"
        }],
        seriesColors: colours,
        valueAxis: {
            title: {
                text: axisLabel,
                font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
            },
            labels: {
                step: 2,
                font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            },
            line: {
                visible: false
            },
            axisCrossingValue: -10,
            majorGridLines: {
                visible: true,
                color: "#eee",
                width: 0.8,
            }
        },
        categoryAxis: {
            field: "_id",
            title: {
                text: name,
                font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
            },
            majorGridLines: {
                visible: false
            },
            labels: {
                font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            },
            majorTickType: "none",
        },
        seriesClick : function (e){
            if(level == "level0"){
                ea.firstLoad(true);
                var param = {
                    level : "level1",
                    additionalfilter:{ detailgroup : e.category },
                    breakDownEa:  "alarmdesc"
                };

                categoryLvl1 = e.category;

                ea.autoGenerateLevel2(param, ea.checkType(0));
            } else if(level == "level1"){
                var param = {
                    level : "level2",
                    additionalfilter:{ detailgroup : categoryLvl1 , alarmdesc : e.category},
                    breakDownEa: "turbine"
                };
                app.loading(true);
                ea.RefreshData(param, ea.checkType(0));
            }

        },
        tooltip: {
            visible: true,
            format: "{0:n1}",
            background: "rgb(255,255,255, 0.9)",
            color: "#58666e",
            font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
            template: "#: category #: #: kendo.toString(value, '" + format + "') # " + axisLabel,
            border: {
                color: "#eee",
                width: "2px",
            },

        },
    });

    setTimeout(function () {
        if ($("#" + id).data("kendoChart") != null) {
            $("#" + id).data("kendoChart").refresh();
        }
        /* check for auto generating */
        if(ea.firstLoad() && level == "level0" ){
            setTimeout(function(){
                var category1 = $("#chartEventAnalysis").data("kendoChart").options.categoryAxis.categories[0];
                var paramLevel1 = {
                    level : "level1",
                    additionalfilter:{ detailgroup : category1 },
                    breakDownEa:  "alarmdesc"
                };
                ea.RefreshData(paramLevel1, ea.checkType(0));
            }, 100);
        } else if (ea.firstLoad() && level == "level1" ){
            setTimeout(function(){
                var category2 = $("#chartEventAnalysisLevel1").data("kendoChart").options.categoryAxis.categories[0]
                var paramLevel2 = {
                    level : "level2",
                    additionalfilter:{ detailgroup : categoryLvl1 , alarmdesc : category2},
                    breakDownEa: "turbine"
                };
                ea.RefreshData(paramLevel2, ea.checkType(0));
            },100);
        } else if (level == "level2") {
            setTimeout(function(){
                ea.firstLoad(false);
                app.loading(false);
            }, 500);
        }
    }, 100);
}

$(function() {

    $("input[name=convert0][value=tohours0]").prop('checked', true);
    $("input[name=convert1][value=tohours1]").prop('checked', true);
    $("input[name=convert2][value=tohours2]").prop('checked', true);

    $(".btnhours0").addClass("active");
    $(".btnhours1").addClass("active");
    $(".btnhours2").addClass("active");

    $('#btnRefresh').on('click', function () {
        ea.firstLoad(true);
        realDesc = {};
        ea.autoGenerateLevel1({level : "level0", breakDownEa: "detailgroup" , additionalfilter: {}}, ea.checkType(0));
        fa.checkTurbine();
    });

    $('#periodList').kendoDropDownList({
        data: fa.periodList,
        dataValueField: 'value',
        dataTextField: 'text',
        suggest: true,
        change: function () { fa.showHidePeriod() }
    });

    $('#projectList').kendoDropDownList({
        data: fa.projectList,
        dataValueField: 'value',
        dataTextField: 'text',
        suggest: true,
        change: function () {
            var project = $('#projectList').data("kendoDropDownList").value();
            fa.populateTurbine(project);
            ea.getDataAvailableInfo(true);
        }
    });

    setTimeout(function(){
        ea.getDataAvailableInfo(true);
        ea.autoGenerateLevel1({level : "level0"}, ea.checkType(0));
    }, 300)
});


text:
package ru.spbau.mit.dbmsau.command;

import ru.spbau.mit.dbmsau.Context;
import ru.spbau.mit.dbmsau.command.exception.CommandExecutionException;
import ru.spbau.mit.dbmsau.exception.UserError;
import ru.spbau.mit.dbmsau.relation.ColumnAccessor;
import ru.spbau.mit.dbmsau.relation.Relation;
import ru.spbau.mit.dbmsau.table.Table;

import java.util.List;

abstract public class AbstractSQLCommand {
    private Context context;

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    protected Table getTable(String name) {
        Table table = getContext().getTableManager().getTable(name);

        if (table == null) {
            throw new UserError("No such table `" + name + "`");
        }

        return table;
    }

    protected int[] getColumnIndexesOf(Relation relation, List<ColumnAccessor> accessors) {
        getContext().getSemanticValidator().checkColumnsAccessors(relation, accessors);

        int[] columnsIndexes = new int[accessors.size()];
        int index = 0;

        for (ColumnAccessor accessor : accessors) {
            columnsIndexes[index++] = accessor.getColumnIndex(relation);
        }

        return columnsIndexes;
    }

    abstract public SQLCommandResult execute() throws CommandExecutionException;
}


text:
using System;

namespace osu.Framework.Graphics.Transforms
{
    /// <summary>
    /// An easing function corresponding to one of the <see cref="Easing"/> types.
    /// </summary>
    public readonly struct DefaultEasingFunction : IEasingFunction
    {
        private const double elastic_const = 2 * Math.PI / .3;
        private const double elastic_const2 = .3 / 4;

        private const double back_const = 1.70158;
        private const double back_const2 = back_const * 1.525;

        private const double bounce_const = 1 / 2.75;

        // constants used to fix expo and elastic curves to start/end at 0/1
        private static readonly double expo_offset = Math.Pow(2, -10);
        private static readonly double elastic_offset_full = Math.Pow(2, -11);
        private static readonly double elastic_offset_half = Math.Pow(2, -10) * Math.Sin((.5 - elastic_const2) * elastic_const);
        private static readonly double elastic_offset_quarter = Math.Pow(2, -10) * Math.Sin((.25 - elastic_const2) * elastic_const);
        private static readonly double in_out_elastic_offset = Math.Pow(2, -10) * Math.Sin((1 - elastic_const2 * 1.5) * elastic_const / 1.5);

        private readonly Easing easing;

        /// <summary>
        /// Creates a new <see cref="DefaultEasingFunction"/> for an <see cref="Easing"/>.
        /// </summary>
        /// <param name="easing">The <see cref="Easing"/> type.</param>
        public DefaultEasingFunction(Easing easing)
        {
            this.easing = easing;
        }

        public double ApplyEasing(double time)
        {
            switch (easing)
            {
                default:
                    return time;

                case Easing.In:
                case Easing.InQuad:
                    return time * time;

                case Easing.Out:
                case Easing.OutQuad:
                    return time * (2 - time);

                case Easing.InOutQuad:
                    if (time < .5) return time * time * 2;

                    return --time * time * -2 + 1;

                case Easing.InCubic:
                    return time * time * time;

                case Easing.OutCubic:
                    return --time * time * time + 1;

                case Easing.InOutCubic:
                    if (time < .5) return time * time * time * 4;

                    return --time * time * time * 4 + 1;

                case Easing.InQuart:
                    return time * time * time * time;

                case Easing.OutQuart:
                    return 1 - --time * time * time * time;

                case Easing.InOutQuart:
                    if (time < .5) return time * time * time * time * 8;

                    return --time * time * time * time * -8 + 1;

                case Easing.InQuint:
                    return time * time * time * time * time;

                case Easing.OutQuint:
                    return --time * time * time * time * time + 1;

                case Easing.InOutQuint:
                    if (time < .5) return time * time * time * time * time * 16;

                    return --time * time * time * time * time * 16 + 1;

                case Easing.InSine:
                    return 1 - Math.Cos(time * Math.PI * .5);

                case Easing.OutSine:
                    return Math.Sin(time * Math.PI * .5);

                case Easing.InOutSine:
                    return .5 - .5 * Math.Cos(Math.PI * time);

                case Easing.InExpo:
                    return Math.Pow(2, 10 * (time - 1)) + expo_offset * (time - 1);

                case Easing.OutExpo:
                    return -Math.Pow(2, -10 * time) + 1 + expo_offset * time;

                case Easing.InOutExpo:
                    if (time < .5) return .5 * (Math.Pow(2, 20 * time - 10) + expo_offset * (2 * time - 1));

                    return 1 - .5 * (Math.Pow(2, -20 * time + 10) + expo_offset * (-2 * time + 1));

                case Easing.InCirc:
                    return 1 - Math.Sqrt(1 - time * time);

                case Easing.OutCirc:
                    return Math.Sqrt(1 - --time * time);

                case Easing.InOutCirc:
                    if ((time *= 2) < 1) return .5 - .5 * Math.Sqrt(1 - time * time);

                    return .5 * Math.Sqrt(1 - (time -= 2) * time) + .5;

                case Easing.InElastic:
                    return -Math.Pow(2, -10 + 10 * time) * Math.Sin((1 - elastic_const2 - time) * elastic_const) + elastic_offset_full * (1 - time);

                case Easing.OutElastic:
                    return Math.Pow(2, -10 * time) * Math.Sin((time - elastic_const2) * elastic_const) + 1 - elastic_offset_full * time;

                case Easing.OutElasticHalf:
                    return Math.Pow(2, -10 * time) * Math.Sin((.5 * time - elastic_const2) * elastic_const) + 1 - elastic_offset_half * time;

                case Easing.OutElasticQuarter:
                    return Math.Pow(2, -10 * time) * Math.Sin((.25 * time - elastic_const2) * elastic_const) + 1 - elastic_offset_quarter * time;

                case Easing.InOutElastic:
                    if ((time *= 2) < 1)
                    {
                        return -.5 * (Math.Pow(2, -10 + 10 * time) * Math.Sin((1 - elastic_const2 * 1.5 - time) * elastic_const / 1.5)
                                      - in_out_elastic_offset * (1 - time));
                    }

                    return .5 * (Math.Pow(2, -10 * --time) * Math.Sin((time - elastic_const2 * 1.5) * elastic_const / 1.5)
                                 - in_out_elastic_offset * time) + 1;

                case Easing.InBack:
                    return time * time * ((back_const + 1) * time - back_const);

                case Easing.OutBack:
                    return --time * time * ((back_const + 1) * time + back_const) + 1;

                case Easing.InOutBack:
                    if ((time *= 2) < 1) return .5 * time * time * ((back_const2 + 1) * time - back_const2);

                    return .5 * ((time -= 2) * time * ((back_const2 + 1) * time + back_const2) + 2);

                case Easing.InBounce:
                    time = 1 - time;
                    if (time < bounce_const)
                        return 1 - 7.5625 * time * time;
                    if (time < 2 * bounce_const)
                        return 1 - (7.5625 * (time -= 1.5 * bounce_const) * time + .75);
                    if (time < 2.5 * bounce_const)
                        return 1 - (7.5625 * (time -= 2.25 * bounce_const) * time + .9375);

                    return 1 - (7.5625 * (time -= 2.625 * bounce_const) * time + .984375);

                case Easing.OutBounce:
                    if (time < bounce_const)
                        return 7.5625 * time * time;
                    if (time < 2 * bounce_const)
                        return 7.5625 * (time -= 1.5 * bounce_const) * time + .75;
                    if (time < 2.5 * bounce_const)
                        return 7.5625 * (time -= 2.25 * bounce_const) * time + .9375;

                    return 7.5625 * (time -= 2.625 * bounce_const) * time + .984375;

                case Easing.InOutBounce:
                    if (time < .5) return .5 - .5 * new DefaultEasingFunction(Easing.OutBounce).ApplyEasing(1 - time * 2);

                    return new DefaultEasingFunction(Easing.OutBounce).ApplyEasing((time - .5) * 2) * .5 + .5;

                case Easing.OutPow10:
                    return --time * Math.Pow(time, 10) + 1;
            }
        }
    }
}


text: .container {float:left; width: 200px;margin:5px}


text:
package org.usfirst.frc0.MyRobot.subsystems;

import edu.wpi.first.wpilibj.command.Subsystem;

/*
 * Mechanism to stack and place totes/can
 */
public interface ILifter {

	public void moveLift(double power);

	public void stop();

	// Move lifter to a certain position between 0-5
	public void moveTo(double position);

}


text:
@interface CFAddProductViewController : UIViewController <ZXCaptureDelegate>

@property (nonatomic,weak) IBOutlet UIView *masqueBlackTop;
@property (nonatomic,weak) IBOutlet UIView *masqueBlackLeft;
@property (nonatomic,weak) IBOutlet UIView *masqueBlackRight;
@property (nonatomic,weak) IBOutlet UIView *masqueBlackBottom;
@property (nonatomic,weak) IBOutlet UIView *scanRectView;
@property (nonatomic,weak) IBOutlet UIView *camOverlay;
@property (nonatomic,weak) IBOutlet UIView *header;

@end


text:
package com.asquera.elasticsearch.plugins.http.auth;

import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;

/**
 *
 * Class that handles the values obtained from the X-Forwarded-For (XFF) HTTP Header
 * field.
 *

 * The X-Forwarded-For (XFF) HTTP header field is a de facto standard for
 * identifying the originating IP address of a client connecting to a web
 * server through an HTTP proxy or load balancer.
 *

 * The usefulness of XFF depends on the proxy server truthfully reporting the
 * original host's IP address; for this reason, effective use of XFF requires
 * knowledge of which proxies are trustworthy, for instance by looking them
 * up in a whitelist of servers whose maintainers can be trusted.
 *
 * @see X-Forwarded-For
 *
 *
 *
 * @author Ernesto Miguez (ernesto.miguez@asquera.de)
 */

public class XForwardedFor {
  /**
   *
   * The X-Forwarded-For Header value as received in the request
   * The general format of the field is:
   *
   *     X-Forwarded-For: client, proxy1, proxy2
   */
  private final String xForwardedFor;

  /**
   *
   * @param xForwardedFor
   */
  public XForwardedFor(String xForwardedFor) {
    this.xForwardedFor = xForwardedFor != null ? xForwardedFor : "";
  }

  /**
   * @return the ip of the client as defined by the X-Forwarded-For Header
   */
  public String client() {
    ArrayList<String> splitted_ips =  new ArrayList<String>(
        Arrays.asList(xForwardedFor.split(",")));
    return splitted_ips.remove(0);
  }

  /**
   *
   * @return true if the X-Forwarded-For header was set
   */
  public boolean isSet() {
    return ! xForwardedFor.equals("");
  }

  /**
   *  delegate method
   */
  @Override
  public String toString() {
    String s = "not used";
    if (isSet()) {
      s = xForwardedFor;
    }
    return s;
  }

  /**
   * @return the ips of the proxies between the client(as defined by the
   * X-Forwarded-For Header) and the * server
   */
  protected List<String> proxies() {
    ArrayList<String> splitted_ips =  new ArrayList<String>(
        Arrays.asList(xForwardedFor.split(",")));
    splitted_ips.remove(0);
    return splitted_ips;
  }

  /**
   * @return the xForwardedFor
   */
  public String getxForwardedFor() {
    return xForwardedFor;
  }
}


text:
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Demography Database - Login{% endblock %}

{% block page_content %}

Login

    Log in with google (New and existing users)

{% endblock %}


text:
var loginVisible = false,
    dropdownOpen = false,
    keyboardHelpVisible = false,
    urlHelpVisible = false;

$document.keydown(function (event) {
  if (event.which == 27) {//} || (keyboardHelpVisible && event.which == 191 && event.shiftKey && event.metaKey)) {
    hideOpen();
  }
});

function hideOpen() {
  if (urlHelpVisible) {
    $body.removeClass('urlHelp');
    urlHelpVisible = false;
    analytics.closeMenu('help');
  } else if (keyboardHelpVisible) {
    $body.removeClass('keyboardHelp');
    keyboardHelpVisible = false;
    analytics.closeMenu('keyboardHelp');
  } else if (dropdownOpen) {
    var open = $('.menu.open').removeClass('open');
    analytics.closeMenu(open.find('.button')[0].hash.substring(1));
    dropdownOpen = false;
  } else if (loginVisible) {
    $('#login').hide();
    analytics.closeMenu('login');
    loginVisible = false;
  }
}

$document.delegate('.modal', 'click', function (event) {
  if ($(event.target).is('.modal')) {
    hideOpen();
  }
});


text:
package pl.touk.nussknacker.engine.process.runner

import org.apache.flink.configuration.Configuration
import org.apache.flink.runtime.jobgraph.SavepointRestoreSettings
import pl.touk.nussknacker.engine.ModelData
import pl.touk.nussknacker.engine.api.ProcessVersion
import pl.touk.nussknacker.engine.api.process.ProcessName
import pl.touk.nussknacker.engine.api.test.TestData
import pl.touk.nussknacker.engine.canonicalgraph.CanonicalProcess
import pl.touk.nussknacker.engine.deployment.DeploymentData
import pl.touk.nussknacker.engine.process.ExecutionConfigPreparer
import pl.touk.nussknacker.engine.process.compiler.TestFlinkProcessCompiler
import pl.touk.nussknacker.engine.process.registrar.FlinkProcessRegistrar
import pl.touk.nussknacker.engine.testmode.TestProcess.TestResults
import pl.touk.nussknacker.engine.testmode.{ResultsCollectingListener, ResultsCollectingListenerHolder}

object FlinkTestMain extends FlinkRunner {

  def run[T](modelData: ModelData, process: CanonicalProcess, testData: TestData, configuration: Configuration, variableEncoder: Any => T): TestResults[T] = {
    val processVersion = ProcessVersion.empty.copy(processName = ProcessName("snapshot version")) // testing process may be unreleased, so it has no version
    new FlinkTestMain(modelData, process, testData, processVersion, DeploymentData.empty, configuration).runTest(variableEncoder)
  }

}

class FlinkTestMain(val modelData: ModelData,
                    val process: CanonicalProcess,
                    testData: TestData,
                    processVersion: ProcessVersion,
                    deploymentData: DeploymentData,
                    val configuration: Configuration)
  extends FlinkStubbedRunner {

  def runTest[T](variableEncoder: Any => T): TestResults[T] = {
    val env = createEnv
    val collectingListener = ResultsCollectingListenerHolder.registerRun(variableEncoder)
    try {
      val registrar: FlinkProcessRegistrar = prepareRegistrar(collectingListener, testData)
      registrar.register(env, process, processVersion, deploymentData, Option(collectingListener.runId))
      execute(env, SavepointRestoreSettings.none())
      collectingListener.results
    } finally {
      collectingListener.clean()
    }
  }

  protected def prepareRegistrar[T](collectingListener: ResultsCollectingListener, testData: TestData): FlinkProcessRegistrar = {
    FlinkProcessRegistrar(new TestFlinkProcessCompiler(
      modelData.configCreator,
      modelData.processConfig,
      collectingListener,
      process,
      testData,
      modelData.objectNaming),
      ExecutionConfigPreparer.defaultChain(modelData))
  }
}


text:
#import <UIKit/UIKit.h>

@interface SampleAppSelectorViewController : UITableViewController

@end


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUserRolesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('user_roles', function (Blueprint $table) {
            $type = DB::connection()->getDoctrineColumn('users', 'id')->getType()->getName();
            if ($type == 'bigint') {
                $table->integer('user_id')->unsigned()->index();
            } else {
                $table->integer('user_id')->unsigned()->index();
            }

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->integer('role_id')->unsigned()->index();
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->primary(['user_id', 'role_id']);
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('user_roles');
    }
}


text:
package com.asakusafw.utils.java.internal.model.syntax;

import com.asakusafw.utils.java.model.syntax.Expression;
import com.asakusafw.utils.java.model.syntax.ModelKind;
import com.asakusafw.utils.java.model.syntax.ThrowStatement;
import com.asakusafw.utils.java.model.syntax.Visitor;

/**
 * An implementation of {@link ThrowStatement}.
 */
public final class ThrowStatementImpl extends ModelRoot implements ThrowStatement {

    private Expression expression;

    @Override
    public Expression getExpression() {
        return this.expression;
    }

    /**
     * Sets the thrown object.
     * @param expression the thrown object
     * @throws IllegalArgumentException if {@code expression} was {@code null}
     */
    public void setExpression(Expression expression) {
        Util.notNull(expression, "expression"); //$NON-NLS-1$
        this.expression = expression;
    }

    /**
     * Returns {@link ModelKind#THROW_STATEMENT} which represents this element kind.
     * @return {@link ModelKind#THROW_STATEMENT}
     */
    @Override
    public ModelKind getModelKind() {
        return ModelKind.THROW_STATEMENT;
    }

    @Override
    public <R, C, E extends Throwable> R accept(Visitor<R, C, E> visitor, C context) throws E {
        Util.notNull(visitor, "visitor"); //$NON-NLS-1$
        return visitor.visitThrowStatement(this, context);
    }
}


text:
/**
 * Created by coverguo on 2015/01/12.
 */

var http = require('http');

var log4js = require('log4js'),
    logger = log4js.getLogger();

var ApproveService = function (){
    this.approveDao = GLOBAL.models.approveDao;
    this.applyDao = GLOBAL.models.applyDao;

};

ApproveService.prototype = {
    query : function (target , callback){

            //管理员
            if(target.user.role ==1){
                this.approveDao.all({} , function (err , items){
                    if(err){
                        callback(err);
                        return;
                    }
                    callback(null,{ret:0, msg:"success", data: items});
                });
            }else{
                this.approveDao.find({userName: target.user.loginName} , function (err , items){
                    if(err){
                        callback(err);
                        return;
                    }
                    callback(null,{ret:0, msg:"success", data: items});
                });
            }

    },
    add: function(target, callback){
        var self = this;
        this.approveDao.create(target , function (err , items){
            if(err){
                callback(err);
                return;
            }
            logger.info("Insert into b_approve success! target: ",target);
            //改变申请表状态
            var apply={
                id : parseInt(target.applyId,10),
                status : parseInt(target.applyStatus,10)
            };
            if(target.applyStatus ==1) {
                apply.passTime = target.createTime;
            }
            self.update(apply, function(err, data){
                if(err){
                    callback(err);
                    return;
                }
                logger.info("Update b_apply success! apply: ",apply);
                callback(null,{ret:0, msg:"success add"});
            })

        });

    },
    remove : function(target, callback){

    },
    update : function(target, callback){
        this.applyDao.one({id: target.id }, function (err, apply) {
            // SQL: "SELECT * FROM b_apply WHERE name = 'xxxx'"
            for(key in target){
                apply[key] = target[key];
            }
            apply.save(function (err) {
                if(err){
                    callback(err);
                    return;
                }
                callback(null);
            });
        });
    }
}

module.exports =  ApproveService;


text:
package configs

import (
	"fmt"

	"github.com/hashicorp/hcl2/hcl"
)

// Provisioner represents a "provisioner" block when used within a
// "resource" block in a module or file.
type Provisioner struct {
	Type       string
	Config     hcl.Body
	Connection *Connection
	When       ProvisionerWhen
	OnFailure  ProvisionerOnFailure

	DeclRange hcl.Range
	TypeRange hcl.Range
}

func decodeProvisionerBlock(block *hcl.Block) (*Provisioner, hcl.Diagnostics) {
	pv := &Provisioner{
		Type:      block.Labels[0],
		TypeRange: block.LabelRanges[0],
		DeclRange: block.DefRange,
		When:      ProvisionerWhenCreate,
		OnFailure: ProvisionerOnFailureFail,
	}

	content, config, diags := block.Body.PartialContent(provisionerBlockSchema)
	pv.Config = config

	if attr, exists := content.Attributes["when"]; exists {
		expr, shimDiags := shimTraversalInString(attr.Expr, true)
		diags = append(diags, shimDiags...)

		switch hcl.ExprAsKeyword(expr) {
		case "create":
			pv.When = ProvisionerWhenCreate
		case "destroy":
			pv.When = ProvisionerWhenDestroy
		default:
			diags = append(diags, &hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Invalid \"when\" keyword",
				Detail:   "The \"when\" argument requires one of the following keywords: create or destroy.",
				Subject:  expr.Range().Ptr(),
			})
		}
	}

	if attr, exists := content.Attributes["on_failure"]; exists {
		expr, shimDiags := shimTraversalInString(attr.Expr, true)
		diags = append(diags, shimDiags...)

		switch hcl.ExprAsKeyword(expr) {
		case "continue":
			pv.OnFailure = ProvisionerOnFailureContinue
		case "fail":
			pv.OnFailure = ProvisionerOnFailureFail
		default:
			diags = append(diags, &hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Invalid \"on_failure\" keyword",
				Detail:   "The \"on_failure\" argument requires one of the following keywords: continue or fail.",
				Subject:  attr.Expr.Range().Ptr(),
			})
		}
	}

	var seenConnection *hcl.Block
	for _, block := range content.Blocks {
		switch block.Type {

		case "connection":
			if seenConnection != nil {
				diags = append(diags, &hcl.Diagnostic{
					Severity: hcl.DiagError,
					Summary:  "Duplicate connection block",
					Detail:   fmt.Sprintf("This provisioner already has a connection block at %s.", seenConnection.DefRange),
					Subject:  &block.DefRange,
				})
				continue
			}
			seenConnection = block

			//conn, connDiags := decodeConnectionBlock(block)
			//diags = append(diags, connDiags...)
			pv.Connection = &Connection{
				Config:    block.Body,
				DeclRange: block.DefRange,
			}

		default:
			// Any other block types are ones we've reserved for future use,
			// so they get a generic message.
			diags = append(diags, &hcl.Diagnostic{
				Severity: hcl.DiagError,
				Summary:  "Reserved block type name in provisioner block",
				Detail:   fmt.Sprintf("The block type name %q is reserved for use by Terraform in a future version.", block.Type),
				Subject:  &block.TypeRange,
			})
		}
	}

	return pv, diags
}

// Connection represents a "connection" block when used within either a
// "resource" or "provisioner" block in a module or file.
type Connection struct {
	Config hcl.Body

	DeclRange hcl.Range
}

// ProvisionerWhen is an enum for valid values for when to run provisioners.
type ProvisionerWhen int

//go:generate stringer -type ProvisionerWhen

const (
	ProvisionerWhenInvalid ProvisionerWhen = iota
	ProvisionerWhenCreate
	ProvisionerWhenDestroy
)

// ProvisionerOnFailure is an enum for valid values for on_failure options
// for provisioners.
type ProvisionerOnFailure int

//go:generate stringer -type ProvisionerOnFailure

const (
	ProvisionerOnFailureInvalid ProvisionerOnFailure = iota
	ProvisionerOnFailureContinue
	ProvisionerOnFailureFail
)

var provisionerBlockSchema = &hcl.BodySchema{
	Attributes: []hcl.AttributeSchema{
		{Name: "when"},
		{Name: "on_failure"},
	},
	Blocks: []hcl.BlockHeaderSchema{
		{Type: "connection"},
		{Type: "lifecycle"}, // reserved for future use
	},
}


text:
module Main where

import ALife.Creatur.Util (shuffle)
import ALife.Creatur.Wain.Audio.Pattern
import ALife.Creatur.Wain.Statistics (mean, popStdDev)
import ALife.Creatur.Wain.UnitInterval (uiToDouble)
import Control.Monad (foldM)
import Control.Monad.Random (evalRand, mkStdGen)
import System.Directory (getDirectoryContents)
import System.Environment (getArgs)
import System.FilePath.Posix (takeFileName)

numTests :: Int
numTests = 500

readDirAndShuffle :: FilePath -> IO [FilePath]
readDirAndShuffle d = do
  let g = mkStdGen 263167 -- seed
  let d2 = d ++ "/"
  files <- map (d2 ++) . drop 2 <$> getDirectoryContents d
  return $ evalRand (shuffle files) g

readAudio2 :: Int -> FilePath -> IO (Pattern, Int)
readAudio2 nvec f = do
  img <- readAudio f nvec
  return (img, read [takeFileName f !! 1])

run :: ([Double], [Double]) -> ((Pattern, Int), (Pattern, Int))
        -> IO ([Double], [Double])
run (intraDiffs, interDiffs) ((i1, n1), (i2, n2)) = do
  putStr $ show n1 ++ " " ++ show n2 ++ " "
  let d = uiToDouble $ audioDiff i1 i2
  if n1 == n2
    then do
      putStrLn $ "same " ++ show d
      return (d:intraDiffs, interDiffs)
    else do
      putStrLn $ "diff " ++ show d
      return (intraDiffs, d:interDiffs)

main :: IO ()
main = do
  args <- getArgs
  let dir = head args
  let nvec = read $ args !! 1
  putStrLn $ "numTests=" ++ show numTests
  files <- take numTests . drop 2 <$> readDirAndShuffle dir
  imgs <- mapM (readAudio2 nvec) files
  let imgPairs = [(a, b) | a <- imgs, b <- imgs, a /= b]
  (intraDiffs, interDiffs) <- foldM run ([], []) imgPairs
  putStrLn $ "Intra-cluster mean diff=" ++ show (mean intraDiffs)
  putStrLn $ "Intra-cluster std dev diff=" ++ show (popStdDev intraDiffs)
  putStrLn $ "Inter-cluster mean diff=" ++ show (mean interDiffs)
  putStrLn $ "Inter-cluster std dev diff=" ++ show (popStdDev interDiffs)
  putStrLn "test complete"


text:
<?php

namespace Scene7\Commands\Layer;

trait Source
{
    // @todo I don't understand the documentation for this so for now, it's just a string
    public function setSource($source)
    {
        return $this->addCommand(['source' => $source]);
    }
}


text:
package com.android.providers.downloads.permission.tests;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.MediumTest;

import tree.love.providers.downloads.Downloads;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Verify that protected Download provider actions require specific permissions.
 *
 * TODO: consider adding test where app has ACCESS_DOWNLOAD_MANAGER, but not
 * ACCESS_DOWNLOAD_MANAGER_ADVANCED
 */
public class DownloadProviderPermissionsTest extends AndroidTestCase {

    private ContentResolver mContentResolver;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mContentResolver = getContext().getContentResolver();
    }

    /**
     * Test that an app cannot access the /cache filesystem
     *
Tests Permission:
     *   {@link android.Manifest.permission#ACCESS_CACHE_FILESYSTEM}
     */
    @MediumTest
    public void testAccessCacheFilesystem() throws IOException {
        try {
            String filePath = "/cache/this-should-not-exist.txt";
            FileOutputStream strm = new FileOutputStream(filePath);
            strm.write("Oops!".getBytes());
            strm.flush();
            strm.close();
            fail("Was able to create and write to " + filePath);
        } catch (SecurityException e) {
            // expected
        } catch (FileNotFoundException e) {
            // also could be expected
        }
    }

    /**
     * Test that an untrusted app cannot write to the download provider
     *
Tests Permission:
     *   {@link com.android.providers.downloads.Manifest.permission#ACCESS_DOWNLOAD_MANAGER}
     *   and
     *   {@link android.Manifest.permission#INTERNET}
     */
    @MediumTest
    public void testWriteDownloadProvider() {
        try {
            ContentValues values = new ContentValues();
            values.put(Downloads.Impl.COLUMN_URI, "foo");
            mContentResolver.insert(Downloads.Impl.CONTENT_URI, values);
            fail("write to provider did not throw SecurityException as expected.");
        } catch (SecurityException e) {
            // expected
        }
    }

    /**
     * Test that an untrusted app cannot access the download service
     *
Tests Permission:
     *   {@link com.android.providers.downloads.Manifest.permission#ACCESS_DOWNLOAD_MANAGER}
     */
    @MediumTest
    public void testStartDownloadService() {
        try {
            Intent downloadServiceIntent = new Intent();
            downloadServiceIntent.setClassName("com.android.providers.downloads",
                    "com.android.providers.downloads.DownloadService");
            getContext().startService(downloadServiceIntent);
            fail("starting download service did not throw SecurityException as expected.");
        } catch (SecurityException e) {
            // expected
        }
    }
}


text:
using System;
using UnityEngine;
using Object = UnityEngine.Object;

namespace HouraiTeahouse {

    /// <summary> A PropertyAttribute for the Unity Editor. Marks a string field to store a path to an asset stored in a
    /// Resources folder. The resultant string can be used with Resources.Load to get said asset. The Unity Editor UI shows a
    /// object field instead of a string field. </summary>
    [AttributeUsage(AttributeTargets.Field)]
    public class ResourceAttribute : PropertyAttribute {

        static readonly Type ObjectType = typeof(Object);

        /// <summary> Initializes a new instance of ResourceAttribute. </summary>
        /// <param name="type"> Optional type restriction on the type of Resource object to use. No restriction is applied if null
        /// or not derived from UnityEngine.Object </param>
        public ResourceAttribute(Type type = null) {
            TypeRestriction = ObjectType;
            if (type == null)
                return;
            if (ObjectType.IsAssignableFrom(type))
                TypeRestriction = type;
            else
                Log.Warning(
                    "Trying to get a resource type restriction on type: {0} is impossible. Use a type derived from UnityEngine.Object.",
                    type.FullName);
        }

        /// <summary> The type of asset to be stored. All instances of this type, including those of derived types, can be used. </summary>
        public Type TypeRestriction { get; private set; }

    }

}