text:
/* SoftAP based Provisioning Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <string.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_system.h>
#include <esp_wifi.h>
#include <esp_event.h>
#include <esp_log.h>
#include <nvs_flash.h>

#include <lwip/err.h>
#include <lwip/sys.h>

#include "app_prov.h"

#define EXAMPLE_AP_RECONN_ATTEMPTS  CONFIG_AP_RECONN_ATTEMPTS

static const char *TAG = "app";

static void event_handler(void* arg, esp_event_base_t event_base,
                          int event_id, void* event_data)
{
    static int s_retry_num = 0;

    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        esp_wifi_connect();
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
        if (s_retry_num < EXAMPLE_AP_RECONN_ATTEMPTS) {
            esp_wifi_connect();
            s_retry_num++;
            ESP_LOGI(TAG, "retry to connect to the AP");
        }
        ESP_LOGI(TAG,"connect to the AP fail");
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
        ESP_LOGI(TAG, "got ip:%s",
                 ip4addr_ntoa(&event->ip_info.ip));
        s_retry_num = 0;
    }
}

static void wifi_init_sta()
{
    /* Set our event handling */
    ESP_ERROR_CHECK(esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, event_handler, NULL));
    ESP_ERROR_CHECK(esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, event_handler, NULL));

    /* Start Wi-Fi in station mode with credentials set during provisioning */
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    ESP_ERROR_CHECK(esp_wifi_start());
}

static void start_softap_provisioning()
{
    /* Security version */
    int security = 0;
    /* Proof of possession */
    const protocomm_security_pop_t *pop = NULL;

#ifdef CONFIG_USE_SEC_1
    security = 1;
#endif

    /* Having proof of possession is optional */
#ifdef CONFIG_USE_POP
    const static protocomm_security_pop_t app_pop = {
        .data = (uint8_t *) CONFIG_POP,
        .len = (sizeof(CONFIG_POP)-1)
    };
    pop = &app_pop;
#endif

        const char *ssid = NULL;

#ifdef CONFIG_SOFTAP_SSID
        ssid = CONFIG_SOFTAP_SSID;
#else
        uint8_t eth_mac[6];
        esp_wifi_get_mac(WIFI_IF_STA, eth_mac);

        char ssid_with_mac[33];
        snprintf(ssid_with_mac, sizeof(ssid_with_mac), "PROV_%02X%02X%02X",
                 eth_mac[3], eth_mac[4], eth_mac[5]);

        ssid = ssid_with_mac;
#endif

    ESP_ERROR_CHECK(app_prov_start_softap_provisioning(
        ssid, CONFIG_SOFTAP_PASS, security, pop));
}

void app_main()
{
    /* Initialize networking stack */
    tcpip_adapter_init();

    /* Create default event loop needed by the
     * main app and the provisioning service */
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    /* Initialize NVS needed by Wi-Fi */
    ESP_ERROR_CHECK(nvs_flash_init());

    /* Initialize Wi-Fi with default config */
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    /* Check if device is provisioned */
    bool provisioned;
    if (app_prov_is_provisioned(&provisioned) != ESP_OK) {
        ESP_LOGE(TAG, "Error getting device provisioning state");
        return;
    }

    if (provisioned == false) {
        /* If not provisioned, start provisioning via soft AP */
        ESP_LOGI(TAG, "Starting WiFi SoftAP provisioning");
        start_softap_provisioning();
    } else {
        /* Start WiFi station with credentials set during provisioning */
        ESP_LOGI(TAG, "Starting WiFi station");
        wifi_init_sta();
    }
}


text:
from mimetypes import guess_type

from django.http import HttpResponse, HttpResponseRedirect
from django.utils.encoding import smart_str
from django.utils.translation import ugettext as _
from django.db.models import F
from django.conf import settings
from django.utils.datastructures import SortedDict

from jmbo.views import ObjectList as JmboObjectList

from category.models import Category

from downloads.models import Download
from downloads.signals import download_requested

def download_request(request, slug):
    # explicitly pass True to get_query_set to include invisible downloads
    download = Download.permitted.get_query_set(True).get(slug=slug)
    download = download.as_leaf_class()

    # increment view count
    # contains race condition: download.view_count += 1
    download.view_count = F('view_count') + 1
    download.save()

    # send signal for other apps to track the download
    download_requested.send(
        sender=download,
        request=request
    )

    f, file_name = download.get_file(request)

    # set this to 'REMOTE' if the request should be redirected
    # to remote storage (like S3)
    serve_method = getattr(settings, 'DOWNLOAD_SERVE_FROM', 'LOCAL')

    # files generated on the fly need to be served locally
    if serve_method == 'LOCAL':
        mime = guess_type(f.name)
        response = HttpResponse(content_type=mime[0])

        # check if it has encoding
        if mime[1]:
            response['Content-Encoding'] = mime[1]
        response['Content-Disposition'] = ('attachment; filename="%s"'
                                           % smart_str(file_name))
        response['Cache-Control'] = 'no-cache, no-store, must-revalidate'
        response['Expires'] = '0'
        response['Pragma'] = 'no-store, no-cache'
        response[getattr(settings, 'DOWNLOAD_INTERNAL_REDIRECT_HEADER',
                         'X-Accel-Redirect')] = smart_str(f.url)

    else:
        response = HttpResponseRedirect(smart_str(f.url))

    return response

class ObjectList(JmboObjectList):

    def get_extra_context(self, *args, **kwargs):
        dls = list(Download.permitted.all())

        # create dictionary of categories
        cat_dict = SortedDict((id, {'parent': parent,
                                    'title': title,
                                    'items': [],
                                    'subcats': [],
                                    'slug': slug,
                                    'child_count': 0})
                              for (id, parent, title, slug) in
                              Category.objects.values_list('id', 'parent',
                                                           'title', 'slug'))
        # add None key for downloads without a category
        cat_dict[None] = {
            'parent': None,
            'items': [],
            'child_count': 0,
            'subcats': []
        }

        # add downloads to category item lists
        for dl in dls:
            cat_dict[dl.primary_category_id]['items'].append(dl)

        # nest subcategories
        for key, val in cat_dict.items():
            if val['parent']:
                cat_dict[val['parent']]['subcats'].append(key)
            child_count = len(val['items'])
            val['child_count'] += child_count
            if child_count > 0:
                parent_id = val['parent']
                while parent_id:
                    cat_dict[parent_id]['child_count'] += child_count
                    parent_id = cat_dict[parent_id]['parent']

        # remove categories with no items in them
        category_list = []
        for key, val in cat_dict.items():
            subcats = []
            for subcat in val['subcats']:
                if cat_dict[subcat]['child_count'] > 0:
                    subcats.append(cat_dict[subcat])
            val['subcats'] = subcats
            if val['child_count'] > 0 and not val['parent']:
                category_list.append(val)

        return {'title': _('Downloads'), 'category_list': category_list}

    def get_queryset(self, *args, **kwargs):
        return Download.permitted.none()

    def get_paginate_by(self, *args, **kwargs):
        return 20

    def get_template_name(self, *args, **kwargs):
        return "downloads/download_list_category.html"

redpajama_set_name: RedPajamaGithub


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

const tap = require('tap')

const silentConsole = {
  log() {},

  error() {}
}
const common = require('../common')

const Readable = require('../../lib/ours/index').Readable // This tests synchronous read callbacks and verifies that even if they nest
// heavily the process handles it without an error

const r = new Readable()
const N = 256 * 1024
let reads = 0

r._read = function (n) {
  const chunk = reads++ === N ? null : Buffer.allocUnsafe(1)
  r.push(chunk)
}

r.on('readable', function onReadable() {
  if (!(r.readableLength % 256)) silentConsole.error('readable', r.readableLength)
  r.read(N * 2)
})
r.on('end', common.mustCall())
r.read(0)
/* replacement start */

process.on('beforeExit', (code) => {
  if (code === 0) {
    tap.pass('test succeeded')
  } else {
    tap.fail(`test failed - exited code ${code}`)
  }
})
/* replacement end */


text:
import os
from setuptools import setup

classifiers = [
    'Development Status :: 4 - Beta',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: MIT License',
    'Operating System :: POSIX',
    'Operating System :: Microsoft :: Windows',
    'Operating System :: MacOS :: MacOS X',
    'Topic :: Software Development :: Testing',
    'Topic :: Software Development :: Libraries',
    'Topic :: Utilities',
    'Programming Language :: Python :: Implementation :: CPython',
    'Programming Language :: Python :: Implementation :: PyPy'] + [
    ('Programming Language :: Python :: %s' % x) for x in
    '2 2.7 3 3.4 3.5 3.6'.split()]

with open('README.rst') as fd:
    long_description = fd.read()

def get_version():
    p = os.path.join(os.path.dirname(
                     os.path.abspath(__file__)), "pluggy/__init__.py")
    with open(p) as f:
        for line in f.readlines():
            if "__version__" in line:
                return line.strip().split("=")[-1].strip(" '")
    raise ValueError("could not read version")

def main():
    setup(
        name='pluggy',
        description='plugin and hook calling mechanisms for python',
        long_description=long_description,
        version=get_version(),
        license='MIT license',
        platforms=['unix', 'linux', 'osx', 'win32'],
        author='Holger Krekel',
        author_email='holger@merlinux.eu',
        url='https://github.com/pytest-dev/pluggy',
        python_requires='>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*',
        classifiers=classifiers,
        packages=['pluggy'],
    )

if __name__ == '__main__':
    main()


text:
package data;

import org.apache.commons.lang3.tuple.MutablePair;
import org.junit.jupiter.api.Test;

import java.util.List;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class TableTest {

  @Test
  public void test_addColumn() {
    Table t = new Table("t", 1);
    t.addColumn("Test", DataType.STR);
    assertEquals(new MutablePair("Test", DataType.STR), t.getSchema().get(0));
  }

  @Test
  public void test_getRandomColumn() {
    Table t = new Table("t", 1);
    assertEquals("Test", t.getRandomColumn("Test", DataType.STR));
  }

  @Test
  public void test_generateColumn() {
    Table t = new Table("t", 1);
    List<?> integerData = t.generateColumn(1, DataType.INTEGER);
    assertEquals(integerData.get(0).getClass(), Integer.class);
  }

  @Test
  public void test_generateData() {
    Table t = new Table("t", 1);
    t.addColumn("Test", DataType.INTEGER);
    List<List<?>> data = t.generateData(1);
    assertEquals(data.get(0).get(0).getClass(), Integer.class);
  }

}


text:
*NOTE* - the npm module for _pitchfork_ does not current work with the new react based pitchfork site.

Pitchfork Preview
===========

Music discovery application that exposes Pitchfork.com reviews. Pitchfork.com/reviews does not expose the review score or any information about the genre of the artist on the list page. This makes browsing the reviews for discovery purposes reliant on browsing each review.

This application utilizes pitchfork-npm to fetch latest reviews per page and expose score as well as a blurb from the review to give you a sense of the genre of the artist.

Application built with nodejs and reactjs.

Testing
-------

Run `npm test` to run the unit tests. (`npm install` required)
See `scripts` in [package.json](./package.json)

Running
-------
install dependicies
`npm install`

compile jsx (via babel, es6 OK)
`gulp watch`

run application
`node app.js`


text:
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Schema::defaultStringLength(191);
        view()->share('column', config('page.column'));
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}


text:
"""Tests for the Windows prefetch parser."""

import unittest

from plaso.formatters import winprefetch  # pylint: disable=unused-import
from plaso.lib import eventdata
from plaso.lib import timelib
from plaso.parsers import winprefetch

from tests import test_lib as shared_test_lib
from tests.parsers import test_lib

class WinPrefetchParserTest(test_lib.ParserTestCase):
  """Tests for the Windows prefetch parser."""

  @shared_test_lib.skipUnlessHasTestFile([u'CMD.EXE-087B4001.pf'])
  def testParse17(self):
    """Tests the Parse function on a version 17 Prefetch file."""
    parser_object = winprefetch.WinPrefetchParser()
    storage_writer = self._ParseFile([u'CMD.EXE-087B4001.pf'], parser_object)

    self.assertEqual(len(storage_writer.events), 2)

    # The prefetch last run event.
    event = storage_writer.events[1]

    self.assertEqual(event.data_type, u'windows:prefetch:execution')
    self.assertEqual(event.version, 17)

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2013-03-10 10:11:49.281250')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc, eventdata.EventTimestamp.LAST_RUNTIME)
    self.assertEqual(event.executable, u'CMD.EXE')
    self.assertEqual(event.prefetch_hash, 0x087b4001)
    self.assertEqual(event.volume_serial_numbers[0], 0x24cb074b)

    expected_mapped_files = [
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\NTDLL.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\KERNEL32.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\UNICODE.NLS',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\LOCALE.NLS',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\SORTTBLS.NLS',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\MSVCRT.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\CMD.EXE',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\USER32.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\GDI32.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\SHIMENG.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\APPPATCH\\SYSMAIN.SDB',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\APPPATCH\\ACGENRAL.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\ADVAPI32.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\RPCRT4.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\WINMM.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\OLE32.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\OLEAUT32.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\MSACM32.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\VERSION.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\SHELL32.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\SHLWAPI.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\USERENV.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\UXTHEME.DLL',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\CTYPE.NLS',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\SORTKEY.NLS',
        (u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\WINSXS\\X86_MICROSOFT.WINDOWS.'
         u'COMMON-CONTROLS_6595B64144CCF1DF_6.0.2600.2180_X-WW_A84F1FF9\\'
         u'COMCTL32.DLL'),
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\WINDOWSSHELL.MANIFEST',
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\SYSTEM32\\COMCTL32.DLL',
        (u'\\DEVICE\\HARDDISKVOLUME1\\D50FF1E628137B1A251B47AB9466\\UPDATE\\'
         u'UPDATE.EXE.MANIFEST'),
        u'\\DEVICE\\HARDDISKVOLUME1\\$MFT',
        (u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\IE7\\SPUNINST\\SPUNINST.EXE.'
         u'MANIFEST'),
        (u'\\DEVICE\\HARDDISKVOLUME1\\D50FF1E628137B1A251B47AB9466\\UPDATE\\'
         u'IERESETICONS.EXE'),
        u'\\DEVICE\\HARDDISKVOLUME1\\WINDOWS\\IE7\\SPUNINST\\IERESETICONS.EXE']

    self.assertEqual(event.mapped_files, expected_mapped_files)

    # The volume creation event.
    event = storage_writer.events[0]

    self.assertEqual(event.data_type, u'windows:volume:creation')

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2013-03-10 10:19:46.234375')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc, eventdata.EventTimestamp.CREATION_TIME)

    expected_message = (
        u'\\DEVICE\\HARDDISKVOLUME1 '
        u'Serial number: 0x24CB074B '
        u'Origin: CMD.EXE-087B4001.pf')

    expected_message_short = (
        u'\\DEVICE\\HARDDISKVOLUME1 '
        u'Origin: CMD.EXE-087B4001.pf')

    self._TestGetMessageStrings(event, expected_message, expected_message_short)

  @shared_test_lib.skipUnlessHasTestFile([u'PING.EXE-B29F6629.pf'])
  def testParse23(self):
    """Tests the Parse function on a version 23 Prefetch file."""
    parser_object = winprefetch.WinPrefetchParser()
    storage_writer = self._ParseFile([u'PING.EXE-B29F6629.pf'], parser_object)

    self.assertEqual(len(storage_writer.events), 2)

    # The prefetch last run event.
    event = storage_writer.events[1]

    self.assertEqual(event.data_type, u'windows:prefetch:execution')
    self.assertEqual(event.version, 23)

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2012-04-06 19:00:55.932955')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc, eventdata.EventTimestamp.LAST_RUNTIME)

    self.assertEqual(event.executable, u'PING.EXE')
    self.assertEqual(event.prefetch_hash, 0xb29f6629)
    self.assertEqual(event.path, u'\\WINDOWS\\SYSTEM32\\PING.EXE')
    self.assertEqual(event.run_count, 14)
    self.assertEqual(event.volume_device_paths[0], u'\\DEVICE\\HARDDISKVOLUME1')
    self.assertEqual(event.volume_serial_numbers[0], 0xac036525)

    expected_message = (
        u'Prefetch [PING.EXE] was executed - run count 14 path: '
        u'\\WINDOWS\\SYSTEM32\\PING.EXE '
        u'hash: 0xB29F6629 '
        u'volume: 1 [serial number: 0xAC036525, '
        u'device path: \\DEVICE\\HARDDISKVOLUME1]')

    expected_message_short = u'PING.EXE was run 14 time(s)'

    self._TestGetMessageStrings(event, expected_message, expected_message_short)

    # The volume creation event.
    event = storage_writer.events[0]

    self.assertEqual(event.data_type, u'windows:volume:creation')

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2010-11-10 17:37:26.484375')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc, eventdata.EventTimestamp.CREATION_TIME)

  @shared_test_lib.skipUnlessHasTestFile([u'WUAUCLT.EXE-830BCC14.pf'])
  def testParse23MultiVolume(self):
    """Tests the Parse function on a multi volume version 23 Prefetch file."""
    parser_object = winprefetch.WinPrefetchParser()
    storage_writer = self._ParseFile(
        [u'WUAUCLT.EXE-830BCC14.pf'], parser_object)

    self.assertEqual(len(storage_writer.events), 6)

    # The prefetch last run event.
    event = storage_writer.events[5]

    self.assertEqual(event.data_type, u'windows:prefetch:execution')
    self.assertEqual(event.version, 23)

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2012-03-15 21:17:39.807996')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc, eventdata.EventTimestamp.LAST_RUNTIME)

    self.assertEqual(event.executable, u'WUAUCLT.EXE')
    self.assertEqual(event.prefetch_hash, 0x830bcc14)
    self.assertEqual(event.path, u'\\WINDOWS\\SYSTEM32\\WUAUCLT.EXE')
    self.assertEqual(event.run_count, 25)
    self.assertEqual(event.volume_device_paths[0], u'\\DEVICE\\HARDDISKVOLUME1')
    self.assertEqual(event.volume_serial_numbers[0], 0xac036525)

    expected_message = (
        u'Prefetch [WUAUCLT.EXE] was executed - run count 25 path: '
        u'\\WINDOWS\\SYSTEM32\\WUAUCLT.EXE '
        u'hash: 0x830BCC14 '
        u'volume: 1 [serial number: 0xAC036525, '
        u'device path: \\DEVICE\\HARDDISKVOLUME1], '
        u'volume: 2 [serial number: 0xAC036525, '
        u'device path: \\DEVICE\\HARDDISKVOLUMESHADOWCOPY2], '
        u'volume: 3 [serial number: 0xAC036525, '
        u'device path: \\DEVICE\\HARDDISKVOLUMESHADOWCOPY4], '
        u'volume: 4 [serial number: 0xAC036525, '
        u'device path: \\DEVICE\\HARDDISKVOLUMESHADOWCOPY7], '
        u'volume: 5 [serial number: 0xAC036525, '
        u'device path: \\DEVICE\\HARDDISKVOLUMESHADOWCOPY8]')

    expected_message_short = u'WUAUCLT.EXE was run 25 time(s)'

    self._TestGetMessageStrings(event, expected_message, expected_message_short)

    # The volume creation event.
    event = storage_writer.events[0]

    self.assertEqual(event.data_type, u'windows:volume:creation')

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2010-11-10 17:37:26.484375')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc, eventdata.EventTimestamp.CREATION_TIME)

    expected_message = (
        u'\\DEVICE\\HARDDISKVOLUME1 '
        u'Serial number: 0xAC036525 '
        u'Origin: WUAUCLT.EXE-830BCC14.pf')

    expected_message_short = (
        u'\\DEVICE\\HARDDISKVOLUME1 '
        u'Origin: WUAUCLT.EXE-830BCC14.pf')

    self._TestGetMessageStrings(event, expected_message, expected_message_short)

  @shared_test_lib.skipUnlessHasTestFile([u'TASKHOST.EXE-3AE259FC.pf'])
  def testParse26(self):
    """Tests the Parse function on a version 26 Prefetch file."""
    parser_object = winprefetch.WinPrefetchParser()
    storage_writer = self._ParseFile(
        [u'TASKHOST.EXE-3AE259FC.pf'], parser_object)

    self.assertEqual(len(storage_writer.events), 5)

    # The prefetch last run event.
    event = storage_writer.events[1]

    self.assertEqual(event.data_type, u'windows:prefetch:execution')
    self.assertEqual(event.version, 26)

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2013-10-04 15:40:09.037833')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc, eventdata.EventTimestamp.LAST_RUNTIME)
    self.assertEqual(event.executable, u'TASKHOST.EXE')
    self.assertEqual(event.prefetch_hash, 0x3ae259fc)

    # The prefetch previous last run event.
    event = storage_writer.events[2]

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2013-10-04 15:28:09.010356')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc,
        u'Previous {0:s}'.format(eventdata.EventTimestamp.LAST_RUNTIME))

    expected_mapped_files = [
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\NTDLL.DLL '
         u'[MFT entry: 46299, sequence: 1]'),
        u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\TASKHOST.EXE',
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\KERNEL32.DLL '
         u'[MFT entry: 45747, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\KERNELBASE.DLL '
         u'[MFT entry: 45734, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\LOCALE.NLS '
         u'[MFT entry: 45777, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\MSVCRT.DLL '
         u'[MFT entry: 46033, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\RPCRT4.DLL '
         u'[MFT entry: 46668, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\COMBASE.DLL '
         u'[MFT entry: 44616, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\OLEAUT32.DLL '
         u'[MFT entry: 46309, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\OLE32.DLL '
         u'[MFT entry: 46348, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\RPCSS.DLL '
         u'[MFT entry: 46654, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\KERNEL.APPCORE.DLL '
         u'[MFT entry: 45698, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\CRYPTBASE.DLL '
         u'[MFT entry: 44560, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\BCRYPTPRIMITIVES.DLL '
         u'[MFT entry: 44355, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\USER32.DLL '
         u'[MFT entry: 47130, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\GDI32.DLL '
         u'[MFT entry: 45344, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\EN-US\\'
         u'TASKHOST.EXE.MUI'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\SECHOST.DLL '
         u'[MFT entry: 46699, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\CLBCATQ.DLL '
         u'[MFT entry: 44511, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\RACENGN.DLL '
         u'[MFT entry: 46549, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\NTMARTA.DLL '
         u'[MFT entry: 46262, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\WEVTAPI.DLL '
         u'[MFT entry: 47223, sequence: 1]'),
        u'\\DEVICE\\HARDDISKVOLUME2\\$MFT',
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\SQMAPI.DLL '
         u'[MFT entry: 46832, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\AEPIC.DLL '
         u'[MFT entry: 43991, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\WINTRUST.DLL '
         u'[MFT entry: 47372, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\SLWGA.DLL '
         u'[MFT entry: 46762, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\DXGI.DLL '
         u'[MFT entry: 44935, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\ESENT.DLL '
         u'[MFT entry: 45256, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\WMICLNT.DLL '
         u'[MFT entry: 47413, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\ADVAPI32.DLL '
         u'[MFT entry: 43994, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\SFC_OS.DLL '
         u'[MFT entry: 46729, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\VERSION.DLL '
         u'[MFT entry: 47120, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\CRYPT32.DLL '
         u'[MFT entry: 44645, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\MSASN1.DLL '
         u'[MFT entry: 45909, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\WTSAPI32.DLL '
         u'[MFT entry: 47527, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\SPPC.DLL '
         u'[MFT entry: 46803, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\POWRPROF.DLL '
         u'[MFT entry: 46413, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\PROFAPI.DLL '
         u'[MFT entry: 46441, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\PROGRAMDATA\\MICROSOFT\\RAC\\STATEDATA\\'
         u'RACMETADATA.DAT [MFT entry: 39345, sequence: 2]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\GLOBALIZATION\\SORTING\\'
         u'SORTDEFAULT.NLS [MFT entry: 37452, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\RACRULES.XML '
         u'[MFT entry: 46509, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\TASKSCHD.DLL '
         u'[MFT entry: 47043, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\SSPICLI.DLL '
         u'[MFT entry: 46856, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\XMLLITE.DLL '
         u'[MFT entry: 47569, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\PROGRAMDATA\\MICROSOFT\\RAC\\STATEDATA\\'
         u'RACWMIEVENTDATA.DAT [MFT entry: 23870, sequence: 3]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\PROGRAMDATA\\MICROSOFT\\RAC\\STATEDATA\\'
         u'RACWMIDATABOOKMARKS.DAT [MFT entry: 23871, sequence: 2]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\TPMTASKS.DLL '
         u'[MFT entry: 47003, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\NCRYPT.DLL '
         u'[MFT entry: 46073, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\BCRYPT.DLL '
         u'[MFT entry: 44346, sequence: 1]'),
        (u'\\DEVICE\\HARDDISKVOLUME2\\WINDOWS\\SYSTEM32\\NTASN1.DLL '
         u'[MFT entry: 46261, sequence: 1]')]

    self.assertEqual(event.mapped_files, expected_mapped_files)

    # The volume creation event.
    event = storage_writer.events[0]

    self.assertEqual(event.data_type, u'windows:volume:creation')

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2013-10-04 15:57:26.146547')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc, eventdata.EventTimestamp.CREATION_TIME)

  @shared_test_lib.skipUnlessHasTestFile([u'BYTECODEGENERATOR.EXE-C1E9BCE6.pf'])
  def testParse30Compressed(self):
    """Tests the Parse function on a compressed version 30 Prefetch file."""
    parser_object = winprefetch.WinPrefetchParser()
    storage_writer = self._ParseFile(
        [u'BYTECODEGENERATOR.EXE-C1E9BCE6.pf'], parser_object)

    self.assertEqual(len(storage_writer.events), 8)

    # The prefetch last run event.
    event = storage_writer.events[1]

    self.assertEqual(event.data_type, u'windows:prefetch:execution')
    self.assertEqual(event.version, 30)

    self.assertEqual(event.data_type, u'windows:prefetch:execution')

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2015-05-14 22:11:58.091134')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc, eventdata.EventTimestamp.LAST_RUNTIME)
    self.assertEqual(event.executable, u'BYTECODEGENERATOR.EXE')
    self.assertEqual(event.prefetch_hash, 0xc1e9bce6)

    # The prefetch previous last run event.
    event = storage_writer.events[2]

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2015-05-14 22:11:55.357652')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc,
        u'Previous {0:s}'.format(eventdata.EventTimestamp.LAST_RUNTIME))

    self.assertEqual(len(event.mapped_files), 1085)

    # The volume creation event.
    event = storage_writer.events[0]

    self.assertEqual(event.data_type, u'windows:volume:creation')

    expected_timestamp = timelib.Timestamp.CopyFromString(
        u'2015-05-15 06:54:55.139294')
    self.assertEqual(event.timestamp, expected_timestamp)
    self.assertEqual(
        event.timestamp_desc, eventdata.EventTimestamp.CREATION_TIME)

if __name__ == u'__main__':
  unittest.main()


text:
using content::BrowserContext;
using content::BrowserThread;

namespace extensions {

ShellExtensionSystem::ShellExtensionSystem(BrowserContext* browser_context)
    : browser_context_(browser_context),
      store_factory_(new ValueStoreFactoryImpl(browser_context->GetPath())) {}

ShellExtensionSystem::~ShellExtensionSystem() = default;

const Extension* ShellExtensionSystem::LoadExtension(
    const base::FilePath& extension_dir) {
  return extension_loader_->LoadExtension(extension_dir);
}

const Extension* ShellExtensionSystem::LoadApp(const base::FilePath& app_dir) {
  return LoadExtension(app_dir);
}

void ShellExtensionSystem::FinishInitialization() {
  // Inform the rest of the extensions system to start.
  ready_.Signal();
  content::NotificationService::current()->Notify(
      NOTIFICATION_EXTENSIONS_READY_DEPRECATED,
      content::Source<BrowserContext>(browser_context_),
      content::NotificationService::NoDetails());
}

void ShellExtensionSystem::LaunchApp(const ExtensionId& extension_id) {
  // Send the onLaunched event.
  DCHECK(ExtensionRegistry::Get(browser_context_)
             ->enabled_extensions()
             .Contains(extension_id));
  const Extension* extension = ExtensionRegistry::Get(browser_context_)
                                   ->enabled_extensions()
                                   .GetByID(extension_id);
  apps::LaunchPlatformApp(browser_context_, extension,
                          AppLaunchSource::kSourceUntracked);
}

void ShellExtensionSystem::ReloadExtension(const ExtensionId& extension_id) {
  extension_loader_->ReloadExtension(extension_id);
}

void ShellExtensionSystem::Shutdown() {
  extension_loader_.reset();
}

void ShellExtensionSystem::InitForRegularProfile(bool extensions_enabled) {
  service_worker_manager_ =
      std::make_unique<ServiceWorkerManager>(browser_context_);
  runtime_data_ =
      std::make_unique<RuntimeData>(ExtensionRegistry::Get(browser_context_));
  quota_service_ = std::make_unique<QuotaService>();
  app_sorting_ = std::make_unique<NullAppSorting>();
  extension_loader_ = std::make_unique<ShellExtensionLoader>(browser_context_);
}

ExtensionService* ShellExtensionSystem::extension_service() {
  return nullptr;
}

RuntimeData* ShellExtensionSystem::runtime_data() {
  return runtime_data_.get();
}

ManagementPolicy* ShellExtensionSystem::management_policy() {
  return nullptr;
}

ServiceWorkerManager* ShellExtensionSystem::service_worker_manager() {
  return service_worker_manager_.get();
}

SharedUserScriptMaster* ShellExtensionSystem::shared_user_script_master() {
  return nullptr;
}

StateStore* ShellExtensionSystem::state_store() {
  return nullptr;
}

StateStore* ShellExtensionSystem::rules_store() {
  return nullptr;
}

scoped_refptr<ValueStoreFactory> ShellExtensionSystem::store_factory() {
  return store_factory_;
}

InfoMap* ShellExtensionSystem::info_map() {
  if (!info_map_.get())
    info_map_ = new InfoMap;
  return info_map_.get();
}

QuotaService* ShellExtensionSystem::quota_service() {
  return quota_service_.get();
}

AppSorting* ShellExtensionSystem::app_sorting() {
  return app_sorting_.get();
}

void ShellExtensionSystem::RegisterExtensionWithRequestContexts(
    const Extension* extension,
    base::OnceClosure callback) {
  base::PostTaskAndReply(FROM_HERE, {BrowserThread::IO},
                         base::BindOnce(&InfoMap::AddExtension, info_map(),
                                        base::RetainedRef(extension),
                                        base::Time::Now(), false, false),
                         std::move(callback));
}

void ShellExtensionSystem::UnregisterExtensionWithRequestContexts(
    const std::string& extension_id,
    const UnloadedExtensionReason reason) {}

const base::OneShotEvent& ShellExtensionSystem::ready() const {
  return ready_;
}

ContentVerifier* ShellExtensionSystem::content_verifier() {
  return nullptr;
}

std::unique_ptr<ExtensionSet> ShellExtensionSystem::GetDependentExtensions(
    const Extension* extension) {
  return std::make_unique<ExtensionSet>();
}

void ShellExtensionSystem::InstallUpdate(
    const std::string& extension_id,
    const std::string& public_key,
    const base::FilePath& temp_dir,
    bool install_immediately,
    InstallUpdateCallback install_update_callback) {
  NOTREACHED();
  base::DeleteFileRecursively(temp_dir);
}

void ShellExtensionSystem::PerformActionBasedOnOmahaAttributes(
    const std::string& extension_id,
    const base::Value& attributes) {
  NOTREACHED();
}

bool ShellExtensionSystem::FinishDelayedInstallationIfReady(
    const std::string& extension_id,
    bool install_immediately) {
  NOTREACHED();
  return false;
}

void ShellExtensionSystem::OnExtensionRegisteredWithRequestContexts(
    scoped_refptr<Extension> extension) {
  ExtensionRegistry* registry = ExtensionRegistry::Get(browser_context_);
  registry->AddReady(extension);
  registry->TriggerOnReady(extension.get());
}

}  // namespace extensions


text:
#define EIGEN_USE_THREADS

#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#endif  // GOOGLE_CUDA

#include "tensorflow_addons/custom_ops/layers/cc/kernels/correlation_cost_op.h"

#include "tensorflow/core/framework/bounds_check.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/util/tensor_format.h"
#include "tensorflow/core/util/work_sharder.h"

namespace tensorflow {
namespace addons {

typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;

namespace functor {

template <typename Dtype>
struct CorrelationCostFunctor<CPUDevice, Dtype> {
  Status operator()(OpKernelContext* context, const Tensor& input_a_t,
                    const Tensor& input_b_t, Tensor* output_t,
                    /* params */
                    int kernel_size, int max_displacement, int stride_1,
                    int stride_2, int pad, TensorFormat data_format) {
    const int32 oN = GetTensorDim(*output_t, FORMAT_NCHW, 'N');
    // const int32 oC = GetTensorDim(*output_t, FORMAT_NCHW, 'C');
    const int32 oH = GetTensorDim(*output_t, FORMAT_NCHW, 'H');
    const int32 oW = GetTensorDim(*output_t, FORMAT_NCHW, 'W');
    const int32 iH = GetTensorDim(input_a_t, data_format, 'H');
    const int32 iW = GetTensorDim(input_a_t, data_format, 'W');
    const int32 iC = GetTensorDim(input_a_t, data_format, 'C');

    const int K = kernel_size * kernel_size * iC;

    const auto input_a = input_a_t.tensor<Dtype, 4>();
    const auto input_b = input_b_t.tensor<Dtype, 4>();
    auto output = output_t->tensor<Dtype, 4>();
    output.setZero();

    const int kernel_rad = (kernel_size - 1) / 2;
    const int displacement_rad = max_displacement / stride_2;
    const int displacement_size = 2 * displacement_rad + 1;

    const bool is_NCHW = (data_format == FORMAT_NCHW);
    // estimate operations per pixel
    const int64 cost_per_pixel =
        iC * ((2 * displacement_rad + 1) * (2 * displacement_rad + 1)) *
        ((2 * kernel_rad + 1) * (2 * kernel_rad + 1)) *
        (Eigen::TensorOpCost::MulCost<Dtype>() +
         Eigen::TensorOpCost::AddCost<Dtype>());

    const auto work = [&](Eigen::Index start, Eigen::Index end) -> void {
      for (Eigen::Index id = start; id < end; ++id) {
        const int n = id / (oH * oW);
        const int h = (id / oW) % oH;
        const int w = id % oW;
        const int h1 = (h - pad) * stride_1 + max_displacement + kernel_rad;
        const int w1 = (w - pad) * stride_1 + max_displacement + kernel_rad;
        for (int tj = -displacement_rad; tj <= displacement_rad; ++tj) {
          for (int ti = -displacement_rad; ti <= displacement_rad; ++ti) {
            const int tc = (tj + displacement_rad) * displacement_size +
                           (ti + displacement_rad);

            const int w2 = w1 + ti * stride_2;
            const int h2 = h1 + tj * stride_2;

            for (int j = -kernel_rad; j <= kernel_rad; ++j) {
              // out-of-bound test
              if (!FastBoundsCheck(h1 + j, iH) || !FastBoundsCheck(h2 + j, iH))
                continue;
              for (int i = -kernel_rad; i <= kernel_rad; ++i) {
                if (!FastBoundsCheck(w1 + i, iW) ||
                    !FastBoundsCheck(w2 + i, iW))
                  continue;
                for (int c = 0; c < iC; ++c) {
                  // eq. (1) in FlowNet: Learning Optical Flow with
                  // Convolutional Networks
                  if (is_NCHW) {
                    output(n, tc, h, w) += input_a(n, c, h1 + j, w1 + i) *
                                           input_b(n, c, h2 + j, w2 + i);
                  } else {
                    output(n, tc, h, w) += input_a(n, h1 + j, w1 + i, c) *
                                           input_b(n, h2 + j, w2 + i, c);
                  }
                }
              }
            }
            output(n, tc, h, w) /= K;
          }
        }
      }
    };
    auto thread_pool =
        context->device()->tensorflow_cpu_worker_threads()->workers;
    thread_pool->ParallelFor(oN * oH * oW, cost_per_pixel, work);
    return Status();
  }
};

template <typename Dtype>
struct CorrelationCostGradFunctor<CPUDevice, Dtype> {
  Status operator()(OpKernelContext* context, const Tensor& input_a_t,
                    const Tensor& input_b_t, const Tensor& topdiff_t,
                    Tensor* output_a_gradient_t, Tensor* output_b_gradient_t,
                    /* params */
                    int kernel_size, int max_displacement, int stride_1,
                    int stride_2, int pad, TensorFormat data_format) {
    const int32 iN = GetTensorDim(input_a_t, data_format, 'N');
    const int32 iC = GetTensorDim(input_a_t, data_format, 'C');
    const int32 iH = GetTensorDim(input_a_t, data_format, 'H');
    const int32 iW = GetTensorDim(input_a_t, data_format, 'W');

    // topdiff is NCHW
    // const int32 oC = GetTensorDim(topdiff_t, FORMAT_NCHW, 'C');
    const int32 oH = GetTensorDim(topdiff_t, FORMAT_NCHW, 'H');
    const int32 oW = GetTensorDim(topdiff_t, FORMAT_NCHW, 'W');

    const auto topdiff = topdiff_t.tensor<Dtype, 4>();
    const auto input_a = input_a_t.tensor<Dtype, 4>();
    const auto input_b = input_b_t.tensor<Dtype, 4>();
    auto output_a_gradient = output_a_gradient_t->tensor<Dtype, 4>();
    auto output_b_gradient = output_b_gradient_t->tensor<Dtype, 4>();
    output_a_gradient.setZero();
    output_b_gradient.setZero();

    const int kernel_rad = (kernel_size - 1) / 2;
    const int displacement_rad = max_displacement / stride_2;
    const int displacement_size = 2 * displacement_rad + 1;
    const int K = kernel_size * kernel_size * iC;

    const bool is_NCHW = (data_format == FORMAT_NCHW);
    // estimate operations per pixel
    const int64 cost_per_pixel =
        2 * iC * ((2 * displacement_rad + 1) * (2 * displacement_rad + 1)) *
        ((2 * kernel_rad + 1) * (2 * kernel_rad + 1)) *
        (Eigen::TensorOpCost::MulCost<Dtype>() +
         Eigen::TensorOpCost::AddCost<Dtype>());

    const auto work = [&](Eigen::Index start, Eigen::Index end) -> void {
      for (Eigen::Index id = start; id < end; ++id) {
        const int n = id / (oH * oW);
        const int h = (id / oW) % oH;
        const int w = id % oW;
        const int h1 = (h - pad) * stride_1 + max_displacement + kernel_rad;
        const int w1 = (w - pad) * stride_1 + max_displacement + kernel_rad;

        for (int tj = -displacement_rad; tj <= displacement_rad; ++tj) {
          for (int ti = -displacement_rad; ti <= displacement_rad; ++ti) {
            const int tc = (tj + displacement_rad) * displacement_size +
                           (ti + displacement_rad);

            const int w2 = w1 + ti * stride_2;
            const int h2 = h1 + tj * stride_2;

            for (int j = -kernel_rad; j <= kernel_rad; ++j) {
              // out-of-bound test
              if (!FastBoundsCheck(h1 + j, iH) || !FastBoundsCheck(h2 + j, iH))
                continue;
              for (int i = -kernel_rad; i <= kernel_rad; ++i) {
                if (!FastBoundsCheck(w1 + i, iW) ||
                    !FastBoundsCheck(w2 + i, iW))
                  continue;
                for (int c = 0; c < iC; ++c) {
                  // eq. (1) in FlowNet: Learning Optical Flow with
                  // Convolutional Networks
                  if (is_NCHW) {
                    output_a_gradient(n, c, h1 + j, w1 + i) +=
                        topdiff(n, tc, h, w) * input_b(n, c, h2 + j, w2 + i) /
                        K;
                    output_b_gradient(n, c, h2 + j, w2 + i) +=
                        topdiff(n, tc, h, w) * input_a(n, c, h1 + j, w1 + i) /
                        K;
                  } else {
                    output_a_gradient(n, h1 + j, w1 + i, c) +=
                        topdiff(n, tc, h, w) * input_b(n, h2 + j, w2 + i, c) /
                        K;
                    output_b_gradient(n, h2 + j, w2 + i, c) +=
                        topdiff(n, tc, h, w) * input_a(n, h1 + j, w1 + i, c) /
                        K;
                  }
                }
              }
            }
          }
        }
      }
    };

    auto thread_pool =
        context->device()->tensorflow_cpu_worker_threads()->workers;
    thread_pool->ParallelFor(iN * oH * oW, cost_per_pixel, work);

    return Status();
  }
};

}  // end namespace functor

template <typename Device, typename T>
class CorrelationCostOp : public OpKernel {
 public:
  explicit CorrelationCostOp(OpKernelConstruction* context)
      : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("kernel_size", &kernel_size));
    OP_REQUIRES_OK(context,
                   context->GetAttr("max_displacement", &max_displacement));
    OP_REQUIRES_OK(context, context->GetAttr("stride_1", &stride_1));
    OP_REQUIRES_OK(context, context->GetAttr("stride_2", &stride_2));
    OP_REQUIRES_OK(context, context->GetAttr("pad", &pad));
    string data_format;
    OP_REQUIRES_OK(context, context->GetAttr("data_format", &data_format));
    OP_REQUIRES(context, FormatFromString(data_format, &data_format_),
                errors::InvalidArgument("Invalid data format"));
    OP_REQUIRES(context, kernel_size % 2 != 0,
                errors::InvalidArgument("kernel_size must be odd"));
  }

  void Compute(OpKernelContext* context) override {
    const Tensor& input_a_t = context->input(0);
    const Tensor& input_b_t = context->input(1);

    // we didn't check the batch-dimension during "SetShapeFn"
    OP_REQUIRES(context, input_a_t.shape() == input_b_t.shape(),
                errors::InvalidArgument("Input shapes have to be the same"));

    const int32 N = GetTensorDim(input_a_t, data_format_, 'N');
    const int32 H = GetTensorDim(input_a_t, data_format_, 'H');
    const int32 W = GetTensorDim(input_a_t, data_format_, 'W');

    // output channels are d**2 where, d = 2r + 1
    const int32 r = max_displacement / stride_2;
    const int32 d = 2 * r + 1;
    const int32 border = max_displacement + (kernel_size - 1) / 2;

    const int32 Cout = d * d;
    const int32 Hout =
        static_cast<int>(ceil(static_cast<float>(((H + 2 * pad) - border * 2)) /
                              static_cast<float>(stride_1)));
    const int32 Wout =
        static_cast<int>(ceil(static_cast<float>(((W + 2 * pad) - border * 2)) /
                              static_cast<float>(stride_1)));

    OP_REQUIRES(context, Hout >= 1,
                errors::InvalidArgument(
                    "Neighborhood and kernel don't fit in input height."));
    OP_REQUIRES(context, Wout >= 1,
                errors::InvalidArgument(
                    "Neighborhood and kernel don't fit in input width."));

    Tensor* output_t;
    OP_REQUIRES_OK(
        context, context->allocate_output(0, TensorShape({N, Cout, Hout, Wout}),
                                          &output_t));

    functor::CorrelationCostFunctor<Device, T> correlationCostFunc;
    Status s = correlationCostFunc(context, input_a_t, input_b_t, output_t,
                                   /* params */
                                   kernel_size, max_displacement, stride_1,
                                   stride_2, pad, data_format_);

    OP_REQUIRES_OK(context, s);
  }

 private:
  int kernel_size;
  int max_displacement;
  int stride_1;
  int stride_2;
  int pad;
  TensorFormat data_format_;
};

template <typename Device, typename T>
class CorrelationCostGradOp : public OpKernel {
 public:
  explicit CorrelationCostGradOp(OpKernelConstruction* context)
      : OpKernel(context) {
    OP_REQUIRES_OK(context, context->GetAttr("kernel_size", &kernel_size));
    OP_REQUIRES_OK(context,
                   context->GetAttr("max_displacement", &max_displacement));
    OP_REQUIRES_OK(context, context->GetAttr("stride_1", &stride_1));
    OP_REQUIRES_OK(context, context->GetAttr("stride_2", &stride_2));
    OP_REQUIRES_OK(context, context->GetAttr("pad", &pad));
    string data_format;
    OP_REQUIRES_OK(context, context->GetAttr("data_format", &data_format));
    OP_REQUIRES(context, FormatFromString(data_format, &data_format_),
                errors::InvalidArgument("Invalid data format"));
    OP_REQUIRES(context, kernel_size % 2 != 0,
                errors::InvalidArgument("kernel_size must be odd"));
  }

  void Compute(OpKernelContext* context) override {
    const Tensor& input_a_t = context->input(0);
    const Tensor& input_b_t = context->input(1);
    const Tensor& topdiff_t = context->input(2);

    OP_REQUIRES(context, input_a_t.shape() == input_b_t.shape(),
                errors::InvalidArgument("Input shapes have to be the same"));

    // Allocate the memory for the bottom diffs
    Tensor* output_a_gradient_t;
    OP_REQUIRES_OK(context, context->allocate_output(0, input_a_t.shape(),
                                                     &output_a_gradient_t));
    Tensor* output_b_gradient_t;
    OP_REQUIRES_OK(context, context->allocate_output(1, input_b_t.shape(),
                                                     &output_b_gradient_t));

    functor::CorrelationCostGradFunctor<Device, T> correlationCostGrad;
    Status s = correlationCostGrad(context, input_a_t, input_b_t, topdiff_t,
                                   output_a_gradient_t, output_b_gradient_t,
                                   /* params */
                                   kernel_size, max_displacement, stride_1,
                                   stride_2, pad, data_format_);

    OP_REQUIRES_OK(context, s);
  }

 private:
  int kernel_size;
  int max_displacement;
  int stride_1;
  int stride_2;
  int pad;
  TensorFormat data_format_;
};

// Register the CPU kernels.
#define REGISTER_CORRELATIONCOST_OP_CPU(T)                   \
  REGISTER_KERNEL_BUILDER(Name("Addons>CorrelationCost")     \
                              .Device(DEVICE_CPU)            \
                              .TypeConstraint<T>("T"),       \
                          CorrelationCostOp<CPUDevice, T>)   \
  REGISTER_KERNEL_BUILDER(Name("Addons>CorrelationCostGrad") \
                              .Device(DEVICE_CPU)            \
                              .TypeConstraint<T>("T"),       \
                          CorrelationCostGradOp<CPUDevice, T>)

TF_CALL_float(REGISTER_CORRELATIONCOST_OP_CPU);
#undef REGISTER_CORRELATIONCOST_OP_CPU

// Register the GPU kernels.
#if GOOGLE_CUDA

#define REGISTER_CORRELATIONCOST_OP_GPU(T)                   \
  REGISTER_KERNEL_BUILDER(Name("Addons>CorrelationCost")     \
                              .Device(DEVICE_GPU)            \
                              .TypeConstraint<T>("T"),       \
                          CorrelationCostOp<GPUDevice, T>)   \
  REGISTER_KERNEL_BUILDER(Name("Addons>CorrelationCostGrad") \
                              .Device(DEVICE_GPU)            \
                              .TypeConstraint<T>("T"),       \
                          CorrelationCostGradOp<GPUDevice, T>)

TF_CALL_float(REGISTER_CORRELATIONCOST_OP_GPU);
#undef REGISTER_CORRELATIONCOST_OP_GPU

#endif  // GOOGLE_CUDA

}  // namespace addons
}  // namespace tensorflow


text:
(function ($) {

  $.listDraggable = function (element, options) {

    // private property
    //
    // plugin's default options
    //
    var defaults = {
      multiSelect: false,
      trash: false,
      removeIcon: true,
      searchable: false,
      groups: [
        {class: 'col-md-3', lists: ['original']},
        {class: 'col-md-9', lists: ['default']}
      ],
      lists: [
        {name: 'original', label: 'Original', class: 'col-md-12'}
      ],
      renderList: null,
      renderItem: null,
      displayResume: true,
      displayGroup: false,
      displayShortcuts: false,
      hideSubList: false,
      trashList: 'none',
      language: {
        dataMissing: 'data option not specified',
        dataEmpty: 'data option is empty',
        printDetails: 'Display details',
        multiSelectDifferentList: 'Multi-select only available on the same list'
      }
    };

    // to avoid confusions, use "plugin" to reference the
    // current instance of the object
    var plugin = this;
    var listElements = [], dataTransfer = [];
    plugin.settings = {};

    var $element = $(element), // reference to the jQuery version of DOM element
      element = element;    // reference to the actual DOM element

    // Constructor
    //
    // Constructor
    //
    plugin.init = function () {

      // Merge settings with defaults
      plugin.settings = $.extend(true, {}, defaults, options);

      if (checkRequirements()) {
        initList();
        refreshList();

        if (plugin.settings.hideSubList == true) {
          var $lists = $element.find('div[data-list]'),
            $checkbox = $(
              '
' +
                '' +
                '<input type="checkbox">' + plugin.settings.language.printDetails +
                '' +
                '
');

          $lists.not('[data-list=original]').hide();
          $lists.not('[data-list!=original]').prepend($checkbox);
        }

        bindEvents();
      }
    }
    ;

    // public method
    //
    // Refresh listing manually
    //
    plugin.refresh = function () {
      refreshList();
    };

    // public method
    //
    //
    //
    plugin.getData = function () {
      return plugin.settings.data;
    };

    plugin.getFilteredData = function () {
      var filtered = {};
      $.each(plugin.settings.lists, function () {
        filtered[this.name] = [];
      });
      filtered['none'] = [];

      $.each(plugin.settings.data, function () {
        var group = this;
        $.each(group.items, function () {
          var item = this;
          if (filtered.hasOwnProperty(item.list)) {
            filtered[item.list].push(item.id);
          }
        });
      });

      return filtered;
    };
    // private method
    //
    // Change a string to an human readable string
    //
    var humanize = function (string) {

      string = string.replace(/([0-9])([a-zA-Z])/g, '$1 $2');
      string = string.replace(/([a-zA-Z])([0-9])/g, '$1 $2');
      string = string.replace(/([a-z])([A-Z])/g, '$1 $2');
      string = string.replace(/([A-Z])([a-z])/g, '$1 $2');

      return string;
    };

    // private method
    //
    // Capitalize string
    //
    var capitalize = function (string) {

      return string[0].toUpperCase() + string.slice(1);

    };

    // private method
    //
    // Check requirements
    //
    var checkRequirements = function () {
      var result = true;

      if (plugin.settings.renderList == null) {
        plugin.settings.renderList = _renderList;
      }
      if (plugin.settings.renderItem == null) {
        plugin.settings.renderItem = _renderItem;
      }
      if (!plugin.settings.data) {
        $element.append('
' + plugin.settings.language.dataMissing + '
');
        result = false;
      }

      if ($.isFunction(plugin.settings.data)) {
        plugin.settings.data = plugin.settings.data();
      }

      if (plugin.settings.data.length < 1) {
        $element.append('
' + plugin.settings.language.dataEmpty + '
');
        result = false;
      }

      if (!plugin.settings.lists || plugin.settings.lists.length < 2) {
        $element.append(
          '
'
            + 'lists option not specified or is empty
'
            + 'lists:[
'
            + '  {name: "mylistname", label: "my list label", class: "span2"}
'
            + ' ,...
'
            + ']'
            + ''
            + '
'
        );
        result = false;
      }

      return result;
    };

    // private method
    //
    // Initialise DOM
    //
    var initList = function () {
      renderGroups();
    };

    // private method
    //
    // refresh list from data
    //
    var refreshList = function () {
      $element.find('ul:not(.trash)').html('');
      var
        $originList = $element.find('div[data-list=original] ul');

      $.each(plugin.settings.data, function (index, group) {
        //create group item
        var groupLi = '
' + group.name + '
',
          risks = [],
          lis = [];

        if (plugin.settings.displayGroup) {
          //append group to all list
          for (var key in listElements) {
            if (listElements.hasOwnProperty(key) && key != 'original') {
              $(listElements[key]).find('ul').append(groupLi);
            }
          }
        }

        //compute items
        $.each(group.items, function (index, item) {
            var itemLi = '
'
                + (
                plugin.settings.removeIcon && item.list != 'none' && item.list != plugin.settings.trashList
                  ? '<button type="button" class="close" data-dismiss="item">×</button>'
                  : ''
                )
                + plugin.settings.renderItem(item)
                + '
',
              list = '';

            if (listElements[item.list]) {
              listElements[item.list].find('ul').append(itemLi);
              list = $('div[data-list=' + item.list + ']').find('.title').text();
              if (!list)
                list = capitalize(item.list);
            }

            if (list != '')
              risks.indexOf(list) < 0 ? risks.push(list) : true;
            lis.push($(itemLi).append('' + list + ''));
          }
        );

        //append all li to originList
        var $groupLi = $(groupLi),
          $risk = $('' + risks.join('/') + '');
        if (plugin.settings.displayGroup) {
          if (plugin.settings.displayResume)
            $groupLi.append($risk);
          $originList.append($groupLi);
        }
        $(lis).each(function () {
          $originList.append(this)
        });
      });

    };

    // private method
    //
    // Bind events (drag, drop, click
    //
    var bindEvents = function () {
      $element
        .on('click', 'input[type=checkbox]', function (e) {
          if ($(this).is(':checked'))
            $element.find('div[data-list]').show();
          else
            $element.find('div[data-list]').not('[data-list=original]').hide();
        })
        .on('keyup', 'input[type=text]', function (e) {
          var $this = $(this), $ul = $(this).next('ul');

          $ul.find('li').each(function () {
            if ($(this).data('name').toLowerCase().indexOf($this.val().toLowerCase()) != -1) {
              $(this).fadeIn('fast');
            } else {
              $(this).fadeOut('fast');
            }
          });
        })
        .on('click', 'button.close', function (e) {
          e.preventDefault();
          e.stopPropagation();
          var $parentLi = $(this).closest('li');
          var itemId = $parentLi.data('id');
          var itemGroup = $parentLi.data('group');
          var group = $.grep(plugin.settings.data, function (group) {
            return group.id == itemGroup
          });
          var item = $.grep(group[0].items, function (item) {
            return item.id == itemId
          });
          item[0].list = plugin.settings.trashList;
          $(this).remove();
          refreshList();
        })
        .on('click', 'li', function (e) {
          if (!plugin.settings.multiSelect)
            return false;
          $ulName = $('li.alert-info[draggable=true]').parents('ul').data('id');

          if ($ulName && $ulName != $(this).parents('ul').data('id')) {
            alert(plugin.settings.language.multiSelectDifferentList);
            return false;
          }
          if ($(this).hasClass('group')) {
            $(this).nextUntil('li.group').toggleClass('alert-info');
          } else {
            $(this).toggleClass('alert-info');
          }
        })
        .on('click', 'button[data-rel=list-choice]', function (e) {
          var $selected = $('li.alert-info[draggable=true]');
          if ($selected.length) {
            $selected.first().trigger('dragstart');
            $('div[data-list=' + $(this).attr('name') + ']').find('ul').trigger('drop');
          }
        })
        .on('dragstart', 'li[draggable=true]', function (e) {
          var $this = $(this), names = [],
          //get multi-select
            selectedNames = $('li.alert-info[draggable=true]').filter(function (a) {
              return $(this).data('id') != $this.data('id');
            }),
            displayNames = [];

          //push selected items on transfer list
          selectedNames.each(function () {
            names.push($(this).data('id'));
            displayNames.push($(this).data('name'));
          });

          $(this).find('span.list').hide();
          if ($(this).hasClass('item')) {
            if (names.indexOf($(this).data('id')) == -1) {
              names.push($(this).data('id'));
              displayNames.push($(this).data('name'));
              dataTransfer["group"] = $(this).data('group');
            }
          }
          else {
            dataTransfer["group"] = $(this).data('id');
            $.each($(this).nextUntil('li.group').filter('li'), function () {
              if (-1 == $.inArray($(this).data('id'), names)) {
                names.push($(this).data('id'));
                displayNames.push($(this).data('name'));
              }
            });
          }

          dataTransfer["item"] = names.join('/');
          dataTransfer["fromlist"] = $(this).closest('ul').data('id');

          if (displayNames.length > 10) {
            displayNames.splice(10);
            displayNames.push('...');
          }
          var draggedItem = $('

').html(displayNames.join('
'));

          if (e.originalEvent) {
            var crt = draggedItem[0].cloneNode(true);
            crt.style.backgroundColor = "#FFFFFF";
            crt.style.border = "1px solid black";
            crt.style.position = "absolute";
            crt.style.top = "0";
            crt.style.right = "-1000px";
            crt.style.padding = "20px";
            document.body.appendChild(crt);

            e.originalEvent.dataTransfer.setDragImage(crt, 0, 0);
            e.originalEvent.dataTransfer.setData('text', '');
          }
        })
        .on('drop', 'ul', function (e) {
          e.preventDefault();
          var toList = $(this).attr('name'),
            itemValue = dataTransfer["item"].split('/'),
            groupValue = dataTransfer["group"] ,
            fromList = dataTransfer["fromlist"];

          if (!(toList == 'originList' || toList == fromList)) {

            var groupResult = $.grep(plugin.settings.data, function (item, index) {
                return item.id == groupValue;
              }),
              itemResult = $.grep(groupResult[0].items, function (item, index) {
                return (itemValue ? $.inArray(String(item.id), itemValue) != -1 : true);
              });

            $.each(itemResult, function () {
              if (toList != 'original')
                this.list = toList.replace('List', '');
              else
                this.list = 'none';
            });
          }
          refreshList();

        })
        .on('dragover', 'ul, button[data-rel=list-choice]', function (e) {
          e.preventDefault();
        })
        .on('drop', 'button[data-rel=list-choice]', function (e) {
          e.preventDefault();
          $('div[data-list=' + $(this).attr('name') + ']').find('ul').trigger('drop');
        });
    };

    var renderGroups = function () {
      $.each(plugin.settings.groups, function () {
        var name = this.lists.join('-');
        var $group = $('

');
        renderLists($group);

        $group.find('div[data-list]').each(function () {
          var $list = $(this), listSetting = $.grep(plugin.settings.lists, function (a, i) {
            return a.name == $list.data('list')
          });

          if (plugin.settings.searchable || (listSetting[0].searchable && listSetting[0].searchable == true)) {
            $list.find('ul').before($('<input placeholder="Search" type="text" name="friend" class="form-control">'));
          }

          if (plugin.settings.displayShortcuts) {
            var
              $shortcut = $('

'), $title = $list.find('.title').addClass('pull-left');

            $.each(plugin.settings.lists, function () {
              if (this.name != $list.data('list') && this.name != 'original')
                $shortcut.append($('<button class="btn btn-default" data-rel="list-choice" name="' + this.name + '">' + this.label + '</button>'))
            });

            $title.wrap('

').after($shortcut);
          }
        });

        $group.appendTo($element);
      });
    };

    var renderLists = function (group) {
      var filtered = $.grep(plugin.settings.lists, function (item) {
        return (group.data('group').indexOf(item.name) >= 0);
      });
      $.each(filtered, function () {
        var $list = $('

');

        if (this.label == undefined)
          this.label = humanize(this.name);

        listElements[this.name] = plugin.settings.renderList(this);

        listElements[this.name].appendTo($list);

        $list.appendTo(group);
      });
    };

    var _renderList = function (list) {
      return $('
'
        + '
' + list.label + '
'
        + '

'
        + '
'
      );
    };

    var _renderItem = function (item) {
      return '' + item.name + '';
    };

    // call the "constructor" method
    plugin.init();

  };

  // add the plugin to the jQuery.fn object
  $.fn.listDraggable = function (options) {

    var args = Array.prototype.slice.call(arguments, 1);

    var returns;

    // iterate through the DOM elements we are attaching the plugin to
    this.each(function () {
      // if plugin has not already been attached to the element

      if (undefined == $(this).data('plugin_listDraggable') || typeof options === 'object') {

        // create a new instance of the plugin
        // pass the DOM element and the user-provided options as arguments
        var plugin = new $.listDraggable(this, options);

        // store a reference to the plugin object
        $(this).data('plugin_listDraggable', plugin);
        console.log("list draggable initialized");

      } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {

        var instance = $(this).data('plugin_listDraggable');

        if (instance instanceof $.listDraggable && typeof instance[options] === 'function') {

          returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
        }

        // Allow instances to be destroyed via the 'destroy' method
        if (options === 'destroy') {
          $(this).data('plugin_listDraggable', null);
        }

      }
    });

    return returns !== undefined ? returns : this;

  };

  // Fix problems with console object when browser debug mode not activated
  if (!window.console) window.console = {log: function () {
  }};

})
  (jQuery);


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.dstadler.jgit</groupId>
  <artifactId>jgit-cookbook</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>jgit-cookbook</name>
  <url>http://maven.apache.org</url>

  <repositories>
    <repository>
      <id>jgit-repository</id>
      <url>https://repo.eclipse.org/content/groups/releases/</url>
    </repository>
  </repositories>

  <!-- Core Library -->
  <dependencies>
    <dependency>
      <groupId>org.eclipse.jgit</groupId>
      <artifactId>org.eclipse.jgit</artifactId>
      <version>4.6.0.201612231935-r</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.jgit</groupId>
      <artifactId>org.eclipse.jgit.archive</artifactId>
      <version>4.6.0.201612231935-r</version>
    </dependency>

	<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>2.5</version>
	</dependency>
	<dependency>
		<groupId>org.slf4j</groupId>
		<artifactId>slf4j-simple</artifactId>
		<version>1.7.21</version>
	</dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.2</version>
        <configuration>
          <source>1.7</source>
          <target>1.7</target>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using AutoRest.Core.ClientModel;

namespace AutoRest.AzureResourceSchema
{
    /// <summary>
    /// The ResourceSchemaParser class is responsible for converting a ServiceClient object into a
    /// ResourceSchemaModel.
    /// </summary>
    public static class ResourceSchemaParser
    {
        private const string resourceMethodPrefix = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/";

        /// <summary>
        /// Parse a ResourceSchemaModel from the provided ServiceClient.
        /// </summary>
        /// <param name="serviceClient"></param>
        /// <returns></returns>
        public static IDictionary<string, ResourceSchema> Parse(ServiceClient serviceClient)
        {
            if (serviceClient == null)
            {
                throw new ArgumentNullException(nameof(serviceClient));
            }

            string apiVersion = serviceClient.ApiVersion;
            if (string.IsNullOrWhiteSpace(apiVersion))
            {
                throw new ArgumentException("No API version is provided in the swagger document.");
            }

            Dictionary<string, ResourceSchema> resourceSchemas = new Dictionary<string, ResourceSchema>();

            foreach (Method method in serviceClient.Methods)
            {
                if (method.HttpMethod != HttpMethod.Put ||
                    method.ReturnType.Body == null ||
                    !(method.ReturnType.Body is CompositeType) ||
                    string.IsNullOrWhiteSpace(method.Url) ||
                    !method.Url.StartsWith(resourceMethodPrefix, StringComparison.OrdinalIgnoreCase) ||
                    !method.Url.EndsWith("}", StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                string afterPrefix = method.Url.Substring(resourceMethodPrefix.Length);
                int forwardSlashIndexAfterProvider = afterPrefix.IndexOf('/');
                string resourceProvider = afterPrefix.Substring(0, forwardSlashIndexAfterProvider);

                if (IsPathVariable(resourceProvider))
                {
                    // If the resourceProvider is a path variable, such as {someValue}, then this
                    // is not a create resource method. Skip it.
                    continue;
                }

                ResourceSchema resourceSchema;
                if (!resourceSchemas.ContainsKey(resourceProvider))
                {
                    resourceSchema = new ResourceSchema();
                    resourceSchema.Id = string.Format(CultureInfo.InvariantCulture, "http://schema.management.azure.com/schemas/{0}/{1}.json#", apiVersion, resourceProvider);
                    resourceSchema.Title = resourceProvider;
                    resourceSchema.Description = resourceProvider.Replace('.', ' ') + " Resource Types";
                    resourceSchema.Schema = "http://json-schema.org/draft-04/schema#";

                    resourceSchemas.Add(resourceProvider, resourceSchema);
                }
                else
                {
                    resourceSchema = resourceSchemas[resourceProvider];
                }

                string methodUrlPathAfterProvider = afterPrefix.Substring(forwardSlashIndexAfterProvider + 1);
                string[] resourceTypes = ParseResourceTypes(resourceProvider, methodUrlPathAfterProvider, method);
                foreach (string resourceType in resourceTypes)
                {
                    JsonSchema resourceDefinition = new JsonSchema();
                    resourceDefinition.JsonType = "object";

                    resourceDefinition.AddProperty("type", JsonSchema.CreateStringEnum(resourceType), true);
                    resourceDefinition.AddProperty("apiVersion", JsonSchema.CreateStringEnum(apiVersion), true);

                    if (method.Body != null)
                    {
                        CompositeType body = method.Body.Type as CompositeType;
                        Debug.Assert(body != null, "The create resource method's body must be a CompositeType and cannot be null.");
                        if (body != null)
                        {
                            foreach (Property property in body.Properties)
                            {
                                if (!resourceDefinition.Properties.Keys.Contains(property.Name))
                                {
                                    JsonSchema propertyDefinition = ParseType(property, property.Type, resourceSchema.Definitions, serviceClient.ModelTypes);
                                    if (propertyDefinition != null)
                                    {
                                        resourceDefinition.AddProperty(property.Name, propertyDefinition, property.IsRequired || property.Name == "properties");
                                    }
                                }
                            }
                        }
                    }

                    resourceDefinition.Description = resourceType;

                    string resourcePropertyName = resourceType.Substring(resourceProvider.Length + 1).Replace('/', '_');

                    Debug.Assert(!resourceSchema.ResourceDefinitions.ContainsKey(resourcePropertyName));
                    resourceSchema.AddResourceDefinition(resourcePropertyName, resourceDefinition);
                }
            }

            // This loop adds child resource schemas to their parent resource schemas. We can't do
            // this until we're done adding all resources as top level resources, though, because
            // it's possible that we will parse a child resource before we parse the parent
            // resource.
            foreach (ResourceSchema resourceSchema in resourceSchemas.Values)
            {
                // By iterating over the reverse order of the defined resource definitions, I'm
                // counting on the resource definitions being in sorted order. That way I'm
                // guaranteed to visit child resource definitions before I visit their parent
                // resource definitions. By doing this, I've guaranteed that grandchildren resource
                // definitions will be added to their grandparent (and beyond) ancestor
                // resource definitions.
                foreach (string resourcePropertyName in resourceSchema.ResourceDefinitions.Keys.Reverse())
                {
                    JsonSchema resourceDefinition = resourceSchema.ResourceDefinitions[resourcePropertyName];

                    string resourceType = resourceDefinition.ResourceType;
                    int lastSlashIndex = resourceType.LastIndexOf('/');
                    string parentResourceType = resourceType.Substring(0, lastSlashIndex);
                    JsonSchema parentResourceDefinition = resourceSchema.GetResourceDefinitionByResourceType(parentResourceType);
                    if (parentResourceDefinition != null)
                    {
                        string childResourceType = resourceType.Substring(lastSlashIndex + 1);
                        JsonSchema childResourceDefinition = resourceDefinition.Clone();
                        childResourceDefinition.ResourceType = childResourceType;

                        string childResourceDefinitionPropertyName = string.Join("_", resourcePropertyName, "childResource");
                        resourceSchema.AddDefinition(childResourceDefinitionPropertyName, childResourceDefinition);

                        JsonSchema childResources;
                        if (parentResourceDefinition.Properties.ContainsKey("resources"))
                        {
                            childResources = parentResourceDefinition.Properties["resources"];
                        }
                        else
                        {
                            childResources = new JsonSchema()
                            {
                                JsonType = "array",
                                Items = new JsonSchema()
                            };
                            parentResourceDefinition.AddProperty("resources", childResources);
                        }

                        childResources.Items.AddOneOf(new JsonSchema()
                        {
                            Ref = "#/definitions/" + childResourceDefinitionPropertyName,
                        });
                    }
                }
            }

            return resourceSchemas;
        }

        private static string[] ParseResourceTypes(string resourceProvider, string methodUrlPathAfterProvider, Method method)
        {
            // Gather the list of resource types defined by this method url. Usually this will
            // result in only one resource type, but if the method url contains an enumerated
            // resource type parameter, then multiple resource types could be declared from a
            // single method url.
            List<string> resourceTypes = new List<string>();
            resourceTypes.Add(resourceProvider);
            string[] pathSegments = methodUrlPathAfterProvider.Split(new char[] { '/' });
            for (int i = 0; i < pathSegments.Length; i += 2)
            {
                string pathSegment = pathSegments[i];
                if (IsPathVariable(pathSegment))
                {
                    string parameterName = pathSegment.Substring(1, pathSegment.Length - 2);
                    Parameter parameter = method.Parameters.FirstOrDefault(methodParameter => methodParameter.Name == parameterName);
                    if (parameter == null)
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Found undefined parameter reference {0} in create resource method \"{1}/{2}/{3}\".", pathSegment, resourceMethodPrefix, resourceProvider, methodUrlPathAfterProvider));
                    }

                    if (parameter.Type == null)
                    {
                        throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Parameter reference {0} has no defined type.", pathSegment));
                    }

                    EnumType parameterType = parameter.Type as EnumType;
                    if (parameterType == null)
                    {
                        // If we encounter a parameter in the URL that isn't an enumeration, then
                        // we can't create a resource from this URL.
                        resourceTypes.Clear();
                        break;
                    }

                    if (parameterType.Values == null || parameterType.Values.Count == 0)
                    {
                        string errorMessage = string.Format(CultureInfo.CurrentCulture, "Parameter reference {0} is defined as an enum type, but it doesn't have any specified values.", pathSegment);
                        throw new ArgumentException(errorMessage);
                    }

                    List<string> newResourceTypes = new List<string>();
                    foreach (string resourceType in resourceTypes)
                    {
                        foreach (EnumValue parameterValue in parameterType.Values)
                        {
                            newResourceTypes.Add(string.Join("/", resourceType, parameterValue.Name));
                        }
                    }

                    resourceTypes = newResourceTypes;
                }
                else
                {
                    for (int j = 0; j < resourceTypes.Count; ++j)
                    {
                        resourceTypes[j] = string.Join("/", resourceTypes[j], pathSegment);
                    }
                }
            }

            return resourceTypes.ToArray();
        }

        private static JsonSchema ParseType(Property property, IType type, IDictionary<string, JsonSchema> definitions, IEnumerable<CompositeType> modelTypes)
        {
            JsonSchema result = null;

            if (property == null || !property.IsReadOnly)
            {
                // A schema that matches a JSON object with specific properties, such as
                // { "name": { "type": "string" }, "age": { "type": "number" } }
                CompositeType compositeType = type as CompositeType;
                if (compositeType != null)
                {
                    result = ParseCompositeType(property, compositeType, definitions, modelTypes);
                }
                else
                {
                    // A schema that matches a "dictionary" JSON object, such as
                    // { "additionalProperties": { "type": "string" } }
                    DictionaryType dictionaryType = type as DictionaryType;
                    if (dictionaryType != null)
                    {
                        result = ParseDictionaryType(property, dictionaryType, definitions, modelTypes);
                    }
                    else
                    {
                        // A schema that matches a single value from a given set of values, such as
                        // { "enum": [ "a", "b" ] }
                        EnumType enumType = type as EnumType;
                        if (enumType != null)
                        {
                            result = ParseEnumType(property, enumType);
                        }
                        else
                        {
                            // A schema that matches simple values, such as { "type": "number" }
                            PrimaryType primaryType = type as PrimaryType;
                            if (primaryType != null)
                            {
                                result = ParsePrimaryType(property, primaryType);
                            }
                            else
                            {
                                // A schema that matches an array of values, such as
                                // { "items": { "type": "number" } }
                                SequenceType sequenceType = type as SequenceType;
                                if (sequenceType != null)
                                {
                                    result = ParseSequenceType(property, sequenceType, definitions, modelTypes);
                                }
                                else
                                {
                                    Debug.Fail("Unrecognized property type: " + type.GetType());
                                }
                            }
                        }
                    }
                }
            }

            return result;
        }

        private static JsonSchema ParseCompositeType(Property property, CompositeType compositeType, IDictionary<string, JsonSchema> definitions, IEnumerable<CompositeType> modelTypes)
        {
            string definitionName = compositeType.Name;

            if (!definitions.ContainsKey(definitionName))
            {
                JsonSchema definition = new JsonSchema()
                {
                    JsonType = "object",
                    Description = compositeType.Documentation
                };

                // This definition must be added to the definition map before we start parsing
                // its properties because its properties may recursively reference back to this
                // definition.
                definitions.Add(definitionName, definition);

                foreach (Property subProperty in compositeType.ComposedProperties)
                {
                    JsonSchema subPropertyDefinition = ParseType(subProperty, subProperty.Type, definitions, modelTypes);
                    if (subPropertyDefinition != null)
                    {
                        definition.AddProperty(subProperty.Name, subPropertyDefinition, subProperty.IsRequired);
                    }
                }

                string discriminatorPropertyName = compositeType.PolymorphicDiscriminator;
                if (!string.IsNullOrWhiteSpace(discriminatorPropertyName))
                {
                    CompositeType[] subTypes = modelTypes.Where(modelType => modelType.BaseModelType == compositeType).ToArray();
                    if (subTypes != null && subTypes.Length > 0)
                    {
                        JsonSchema discriminatorDefinition = new JsonSchema()
                        {
                            JsonType = "string"
                        };

                        if (subTypes.Length == 1)
                        {
                            CompositeType subType = subTypes[0];
                            if (subType != null)
                            {
                                foreach (Property subTypeProperty in subType.Properties)
                                {
                                    JsonSchema subTypePropertyDefinition = ParseType(subTypeProperty, subTypeProperty.Type, definitions, modelTypes);
                                    if (subTypePropertyDefinition != null)
                                    {
                                        definition.AddProperty(subTypeProperty.Name, subTypePropertyDefinition, subTypeProperty.IsRequired);
                                    }
                                }

                                const string discriminatorValueExtensionName = "x-ms-discriminator-value";
                                if (subType.ComposedExtensions.ContainsKey(discriminatorValueExtensionName))
                                {
                                    string discriminatorValue = subType.ComposedExtensions[discriminatorValueExtensionName] as string;
                                    if (!string.IsNullOrWhiteSpace(discriminatorValue))
                                    {
                                        discriminatorDefinition.AddEnum(discriminatorValue);
                                    }
                                }
                            }

                            definition.AddProperty(discriminatorPropertyName, discriminatorDefinition);
                        }
                        else
                        {
                            string errorMessage = string.Format(
                                CultureInfo.CurrentCulture,
                                "Multiple sub-types ({0}) of a polymorphic discriminated type ({1}) are not currently supported.",
                                string.Join(", ", subTypes.Select(subType => subType.Name)),
                                compositeType.Name);
                            throw new NotSupportedException(errorMessage);
                        }
                    }
                }
            }

            JsonSchema result = new JsonSchema()
            {
                Ref = "#/definitions/" + definitionName
            };

            if (property != null)
            {
                result.Description = RemovePossibleValuesFromDescription(property.Documentation);
            }

            return result;
        }

        private static JsonSchema ParseDictionaryType(Property property, DictionaryType dictionaryType, IDictionary<string, JsonSchema> definitions, IEnumerable<CompositeType> modelTypes)
        {
            JsonSchema result = new JsonSchema()
            {
                JsonType = "object",
                AdditionalProperties = ParseType(null, dictionaryType.ValueType, definitions, modelTypes)
            };

            if (property != null)
            {
                result.Description = RemovePossibleValuesFromDescription(property.Documentation);
            }

            return result;
        }

        private static JsonSchema ParseEnumType(Property property, EnumType enumType)
        {
            JsonSchema result = new JsonSchema()
            {
                JsonType = "string"
            };

            foreach (EnumValue enumValue in enumType.Values)
            {
                result.AddEnum(enumValue.Name);
            }

            if (property != null)
            {
                result.Description = RemovePossibleValuesFromDescription(property.Documentation);
            }

            return result;
        }

        private static JsonSchema ParsePrimaryType(Property property, PrimaryType primaryType)
        {
            JsonSchema result = new JsonSchema()
            {
                Format = primaryType.Format
            };

            switch (primaryType.Type)
            {
                case KnownPrimaryType.Boolean:
                    result.JsonType = "boolean";
                    break;

                case KnownPrimaryType.Int:
                case KnownPrimaryType.Long:
                    result.JsonType = "integer";
                    break;

                case KnownPrimaryType.Double:
                    result.JsonType = "number";
                    break;

                case KnownPrimaryType.Object:
                    result.JsonType = "object";
                    break;

                case KnownPrimaryType.DateTime:
                case KnownPrimaryType.String:
                case KnownPrimaryType.TimeSpan:
                    result.JsonType = "string";
                    break;

                default:
                    Debug.Assert(false, "Unrecognized known property type: " + primaryType.Type);
                    break;
            }

            if (property != null)
            {
                result.Description = property.Documentation;

                if (property.DefaultValue != null)
                {
                    result.AddEnum(property.DefaultValue);
                }

                if (property.Constraints.Count > 0)
                {
                    foreach (KeyValuePair<Constraint, string> entry in property.Constraints)
                    {
                        switch (entry.Key)
                        {
                            case Constraint.InclusiveMinimum:
                                Debug.Assert(result.JsonType == "integer" || result.JsonType == "number", "Expected to only find an InclusiveMinimum constraint on an integer or number property.");
                                result.Minimum = Double.Parse(entry.Value, CultureInfo.CurrentCulture);
                                break;

                            case Constraint.InclusiveMaximum:
                                Debug.Assert(result.JsonType == "integer" || result.JsonType == "number", "Expected to only find an InclusiveMaximum constraint on an integer or number property.");
                                result.Maximum = Double.Parse(entry.Value, CultureInfo.CurrentCulture);
                                break;

                            case Constraint.Pattern:
                                Debug.Assert(result.JsonType == "string", "Expected to only find a Pattern constraint on a string property.");
                                result.Pattern = entry.Value;
                                break;

                            default:
                                Debug.Fail("Unrecognized property Constraint: " + entry.Key);
                                break;
                        }
                    }
                }
            }

            return result;
        }

        private static JsonSchema ParseSequenceType(Property property, SequenceType sequenceType, IDictionary<string, JsonSchema> definitions, IEnumerable<CompositeType> modelTypes)
        {
            JsonSchema result = new JsonSchema()
            {
                JsonType = "array",
                Items = ParseType(null, sequenceType.ElementType, definitions, modelTypes)
            };

            if (property != null)
            {
                result.Description = RemovePossibleValuesFromDescription(property.Documentation);
            }

            return result;
        }

        /// <summary>
        /// AutoRest has no way of indicating that you don't want Enum properties to have a
        /// "Possible values include: ..." string appended at the end of their descriptions. This
        /// function removes the "Possible values" suffix if it exists.
        /// </summary>
        /// <param name="description">The description to remove the "Possible values" suffix from.</param>
        /// <returns></returns>
        private static string RemovePossibleValuesFromDescription(string description)
        {
            if (!string.IsNullOrEmpty(description))
            {
                int possibleValuesIndex = description.IndexOf("Possible values include: ", StringComparison.OrdinalIgnoreCase);
                if (possibleValuesIndex > -1)
                {
                    description = description.Substring(0, possibleValuesIndex).TrimEnd();
                }
            }
            return description;
        }

        private static bool IsPathVariable(string pathSegment)
        {
            Debug.Assert(pathSegment != null);

            return pathSegment.StartsWith("{", StringComparison.Ordinal) && pathSegment.EndsWith("}", StringComparison.Ordinal);
        }
    }
}


text: export { default } from "./Transactions.js";


text:
package com.android.dexgen.dex.code.form;

import com.android.dexgen.dex.code.CstInsn;
import com.android.dexgen.dex.code.DalvInsn;
import com.android.dexgen.dex.code.InsnFormat;
import com.android.dexgen.rop.code.RegisterSpecList;
import com.android.dexgen.rop.cst.Constant;
import com.android.dexgen.rop.cst.CstLiteralBits;
import com.android.dexgen.util.AnnotatedOutput;

/**
 * Instruction format {@code 22b}. See the instruction format spec
 * for details.
 */
public final class Form22b extends InsnFormat {
    /** {@code non-null;} unique instance of this class */
    public static final InsnFormat THE_ONE = new Form22b();

    /**
     * Constructs an instance. This class is not publicly
     * instantiable. Use {@link #THE_ONE}.
     */
    private Form22b() {
        // This space intentionally left blank.
    }

    /** {@inheritDoc} */
    @Override
    public String insnArgString(DalvInsn insn) {
        RegisterSpecList regs = insn.getRegisters();
        CstLiteralBits value = (CstLiteralBits) ((CstInsn) insn).getConstant();

        return regs.get(0).regString() + ", " + regs.get(1).regString() +
            ", " + literalBitsString(value);
    }

    /** {@inheritDoc} */
    @Override
    public String insnCommentString(DalvInsn insn, boolean noteIndices) {
        CstLiteralBits value = (CstLiteralBits) ((CstInsn) insn).getConstant();
        return literalBitsComment(value, 8);
    }

    /** {@inheritDoc} */
    @Override
    public int codeSize() {
        return 2;
    }

    /** {@inheritDoc} */
    @Override
    public boolean isCompatible(DalvInsn insn) {
        RegisterSpecList regs = insn.getRegisters();
        if (!((insn instanceof CstInsn) &&
              (regs.size() == 2) &&
              unsignedFitsInByte(regs.get(0).getReg()) &&
              unsignedFitsInByte(regs.get(1).getReg()))) {
            return false;
        }

        CstInsn ci = (CstInsn) insn;
        Constant cst = ci.getConstant();

        if (!(cst instanceof CstLiteralBits)) {
            return false;
        }

        CstLiteralBits cb = (CstLiteralBits) cst;

        return cb.fitsInInt() && signedFitsInByte(cb.getIntBits());
    }

    /** {@inheritDoc} */
    @Override
    public InsnFormat nextUp() {
        return Form22s.THE_ONE;
    }

    /** {@inheritDoc} */
    @Override
    public void writeTo(AnnotatedOutput out, DalvInsn insn) {
        RegisterSpecList regs = insn.getRegisters();
        int value =
            ((CstLiteralBits) ((CstInsn) insn).getConstant()).getIntBits();

        write(out,
              opcodeUnit(insn, regs.get(0).getReg()),
              codeUnit(regs.get(1).getReg(), value & 0xff));
    }
}