text:
"use strict";

exports.__esModule = true;
exports.default = void 0;

var _AnimationPropTypes = _interopRequireDefault(require("../../modules/AnimationPropTypes"));

var _BorderPropTypes = _interopRequireDefault(require("../../modules/BorderPropTypes"));

var _ColorPropType = _interopRequireDefault(require("../ColorPropType"));

var _InteractionPropTypes = _interopRequireDefault(require("../../modules/InteractionPropTypes"));

var _LayoutPropTypes = _interopRequireDefault(require("../../modules/LayoutPropTypes"));

var _ShadowPropTypes = _interopRequireDefault(require("../../modules/ShadowPropTypes"));

var _TransformPropTypes = _interopRequireDefault(require("../../modules/TransformPropTypes"));

var _propTypes = require("prop-types");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var stringOrNumber = (0, _propTypes.oneOfType)([_propTypes.string, _propTypes.number]);
var overscrollBehaviorType = (0, _propTypes.oneOf)(['auto', 'contain', 'none']);

var ViewStylePropTypes = _objectSpread({}, _AnimationPropTypes.default, _BorderPropTypes.default, _InteractionPropTypes.default, _LayoutPropTypes.default, _ShadowPropTypes.default, _TransformPropTypes.default, {
  backgroundColor: _ColorPropType.default,
  opacity: _propTypes.number,

  /**
   * @platform unsupported
   */
  elevation: _propTypes.number,

  /**
   * @platform web
   */
  backdropFilter: _propTypes.string,
  backgroundAttachment: _propTypes.string,
  backgroundBlendMode: _propTypes.string,
  backgroundClip: _propTypes.string,
  backgroundImage: _propTypes.string,
  backgroundOrigin: (0, _propTypes.oneOf)(['border-box', 'content-box', 'padding-box']),
  backgroundPosition: _propTypes.string,
  backgroundRepeat: _propTypes.string,
  backgroundSize: _propTypes.string,
  boxShadow: _propTypes.string,
  clip: _propTypes.string,
  filter: _propTypes.string,
  outlineColor: _ColorPropType.default,
  outlineOffset: stringOrNumber,
  outlineStyle: _propTypes.string,
  outlineWidth: stringOrNumber,
  overscrollBehavior: overscrollBehaviorType,
  overscrollBehaviorX: overscrollBehaviorType,
  overscrollBehaviorY: overscrollBehaviorType,
  scrollbarWidth: (0, _propTypes.oneOf)(['auto', 'none']),
  scrollSnapAlign: _propTypes.string,
  scrollSnapType: _propTypes.string,
  WebkitMaskImage: _propTypes.string,
  WebkitOverflowScrolling: (0, _propTypes.oneOf)(['auto', 'touch'])
});

var _default = ViewStylePropTypes;
exports.default = _default;
module.exports = exports.default;


text:
import {
    Course, EquivType, Institution, KeyCourse
} from '../common/api-models';

export class CourseEquivalency {
    /** Course to perform lookups on */
    public keyCourse: KeyCourse;

    constructor(public input: Course[], public output: Course[], public type: EquivType) {
        if (input === null || input === undefined || input.length === 0) {
            throw new Error('input did not exist or was an empty array');
        }
        this.keyCourse = {
            subject: input[0].subject,
            number: input[0].number
        };
    }
}

/**
 * Used for inserting course equivalencies from the same institution into the
 * database. Equivalencies pulled from the database have the shape of
 * CourseEquivalencyDocument.
 */
export interface EquivalencyContext {
    institution: Institution;
    equivalencies: CourseEquivalency[];
    unparseable: number;
    parseSuccessRate: number;
}

export const CREDITS_UNKNOWN = -1;

redpajama_set_name: RedPajamaGithub


text:
> Lucy's web crawler and web scraper.

[Lucy](https://github.com/chirakiru/lucy "Code repository") is a tool to visualize in a friendly way truthful information about the status of air pollution.

## Installation

### Ubuntu 14.04.1 LTS (Trusty Tahr):
Commands to install [Scrapy](http://doc.scrapy.org):

```bash
$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 627220E7
$ echo 'deb http://archive.scrapy.org/ubuntu scrapy main' | sudo tee /etc/apt/sources.list.d/scrapy.list
$ sudo apt-get update && sudo apt-get install scrapy-0.24 python-psycopg2
```

### OS X
Install [pip](https://pip.pypa.io/en/latest/):

```bash
$ sudo easy_install pip
```

And then, install Scrapy

```bash
$ sudo pip install scrapy
```

## Usage

```bash
$ env LCDATABASE=yourdb LCUSER=youruser LCPASSWORD=yourpassword LCHOST=yourhost LCPORT=yourport scrapy crawl pollutants
```

Poor man's scheduler:

```bash
while [ $((1)) == 1 ]; do
  env LCDATABASE=yourdb LCUSER=youruser LCPASSWORD=yourpassword LCHOST=yourhost LCPORT=yourport scrapy crawl pollutants
  sleep 3600
done
```

Also, you can check [scrapy's documentation](http://doc.scrapy.org/en/latest/index.html).


text:
package com.plusonelabs.tasks;

public enum Alignment {

    LEFT(R.layout.day_header_left),
    CENTER(R.layout.day_header_center),
    RIGHT(R.layout.day_header_right);

    private int layoutId;

    Alignment(int layoutId) {
        this.layoutId = layoutId;
    }

    public int getLayoutId() {
        return layoutId;
    }
}


text:
// = Web Workers / Gears WorkerPool Abstraction =

dojo.provide("bespin.worker.worker");

(function() {
var WORKER_COUNT = 1;
var WORKER_INDEX = 0;
var CALL_INDEX   = 0;
var USE_GEARS    = false;

// these functions are part of a hack to transport code into the worker via
// a hash (#) url part that is extracted and evaled inside the worker
// Sounds like a security hole, but maybe it is not.
var JS_WORKER_SOURCE = "js/bespin/bootstrap_worker.js";
var uriEncodeSource = function(source) {
    return JS_WORKER_SOURCE+"#"+escape(source)
};
var uriDecodeSource = function(uri) {
    return unescape(uri.substr( (JS_WORKER_SOURCE+"#").length ))
};

// If there is no Worker API (http://www.whatwg.org/specs/web-workers/current-work/) yet,
// try to build one using Google Gears API
if (typeof Worker == "undefined") {
    BespinGearsInitializeGears(); // this functions initializes Gears only if we need it
    if(window.google && google.gears) {
        USE_GEARS   = true; // OK, gears is here

        var wp      = google.gears.factory.create('beta.workerpool');
        var workers = {};
        Worker      = function(uri, source) { // The worker class, non standard second source para
            this.isGears = true;

            this.id = wp.createWorker(source);
            workers[this.id] = this;
        };

        Worker.prototype = { // we can post messages to the worker
            postMessage: function(data) {
                wp.sendMessage(data, this.id)
            }
        };

        // upon receiving a message we call our onmessage callback
        // DOM-Message-Events are not supported
        wp.onmessage = function(a, b, message) {
            var worker = workers[message.sender];
            var cb = worker.onmessage;
            if(cb) {
                cb.call(worker, {
                    data: message.body
                });
            }
        };
    }
}
//** {{{ bespin.worker.Worker }}} **
//
// Takes an objects and build a facade object for it.
// Creates source code for a web worker that implements the same functionality as the original object
// and sends the source code to the web worker (The source code is created recursively, so complex
// objects are supported).
// Methods which are send to the facade are from now one delegated to the worker.
//
// Because all method calls are now async, the methods of the facade object return an object
// that has a function property called "and" which can invoked to defined a callback that will receive
// the return value of the method call.
// The and function takes 4 parameters
//    context: the this value of the callback.
//    mutex: (optional) a mutex for the callback (Means that after-callback of the mutex wont be called until after this callback is finished
//    paras: (optiona) array of extra parameters for the callback.
//    callback: Callback for the method. First parameter will be the return value of the method
//
// Background APIs:
// We prefer to use the web worker API
// If that is not there we try to use Gears Workers
// If that is not there code will be executed within the regular context but still be async (using setTimeout)
//
// Limitations:
// Objects may not include
// - closures
// - references to DOM nodes
// - circular references

dojo.declare("bespin.worker.WorkerFacade", null, {
    constructor: function(obj, workerCount, libs) { // only use workerCount > 1 if the object is stateless

        // Properties use __name__ notation to avoid conflicts with facade methods

        this.__obj__ = obj;

        var callbacks = {};
        this.__callbacks__ = callbacks;

        this.__workerCount__ = workerCount || WORKER_COUNT;

        // __hasWorkers__ is a public API of the facade
        this.__hasWorkers__ = false;

        if(typeof Worker != "undefined") { // We have a Worker implementation
            this.__hasWorkers__ = true;

            var source  = this.createWorkerSource(obj, libs);
            var workers = this.createWorkers(source);
            this.__workers__ = workers;
        }

        this.createFacade(obj);

    },

    // We support pools of workers which share the load
    __getWorker__: function() {
        var index = WORKER_INDEX++ % this.__workerCount__; // round robin scheduling
        // TODO maintain a smarter queue based on which workers are actually idle
        return this.__workers__[index];
    },

    // Create N workers based on source
    createWorkers: function(source) { // round robin scheduling
        var self    = this;
        var workers = [];

        // The standard callback choose a callback for the particular method using
        // the callIndex that is set upon sending the method
        var cb = function(event) {
            var data  = event.data;
            if(typeof data == "string") {
                data = dojo.fromJson(data);
            }
            var index = data.callIndex;

            var callback = self.__callbacks__[index];
            delete self.__callbacks__[index];
            if(callback) {
                callback(data.returnValue);
            }
        };

        var loadScript = function (index, url) {
            var worker = this;
            bespin.get("server").request('GET', url, null, {
                onSuccess: function (src) {
                    worker.postMessage("__IMPORT_SCRIPT__//"+index+"\n"+src);
                }
            });
        }

        var onmessage = function(event) {
            var message = event.data
            if(typeof message == "string") {
                if(message.indexOf("log=") == 0) {
                    console.log("From Worker: "+message.substr(4))
                    return
                }
                else
                if(message.indexOf("__IMPORT_SCRIPT__") == 0) {
                    var json = message.substr("__IMPORT_SCRIPT__".length)
                    var paras = dojo.fromJson(json)
                    loadScript.apply(this, paras)
                    return
                }
                else {
                    message = dojo.fromJson(message)
                }
            }
            cb.call(this, event)

        }

        for(var i = 0; i < this.__workerCount__;i++) {
            //console.log("Create worker")
            var worker = new Worker("/js/bespin/bootstrap_worker.js", source);
            //console.log("Worker created")
            worker.onmessage = onmessage;
            source = "// YOUcannotGuessMe\n" + source
            if(!USE_GEARS) {
                window.setTimeout(function() {
                    worker.postMessage(source)
                },0)
            }
            workers.push(worker)
        }
        return workers
    },

    // create a shallow facade for object
    createFacade: function(obj) {

        var facade = this;

        for(var prop in obj) {
            if(prop.charAt(0) != "_") { // supposedly we dont need "private" methods. Delete if assumption is wrong
                (function() { // make a lexical scope
                    var val    = obj[prop];
                    var method = prop
                    if(typeof val == "function") { // functions are replaced with code to call the worker
                        facade[prop] = function() {
                             var self  = this;
                             var index = CALL_INDEX++ // each call gets a globally unique index
                             var paras = Array.prototype.slice.call(arguments);
                             if(this.__hasWorkers__) {
                                 var data = {
                                     callIndex: index,
                                     method: method,
                                     paras:  paras
                                 }
                                 if(!USE_GEARS) data = dojo.toJson(data) // here we should really test whether our postMessage supports structured data. Safari 4 does not
                                 // send the method to a worker
                                 // console.log("Contacting worker "+data)
                                 this.__getWorker__().postMessage(data)
                             } else {
                                 // No worker implementation available. Use an async call using
                                 // setTimeout instead
                                 var self = this;
                                 window.setTimeout(function() {
                                     var retVal = self.__obj__[method].apply(self.__obj__, paras);
                                     var callback = self.__callbacks__[index];
                                     delete self.__callbacks__[index]
                                     if(callback) {
                                         callback(retVal)
                                     }
                                 }, 0)
                             }
                             // Return an object to create a "fluid-interface" style callback generator
                             // callback will be applied against context
                             // callback will be part of the mutex
                             // paras is an array of extra paras for the callback
                             return {
                                 and: function(context, mutex, paras, callback) {
                                     var func = arguments[arguments.length - 1] // always the last para
                                     if(mutex instanceof bespin.worker.Mutex) {
                                         mutex.start()
                                         func = function() {
                                             callback.apply(this, arguments)
                                             mutex.stop()
                                         }
                                     }

                                     self.__callbacks__[index] = function() {
                                         paras = Array.prototype.slice.call(arguments).concat(paras)
                                         func.apply(context, paras)
                                     }
                                 }
                             }
                        }
                    }
                    else {
                        // put instance vars here, too?
                    }
                })()
            }
        }
    },

    // Determines whether there are functions (deeply) inside a JS object
    hasFunctions: function(obj) {
        for(var i in obj) {
            var val = obj[i];
            if(typeof val == "function") {
                return true
            }
            if(val && typeof val == "object") {
                if(this.hasFunctions(val)) {
                    return true
                }
            }
        }
        return false
    },

    // Recursively turn a JS object into its source including functions
    serializeToPortableSource: function(obj) {
        var self   = this;
        var source = "{\n"

        for(var prop in obj) {
            // console.log("Serializing "+prop);
            (function() { // lexical scope
                if(prop == "_constructor") { // workaround for unserializable method in dojo
                    return                   // maybe replace with test for [native code] in string
                }
                var val    = obj[prop];
                var method = prop
                var src = ""
                if(typeof val == "function") { // serialize function to their string representation
                    src = val.toString();      // toSource() might be better but toString insert nice line breaks
                }
                // if val is an object that included functions we need to call ourselves recursively
                else if(val && typeof val == "object" && self.hasFunctions(val)) {
                    src = self.serializeToPortableSource(val)
                }
                // everything else is turned into JSON
                else {
                    src = dojo.toJson(val)
                }

                // Make sure to encode the property so nobody can insert arbitrary string into our JS
                prop = '"'+prop.replace(/"/g, '\\"', 'g')+'"'

                source += prop+": "+src+",\n"
            })()
        }

        source += "}\n";

        return source;
    },

    createWorkerSource: function(obj, libs) {
        var con = function(msg) {
            postMessage("log="+msg)
        }
        var source = "console = { log: "+con.toString()+" };\n"

        if(libs) {
            var quoted = [];
            dojo.forEach(libs, function(lib) {
                quoted.push("'"+lib+"'")
            })
            source += "importScripts("+quoted.join(", ")+");\n"
        }

        source += "var theObject = "+this.serializeToPortableSource(obj)

        // onmessage handler for use inside the worker
        var onmessage  = function(event) {
            var body         = event.data
            //console.log("Received "+body)
            var dataIsString = false;
            if(typeof body == "string") { // if the data is a string, assume that it is JSON
                if(body.indexOf("__IMPORT_SCRIPT__") == 0) {
                    var source = body.substr("__IMPORT_SCRIPT__".length);
                    var match = source.match(/^\/\/(\d+)/)
                    if(match) {
                        var index = parseInt(match[1], 10);
                        __evalScriptFromImport(index, source)

                    }
                    return
                }
                dataIsString = true;
                try {
                    body = JSON.parse(body)
                } catch(e) {
                    throw e+""+body
                }
            }
            var method = body.method;

            var o      = theObject

            // actually call the method
            var ret    = o[body.method].apply(o, body.paras)

            var data   = {
                method: body.method,
                returnValue: ret,
                callIndex: body.callIndex // the original callIndex to find callback
            }

            if(dataIsString) { // If data came as a json string encode data as JSON
                data = JSON.stringify(data)
            }

            //console.log("Sending "+data)
            postMessage(data)
        }

        function ajaxRequest (method, url, data, callback, errorCallback) {

            var request
            if(this.clientHasGears()) {
                request = google.gears.factory.create('beta.httprequest');
            } else {
                request = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
            }
            var dataString    = ""
            if(data) {
                for(var i in data) {
                    dataString += encodeURIComponent(i)+"="+encodeURIComponent(data[i])+"&"
                }
            }
            var theUrl = url;
            if(data && method == "GET") {
                theUrl += "?"+dataString
            }
            request.open(method, theUrl, true);

            request.onreadystatechange = function onreadystatechange () {
                if (request.readyState == 4) {
                    if(request.status >= 200 && request.status < 400) {
                        var res = request.responseText;
                        callback(res)
                    } else {
                        if(errorCallback) {
                            return errorCallback(request)
                        } else {
                            throw new Error("Error fetching url "+theUrl+". Response code: " + request.status + " Response text: "+request.responseText)
                        }
                    }
                }
            };
            if(data && method == "POST") {
                // FIXME determine page encoding instead of always using UTF8
                request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                request.send(dataString)
            } else {
                dataString = ""
                request.send(dataString);
            }
        }

        if(USE_GEARS) { // For Gears we need to create a fake postMessage function
            var gearsCB = function(a, b, message) {
                var sender = message.sender
                postMessage = function(data) {
                    wp.sendMessage(data, sender)
                }
                onmessage({ // call the onmessage function defined above
                    data: message.body
                })
            }

            source += "\nvar wp = google.gears.workerPool; wp.onmessage = "+gearsCB.toString()+"\n";

            // emulate importScripts in Gears.
            var importScripts = function importScripts () {
                var global = this;
                var src = "";
                var i = 0;
                var load = function(url, callback) {
                    var request = google.gears.factory.create('beta.httprequest');
                    request.open('GET', url);
                    request.onreadystatechange = function() {
                        if(request.readyState == 4) {
                            if(request.status >= 200 && request.status < 400) {
                                var res = request.responseText;
                                src += res+"\n";
                                callback()
                            } else {
                                throw new Error("Error fetching script "+url+". Response code: " + request.status + " Response text: "+request.responseText)
                            }
                        }
                    };
                    request.send()
                }
                var urls = Array.prototype.splice.call(arguments, 0);
                var loader = function() {
                    var url = urls.shift()
                    if(url) {
                        load(url, loader)
                    } else {
                        global.eval(src)
                    }
                }
                loader()
            }

            source += importScripts.toString();
        }

        source += "\nonmessage = "+onmessage.toString()+"; \n"

        //console.log(source)

        return source
    }

});

//** {{{ bespin.worker.Mutex }}} **
//
// Object that maintains a counter of running workers/async processes.
// Calling after(callback) schedules a function to be called until all
// async processes are finished
//
// Is Mutex the correct term?
dojo.declare("bespin.worker.Mutex", null, {
    constructor: function(name, options) {
        this.name  = name;
        this.count = 0;
        this.afterJobs = [];
        this.options   = options || {}
    },
    start: function() {
        this.count = this.count + 1
    },
    stop: function() {
        this.count = this.count - 1
        if(this.count == 0) {
            if(this.options.onlyLast) {
                var last = this.afterJobs[this.afterJobs.length-1];
                if(last) {
                    last()
                }
            } else {
                for(var i = 0; i < this.afterJobs.length; ++i) {
                    var job = this.afterJobs[i];
                    job()
                }
            }
            this.afterJobs = []
        }
    },
    after: function(context, func) {
        this.afterJobs.push(function() {
            func.call(context)
        })
    }
})

// Copyright 2007, Google Inc.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Sets up google.gears.*, which is *the only* supported way to access Gears.
//
// Circumvent this file at your own risk!
//
// In the future, Gears may automatically define google.gears.* without this
// file. Gears may use these objects to transparently fix bugs and compatibility
// issues. Applications that use the code below will continue to work seamlessly
// when that happens.

// Sorry Google for modifying this :)
function BespinGearsInitializeGears() {
  // We are already defined. Hooray!
  if (window.google && google.gears) {
    return;
  }

  var factory = null;

  // Firefox
  if (typeof GearsFactory != 'undefined') {
    factory = new GearsFactory();
  } else {
    // IE
    try {
      factory = new ActiveXObject('Gears.Factory');
      // privateSetGlobalObject is only required and supported on WinCE.
      if (factory.getBuildInfo().indexOf('ie_mobile') != -1) {
        factory.privateSetGlobalObject(this);
      }
    } catch (e) {
      // Safari
      if (navigator.mimeTypes["application/x-googlegears"]) {
        factory = document.createElement("object");
        factory.style.display = "none";
        factory.width = 0;
        factory.height = 0;
        factory.type = "application/x-googlegears";
        document.documentElement.appendChild(factory);
      }
    }
  }

  // *Do not* define any objects if Gears is not installed. This mimics the
  // behavior of Gears defining the objects in the future.
  if (!factory) {
    return;
  }

  // Now set up the objects, being careful not to overwrite anything.
  //
  // Note: In Internet Explorer for Windows Mobile, you can't add properties to
  // the window object. However, global objects are automatically added as
  // properties of the window object in all browsers.
  if (!window.google) {
    google = {};
  }

  if (!google.gears) {
    google.gears = {factory: factory};
  }
}

})()


text:
import reducer from 'features/home/reducer'

describe('feature/home/reducer', () => {
  it('feature reducer does nothing if no matched action', () => {
    const prevState = {}
    const state = reducer(
      prevState,
      { type: '__unknown_action_type__' }
    )
    expect(state).to.equal(prevState)
  })

  // TODO: add global reducer test if needed.
})


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: tensorflow_serving/core/logging.proto

#ifndef PROTOBUF_tensorflow_5fserving_2fcore_2flogging_2eproto__INCLUDED
#define PROTOBUF_tensorflow_5fserving_2fcore_2flogging_2eproto__INCLUDED

#include <string>

#include <google/protobuf/stubs/common.h>

#if GOOGLE_PROTOBUF_VERSION < 3002000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please update
#error your headers.
#endif
#if 3002000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please
#error regenerate this file with a newer version of protoc.
#endif

#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>  // IWYU pragma: export
#include <google/protobuf/extension_set.h>  // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
#include "tensorflow_serving/apis/model.pb.h"
#include "tensorflow_serving/config/logging_config.pb.h"
// @@protoc_insertion_point(includes)
namespace tensorflow {
namespace serving {
class LogMetadata;
class LogMetadataDefaultTypeInternal;
extern LogMetadataDefaultTypeInternal _LogMetadata_default_instance_;
class LoggingConfig;
class LoggingConfigDefaultTypeInternal;
extern LoggingConfigDefaultTypeInternal _LoggingConfig_default_instance_;
class ModelSpec;
class ModelSpecDefaultTypeInternal;
extern ModelSpecDefaultTypeInternal _ModelSpec_default_instance_;
class SamplingConfig;
class SamplingConfigDefaultTypeInternal;
extern SamplingConfigDefaultTypeInternal _SamplingConfig_default_instance_;
}  // namespace serving
}  // namespace tensorflow

namespace tensorflow {
namespace serving {

namespace protobuf_tensorflow_5fserving_2fcore_2flogging_2eproto {
// Internal implementation detail -- do not call these.
struct TableStruct {
  static const ::google::protobuf::uint32 offsets[];
  static void InitDefaultsImpl();
  static void Shutdown();
};
void AddDescriptors();
void InitDefaults();
}  // namespace protobuf_tensorflow_5fserving_2fcore_2flogging_2eproto

// ===================================================================

class LogMetadata : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:tensorflow.serving.LogMetadata) */ {
 public:
  LogMetadata();
  virtual ~LogMetadata();

  LogMetadata(const LogMetadata& from);

  inline LogMetadata& operator=(const LogMetadata& from) {
    CopyFrom(from);
    return *this;
  }

  inline ::google::protobuf::Arena* GetArena() const PROTOBUF_FINAL {
    return GetArenaNoVirtual();
  }
  inline void* GetMaybeArenaPointer() const PROTOBUF_FINAL {
    return MaybeArenaPtr();
  }
  static const ::google::protobuf::Descriptor* descriptor();
  static const LogMetadata& default_instance();

  static inline const LogMetadata* internal_default_instance() {
    return reinterpret_cast<const LogMetadata*>(
               &_LogMetadata_default_instance_);
  }

  void UnsafeArenaSwap(LogMetadata* other);
  void Swap(LogMetadata* other);

  // implements Message ----------------------------------------------

  inline LogMetadata* New() const PROTOBUF_FINAL { return New(NULL); }

  LogMetadata* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
  void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
  void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
  void CopyFrom(const LogMetadata& from);
  void MergeFrom(const LogMetadata& from);
  void Clear() PROTOBUF_FINAL;
  bool IsInitialized() const PROTOBUF_FINAL;

  size_t ByteSizeLong() const PROTOBUF_FINAL;
  bool MergePartialFromCodedStream(
      ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
  void SerializeWithCachedSizes(
      ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
  ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
      bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
  ::google::protobuf::uint8* SerializeWithCachedSizesToArray(::google::protobuf::uint8* output)
      const PROTOBUF_FINAL {
    return InternalSerializeWithCachedSizesToArray(
        ::google::protobuf::io::CodedOutputStream::IsDefaultSerializationDeterministic(), output);
  }
  int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const PROTOBUF_FINAL;
  void InternalSwap(LogMetadata* other);
  protected:
  explicit LogMetadata(::google::protobuf::Arena* arena);
  private:
  static void ArenaDtor(void* object);
  inline void RegisterArenaDtor(::google::protobuf::Arena* arena);
  private:
  inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
    return _internal_metadata_.arena();
  }
  inline void* MaybeArenaPtr() const {
    return _internal_metadata_.raw_arena_ptr();
  }
  public:

  ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;

  // nested types ----------------------------------------------------

  // accessors -------------------------------------------------------

  // .tensorflow.serving.ModelSpec model_spec = 1;
  bool has_model_spec() const;
  void clear_model_spec();
  static const int kModelSpecFieldNumber = 1;
  private:
  void _slow_mutable_model_spec();
  void _slow_set_allocated_model_spec(
      ::google::protobuf::Arena* message_arena, ::tensorflow::serving::ModelSpec** model_spec);
  ::tensorflow::serving::ModelSpec* _slow_release_model_spec();
  public:
  const ::tensorflow::serving::ModelSpec& model_spec() const;
  ::tensorflow::serving::ModelSpec* mutable_model_spec();
  ::tensorflow::serving::ModelSpec* release_model_spec();
  void set_allocated_model_spec(::tensorflow::serving::ModelSpec* model_spec);
  ::tensorflow::serving::ModelSpec* unsafe_arena_release_model_spec();
  void unsafe_arena_set_allocated_model_spec(
      ::tensorflow::serving::ModelSpec* model_spec);

  // .tensorflow.serving.SamplingConfig sampling_config = 2;
  bool has_sampling_config() const;
  void clear_sampling_config();
  static const int kSamplingConfigFieldNumber = 2;
  private:
  void _slow_mutable_sampling_config();
  void _slow_set_allocated_sampling_config(
      ::google::protobuf::Arena* message_arena, ::tensorflow::serving::SamplingConfig** sampling_config);
  ::tensorflow::serving::SamplingConfig* _slow_release_sampling_config();
  public:
  const ::tensorflow::serving::SamplingConfig& sampling_config() const;
  ::tensorflow::serving::SamplingConfig* mutable_sampling_config();
  ::tensorflow::serving::SamplingConfig* release_sampling_config();
  void set_allocated_sampling_config(::tensorflow::serving::SamplingConfig* sampling_config);
  ::tensorflow::serving::SamplingConfig* unsafe_arena_release_sampling_config();
  void unsafe_arena_set_allocated_sampling_config(
      ::tensorflow::serving::SamplingConfig* sampling_config);

  // @@protoc_insertion_point(class_scope:tensorflow.serving.LogMetadata)
 private:

  ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
  friend class ::google::protobuf::Arena;
  typedef void InternalArenaConstructable_;
  typedef void DestructorSkippable_;
  ::tensorflow::serving::ModelSpec* model_spec_;
  ::tensorflow::serving::SamplingConfig* sampling_config_;
  mutable int _cached_size_;
  friend struct  protobuf_tensorflow_5fserving_2fcore_2flogging_2eproto::TableStruct;
};
// ===================================================================

// ===================================================================

#if !PROTOBUF_INLINE_NOT_IN_HEADERS
// LogMetadata

// .tensorflow.serving.ModelSpec model_spec = 1;
inline bool LogMetadata::has_model_spec() const {
  return this != internal_default_instance() && model_spec_ != NULL;
}
inline void LogMetadata::clear_model_spec() {
  if (GetArenaNoVirtual() == NULL && model_spec_ != NULL) delete model_spec_;
  model_spec_ = NULL;
}
inline const ::tensorflow::serving::ModelSpec& LogMetadata::model_spec() const {
  // @@protoc_insertion_point(field_get:tensorflow.serving.LogMetadata.model_spec)
  return model_spec_ != NULL ? *model_spec_
                         : *::tensorflow::serving::ModelSpec::internal_default_instance();
}
inline ::tensorflow::serving::ModelSpec* LogMetadata::mutable_model_spec() {

  if (model_spec_ == NULL) {
    _slow_mutable_model_spec();
  }
  // @@protoc_insertion_point(field_mutable:tensorflow.serving.LogMetadata.model_spec)
  return model_spec_;
}
inline ::tensorflow::serving::ModelSpec* LogMetadata::release_model_spec() {
  // @@protoc_insertion_point(field_release:tensorflow.serving.LogMetadata.model_spec)

  if (GetArenaNoVirtual() != NULL) {
    return _slow_release_model_spec();
  } else {
    ::tensorflow::serving::ModelSpec* temp = model_spec_;
    model_spec_ = NULL;
    return temp;
  }
}
inline  void LogMetadata::set_allocated_model_spec(::tensorflow::serving::ModelSpec* model_spec) {
  ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
  if (message_arena == NULL) {
    delete model_spec_;
  }
  if (model_spec != NULL) {
    _slow_set_allocated_model_spec(message_arena, &model_spec);
  }
  model_spec_ = model_spec;
  if (model_spec) {

  } else {

  }
  // @@protoc_insertion_point(field_set_allocated:tensorflow.serving.LogMetadata.model_spec)
}

// .tensorflow.serving.SamplingConfig sampling_config = 2;
inline bool LogMetadata::has_sampling_config() const {
  return this != internal_default_instance() && sampling_config_ != NULL;
}
inline void LogMetadata::clear_sampling_config() {
  if (GetArenaNoVirtual() == NULL && sampling_config_ != NULL) delete sampling_config_;
  sampling_config_ = NULL;
}
inline const ::tensorflow::serving::SamplingConfig& LogMetadata::sampling_config() const {
  // @@protoc_insertion_point(field_get:tensorflow.serving.LogMetadata.sampling_config)
  return sampling_config_ != NULL ? *sampling_config_
                         : *::tensorflow::serving::SamplingConfig::internal_default_instance();
}
inline ::tensorflow::serving::SamplingConfig* LogMetadata::mutable_sampling_config() {

  if (sampling_config_ == NULL) {
    _slow_mutable_sampling_config();
  }
  // @@protoc_insertion_point(field_mutable:tensorflow.serving.LogMetadata.sampling_config)
  return sampling_config_;
}
inline ::tensorflow::serving::SamplingConfig* LogMetadata::release_sampling_config() {
  // @@protoc_insertion_point(field_release:tensorflow.serving.LogMetadata.sampling_config)

  if (GetArenaNoVirtual() != NULL) {
    return _slow_release_sampling_config();
  } else {
    ::tensorflow::serving::SamplingConfig* temp = sampling_config_;
    sampling_config_ = NULL;
    return temp;
  }
}
inline  void LogMetadata::set_allocated_sampling_config(::tensorflow::serving::SamplingConfig* sampling_config) {
  ::google::protobuf::Arena* message_arena = GetArenaNoVirtual();
  if (message_arena == NULL) {
    delete sampling_config_;
  }
  if (sampling_config != NULL) {
    _slow_set_allocated_sampling_config(message_arena, &sampling_config);
  }
  sampling_config_ = sampling_config;
  if (sampling_config) {

  } else {

  }
  // @@protoc_insertion_point(field_set_allocated:tensorflow.serving.LogMetadata.sampling_config)
}

#endif  // !PROTOBUF_INLINE_NOT_IN_HEADERS

// @@protoc_insertion_point(namespace_scope)

}  // namespace serving
}  // namespace tensorflow

// @@protoc_insertion_point(global_scope)

#endif  // PROTOBUF_tensorflow_5fserving_2fcore_2flogging_2eproto__INCLUDED


text:
    <column name="trash_srl" type="number" size="11" notnull="notnull" primary_key="primary_key" />
    <column name="title" type="varchar" size="250" />
    <column name="origin_module" type="varchar" size="250" default="document" notnull="notnull" />
    <column name="serialized_object" type="bigtext" notnull="notnull" />
    <column name="description" type="text" />
    <column name="ipaddress" type="varchar" size="128" notnull="notnull" />
    <column name="remover_srl" type="number" size="11" notnull="notnull" />
    <column name="regdate" type="date" index="idx_regdate" />


text:
import math

import torch
import torch.nn as nn
import torch.nn.functional as F

from fairseq import utils
from fairseq.models import (
    FairseqEncoder,
    FairseqIncrementalDecoder,
    FairseqEncoderDecoderModel,
    register_model,
    register_model_architecture,
)
from fairseq.modules import (
    AdaptiveSoftmax, BeamableMM, FairseqDropout, GradMultiply, LearnedPositionalEmbedding,
    LinearizedConvolution,
)

@register_model('fconv')
class FConvModel(FairseqEncoderDecoderModel):
    """
    A fully convolutional model, i.e. a convolutional encoder and a
    convolutional decoder, as described in `"Convolutional Sequence to Sequence
    Learning" (Gehring et al., 2017) <https://arxiv.org/abs/1705.03122>`_.

    Args:
        encoder (FConvEncoder): the encoder
        decoder (FConvDecoder): the decoder

    The Convolutional model provides the following named architectures and
    command-line arguments:

    .. argparse::
        :ref: fairseq.models.fconv_parser
        :prog:
    """

    @classmethod
    def hub_models(cls):

        def moses_subword(path):
            return {
                'path': path,
                'tokenizer': 'moses',
                'bpe': 'subword_nmt',
            }

        return {
            'conv.wmt14.en-fr': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/wmt14.v2.en-fr.fconv-py.tar.bz2'),
            'conv.wmt14.en-de': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/wmt14.en-de.fconv-py.tar.bz2'),
            'conv.wmt17.en-de': moses_subword('https://dl.fbaipublicfiles.com/fairseq/models/wmt17.v2.en-de.fconv-py.tar.bz2'),
        }

    def __init__(self, encoder, decoder):
        super().__init__(encoder, decoder)
        self.encoder.num_attention_layers = sum(layer is not None for layer in decoder.attention)

    @staticmethod
    def add_args(parser):
        """Add model-specific arguments to the parser."""
        # fmt: off
        parser.add_argument('--dropout', type=float, metavar='D',
                            help='dropout probability')
        parser.add_argument('--encoder-embed-dim', type=int, metavar='N',
                            help='encoder embedding dimension')
        parser.add_argument('--encoder-embed-path', type=str, metavar='STR',
                            help='path to pre-trained encoder embedding')
        parser.add_argument('--encoder-layers', type=str, metavar='EXPR',
                            help='encoder layers [(dim, kernel_size), ...]')
        parser.add_argument('--decoder-embed-dim', type=int, metavar='N',
                            help='decoder embedding dimension')
        parser.add_argument('--decoder-embed-path', type=str, metavar='STR',
                            help='path to pre-trained decoder embedding')
        parser.add_argument('--decoder-layers', type=str, metavar='EXPR',
                            help='decoder layers [(dim, kernel_size), ...]')
        parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N',
                            help='decoder output embedding dimension')
        parser.add_argument('--decoder-attention', type=str, metavar='EXPR',
                            help='decoder attention [True, ...]')
        parser.add_argument('--share-input-output-embed', action='store_true',
                            help='share input and output embeddings (requires'
                                 ' --decoder-out-embed-dim and --decoder-embed-dim'
                                 ' to be equal)')
        # fmt: on

    @classmethod
    def build_model(cls, args, task):
        """Build a new model instance."""
        # make sure that all args are properly defaulted (in case there are any new ones)
        base_architecture(args)

        encoder_embed_dict = None
        if args.encoder_embed_path:
            encoder_embed_dict = utils.parse_embedding(args.encoder_embed_path)
            utils.print_embed_overlap(encoder_embed_dict, task.source_dictionary)

        decoder_embed_dict = None
        if args.decoder_embed_path:
            decoder_embed_dict = utils.parse_embedding(args.decoder_embed_path)
            utils.print_embed_overlap(decoder_embed_dict, task.target_dictionary)

        encoder = FConvEncoder(
            dictionary=task.source_dictionary,
            embed_dim=args.encoder_embed_dim,
            embed_dict=encoder_embed_dict,
            convolutions=eval(args.encoder_layers),
            dropout=args.dropout,
            max_positions=args.max_source_positions,
        )
        decoder = FConvDecoder(
            dictionary=task.target_dictionary,
            embed_dim=args.decoder_embed_dim,
            embed_dict=decoder_embed_dict,
            convolutions=eval(args.decoder_layers),
            out_embed_dim=args.decoder_out_embed_dim,
            attention=eval(args.decoder_attention),
            dropout=args.dropout,
            max_positions=args.max_target_positions,
            share_embed=args.share_input_output_embed,
        )
        return FConvModel(encoder, decoder)

class FConvEncoder(FairseqEncoder):
    """
    Convolutional encoder consisting of `len(convolutions)` layers.

    Args:
        dictionary (~fairseq.data.Dictionary): encoding dictionary
        embed_dim (int, optional): embedding dimension
        embed_dict (str, optional): filename from which to load pre-trained
            embeddings
        max_positions (int, optional): maximum supported input sequence length
        convolutions (list, optional): the convolutional layer structure. Each
            list item `i` corresponds to convolutional layer `i`. Layers are
            given as ``(out_channels, kernel_width, [residual])``. Residual
            connections are added between layers when ``residual=1`` (which is
            the default behavior).
        dropout (float, optional): dropout to be applied before each conv layer
    """

    def __init__(
        self, dictionary, embed_dim=512, embed_dict=None, max_positions=1024,
        convolutions=((512, 3),) * 20, dropout=0.1,
    ):
        super().__init__(dictionary)
        self.dropout_module = FairseqDropout(
            dropout, module_name=self.__class__.__name__
        )
        self.num_attention_layers = None

        num_embeddings = len(dictionary)
        self.padding_idx = dictionary.pad()
        self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx)
        if embed_dict:
            self.embed_tokens = utils.load_embedding(embed_dict, self.dictionary, self.embed_tokens)

        self.embed_positions = PositionalEmbedding(
            max_positions,
            embed_dim,
            self.padding_idx,
        )

        convolutions = extend_conv_spec(convolutions)
        in_channels = convolutions[0][0]
        self.fc1 = Linear(embed_dim, in_channels, dropout=dropout)
        self.projections = nn.ModuleList()
        self.convolutions = nn.ModuleList()
        self.residuals = []

        layer_in_channels = [in_channels]
        for _, (out_channels, kernel_size, residual) in enumerate(convolutions):
            if residual == 0:
                residual_dim = out_channels
            else:
                residual_dim = layer_in_channels[-residual]
            self.projections.append(Linear(residual_dim, out_channels)
                                    if residual_dim != out_channels else None)
            if kernel_size % 2 == 1:
                padding = kernel_size // 2
            else:
                padding = 0
            self.convolutions.append(
                ConvTBC(in_channels, out_channels * 2, kernel_size,
                        dropout=dropout, padding=padding)
            )
            self.residuals.append(residual)
            in_channels = out_channels
            layer_in_channels.append(out_channels)
        self.fc2 = Linear(in_channels, embed_dim)

    def forward(self, src_tokens, src_lengths):
        """
        Args:
            src_tokens (LongTensor): tokens in the source language of shape
                `(batch, src_len)`
            src_lengths (LongTensor): lengths of each source sentence of shape
                `(batch)`

        Returns:
            dict:
                - **encoder_out** (tuple): a tuple with two elements, where the
                  first element is the last encoder layer's output and the
                  second element is the same quantity summed with the input
                  embedding (used for attention). The shape of both tensors is
                  `(batch, src_len, embed_dim)`.
                - **encoder_padding_mask** (ByteTensor): the positions of
                  padding elements of shape `(batch, src_len)`
        """
        # embed tokens and positions
        x = self.embed_tokens(src_tokens) + self.embed_positions(src_tokens)
        x = self.dropout_module(x)
        input_embedding = x

        # project to size of convolution
        x = self.fc1(x)

        # used to mask padding in input
        encoder_padding_mask = src_tokens.eq(self.padding_idx).t()  # -> T x B
        if not encoder_padding_mask.any():
            encoder_padding_mask = None

        # B x T x C -> T x B x C
        x = x.transpose(0, 1)

        residuals = [x]
        # temporal convolutions
        for proj, conv, res_layer in zip(self.projections, self.convolutions, self.residuals):
            if res_layer > 0:
                residual = residuals[-res_layer]
                residual = residual if proj is None else proj(residual)
            else:
                residual = None

            if encoder_padding_mask is not None:
                x = x.masked_fill(encoder_padding_mask.unsqueeze(-1), 0)

            x = self.dropout_module(x)
            if conv.kernel_size[0] % 2 == 1:
                # padding is implicit in the conv
                x = conv(x)
            else:
                padding_l = (conv.kernel_size[0] - 1) // 2
                padding_r = conv.kernel_size[0] // 2
                x = F.pad(x, (0, 0, 0, 0, padding_l, padding_r))
                x = conv(x)
            x = F.glu(x, dim=2)

            if residual is not None:
                x = (x + residual) * math.sqrt(0.5)
            residuals.append(x)

        # T x B x C -> B x T x C
        x = x.transpose(1, 0)

        # project back to size of embedding
        x = self.fc2(x)

        if encoder_padding_mask is not None:
            encoder_padding_mask = encoder_padding_mask.t()  # -> B x T
            x = x.masked_fill(encoder_padding_mask.unsqueeze(-1), 0)

        # scale gradients (this only affects backward, not forward)
        x = GradMultiply.apply(x, 1.0 / (2.0 * self.num_attention_layers))

        # add output to input embedding for attention
        y = (x + input_embedding) * math.sqrt(0.5)

        return {
            'encoder_out': (x, y),
            'encoder_padding_mask': encoder_padding_mask,  # B x T
        }

    def reorder_encoder_out(self, encoder_out, new_order):
        if encoder_out['encoder_out'] is not None:
            encoder_out['encoder_out'] = (
                encoder_out['encoder_out'][0].index_select(0, new_order),
                encoder_out['encoder_out'][1].index_select(0, new_order),
            )
        if encoder_out['encoder_padding_mask'] is not None:
            encoder_out['encoder_padding_mask'] = \
                encoder_out['encoder_padding_mask'].index_select(0, new_order)
        return encoder_out

    def max_positions(self):
        """Maximum input length supported by the encoder."""
        return self.embed_positions.max_positions

class AttentionLayer(nn.Module):
    def __init__(self, conv_channels, embed_dim, bmm=None):
        super().__init__()
        # projects from output of convolution to embedding dimension
        self.in_projection = Linear(conv_channels, embed_dim)
        # projects from embedding dimension to convolution size
        self.out_projection = Linear(embed_dim, conv_channels)

        self.bmm = bmm if bmm is not None else torch.bmm

    def forward(self, x, target_embedding, encoder_out, encoder_padding_mask):
        residual = x

        # attention
        x = (self.in_projection(x) + target_embedding) * math.sqrt(0.5)
        x = self.bmm(x, encoder_out[0])

        # don't attend over padding
        if encoder_padding_mask is not None:
            x = x.float().masked_fill(
                encoder_padding_mask.unsqueeze(1),
                float('-inf')
            ).type_as(x)  # FP16 support: cast to float and back

        # softmax over last dim
        sz = x.size()
        x = F.softmax(x.view(sz[0] * sz[1], sz[2]), dim=1)
        x = x.view(sz)
        attn_scores = x

        x = self.bmm(x, encoder_out[1])

        # scale attention output (respecting potentially different lengths)
        s = encoder_out[1].size(1)
        if encoder_padding_mask is None:
            x = x * (s * math.sqrt(1.0 / s))
        else:
            s = s - encoder_padding_mask.type_as(x).sum(dim=1, keepdim=True)  # exclude padding
            s = s.unsqueeze(-1)
            x = x * (s * s.rsqrt())

        # project back
        x = (self.out_projection(x) + residual) * math.sqrt(0.5)
        return x, attn_scores

    def make_generation_fast_(self, beamable_mm_beam_size=None, **kwargs):
        """Replace torch.bmm with BeamableMM."""
        if beamable_mm_beam_size is not None:
            del self.bmm
            self.add_module('bmm', BeamableMM(beamable_mm_beam_size))

class FConvDecoder(FairseqIncrementalDecoder):
    """Convolutional decoder"""

    def __init__(
        self, dictionary, embed_dim=512, embed_dict=None, out_embed_dim=256,
        max_positions=1024, convolutions=((512, 3),) * 20, attention=True,
        dropout=0.1, share_embed=False, positional_embeddings=True,
        adaptive_softmax_cutoff=None, adaptive_softmax_dropout=0.,
    ):
        super().__init__(dictionary)
        self.register_buffer('version', torch.Tensor([2]))
        self.dropout_module = FairseqDropout(
            dropout, module_name=self.__class__.__name__
        )
        self.need_attn = True

        convolutions = extend_conv_spec(convolutions)
        in_channels = convolutions[0][0]
        if isinstance(attention, bool):
            # expand True into [True, True, ...] and do the same with False
            attention = [attention] * len(convolutions)
        if not isinstance(attention, list) or len(attention) != len(convolutions):
            raise ValueError('Attention is expected to be a list of booleans of '
                             'length equal to the number of layers.')

        num_embeddings = len(dictionary)
        padding_idx = dictionary.pad()
        self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx)
        if embed_dict:
            self.embed_tokens = utils.load_embedding(embed_dict, self.dictionary, self.embed_tokens)

        self.embed_positions = PositionalEmbedding(
            max_positions,
            embed_dim,
            padding_idx,
        ) if positional_embeddings else None

        self.fc1 = Linear(embed_dim, in_channels, dropout=dropout)
        self.projections = nn.ModuleList()
        self.convolutions = nn.ModuleList()
        self.attention = nn.ModuleList()
        self.residuals = []

        layer_in_channels = [in_channels]
        for i, (out_channels, kernel_size, residual) in enumerate(convolutions):
            if residual == 0:
                residual_dim = out_channels
            else:
                residual_dim = layer_in_channels[-residual]
            self.projections.append(Linear(residual_dim, out_channels)
                                    if residual_dim != out_channels else None)
            self.convolutions.append(
                LinearizedConv1d(in_channels, out_channels * 2, kernel_size,
                                 padding=(kernel_size - 1), dropout=dropout)
            )
            self.attention.append(AttentionLayer(out_channels, embed_dim)
                                  if attention[i] else None)
            self.residuals.append(residual)
            in_channels = out_channels
            layer_in_channels.append(out_channels)

        self.adaptive_softmax = None
        self.fc2 = self.fc3 = None

        if adaptive_softmax_cutoff is not None:
            assert not share_embed
            self.adaptive_softmax = AdaptiveSoftmax(num_embeddings, in_channels, adaptive_softmax_cutoff,
                                                    dropout=adaptive_softmax_dropout)
        else:
            self.fc2 = Linear(in_channels, out_embed_dim)
            if share_embed:
                assert out_embed_dim == embed_dim, \
                    "Shared embed weights implies same dimensions " \
                    " out_embed_dim={} vs embed_dim={}".format(out_embed_dim, embed_dim)
                self.fc3 = nn.Linear(out_embed_dim, num_embeddings)
                self.fc3.weight = self.embed_tokens.weight
            else:
                self.fc3 = Linear(out_embed_dim, num_embeddings, dropout=dropout)

    def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None, **unused):
        if encoder_out is not None:
            encoder_padding_mask = encoder_out['encoder_padding_mask']
            encoder_out = encoder_out['encoder_out']

            # split and transpose encoder outputs
            encoder_a, encoder_b = self._split_encoder_out(encoder_out, incremental_state)

        if self.embed_positions is not None:
            pos_embed = self.embed_positions(prev_output_tokens, incremental_state)
        else:
            pos_embed = 0

        if incremental_state is not None:
            prev_output_tokens = prev_output_tokens[:, -1:]
        x = self._embed_tokens(prev_output_tokens, incremental_state)

        # embed tokens and combine with positional embeddings
        x += pos_embed
        x = self.dropout_module(x)
        target_embedding = x

        # project to size of convolution
        x = self.fc1(x)

        # B x T x C -> T x B x C
        x = self._transpose_if_training(x, incremental_state)

        # temporal convolutions
        avg_attn_scores = None
        num_attn_layers = len(self.attention)
        residuals = [x]
        for proj, conv, attention, res_layer in zip(self.projections, self.convolutions, self.attention,
                                                    self.residuals):
            if res_layer > 0:
                residual = residuals[-res_layer]
                residual = residual if proj is None else proj(residual)
            else:
                residual = None

            x = self.dropout_module(x)
            x = conv(x, incremental_state)
            x = F.glu(x, dim=2)

            # attention
            if attention is not None:
                x = self._transpose_if_training(x, incremental_state)

                x, attn_scores = attention(x, target_embedding, (encoder_a, encoder_b), encoder_padding_mask)

                if not self.training and self.need_attn:
                    attn_scores = attn_scores / num_attn_layers
                    if avg_attn_scores is None:
                        avg_attn_scores = attn_scores
                    else:
                        avg_attn_scores.add_(attn_scores)

                x = self._transpose_if_training(x, incremental_state)

            # residual
            if residual is not None:
                x = (x + residual) * math.sqrt(0.5)
            residuals.append(x)

        # T x B x C -> B x T x C
        x = self._transpose_if_training(x, incremental_state)

        # project back to size of vocabulary if not using adaptive softmax
        if self.fc2 is not None and self.fc3 is not None:
            x = self.fc2(x)
            x = self.dropout_module(x)
            x = self.fc3(x)

        return x, avg_attn_scores

    def reorder_incremental_state(self, incremental_state, new_order):
        super().reorder_incremental_state(incremental_state, new_order)
        encoder_out = utils.get_incremental_state(self, incremental_state, 'encoder_out')
        if encoder_out is not None:
            encoder_out = tuple(eo.index_select(0, new_order) for eo in encoder_out)
            utils.set_incremental_state(self, incremental_state, 'encoder_out', encoder_out)

    def max_positions(self):
        """Maximum output length supported by the decoder."""
        return self.embed_positions.max_positions if self.embed_positions is not None else float('inf')

    def upgrade_state_dict(self, state_dict):
        if utils.item(state_dict.get('decoder.version', torch.Tensor([1]))[0]) < 2:
            # old models use incorrect weight norm dimension
            for i, conv in enumerate(self.convolutions):
                # reconfigure weight norm
                nn.utils.remove_weight_norm(conv)
                self.convolutions[i] = nn.utils.weight_norm(conv, dim=0)
            state_dict['decoder.version'] = torch.Tensor([1])
        return state_dict

    def make_generation_fast_(self, need_attn=False, **kwargs):
        self.need_attn = need_attn

    def _embed_tokens(self, tokens, incremental_state):
        if incremental_state is not None:
            # keep only the last token for incremental forward pass
            tokens = tokens[:, -1:]
        return self.embed_tokens(tokens)

    def _split_encoder_out(self, encoder_out, incremental_state):
        """Split and transpose encoder outputs.

        This is cached when doing incremental inference.
        """
        cached_result = utils.get_incremental_state(self, incremental_state, 'encoder_out')
        if cached_result is not None:
            return cached_result

        # transpose only once to speed up attention layers
        encoder_a, encoder_b = encoder_out
        encoder_a = encoder_a.transpose(1, 2).contiguous()
        result = (encoder_a, encoder_b)

        if incremental_state is not None:
            utils.set_incremental_state(self, incremental_state, 'encoder_out', result)
        return result

    def _transpose_if_training(self, x, incremental_state):
        if incremental_state is None:
            x = x.transpose(0, 1)
        return x

def extend_conv_spec(convolutions):
    """
    Extends convolutional spec that is a list of tuples of 2 or 3 parameters
    (kernel size, dim size and optionally how many layers behind to look for residual)
    to default the residual propagation param if it is not specified
    """
    extended = []
    for spec in convolutions:
        if len(spec) == 3:
            extended.append(spec)
        elif len(spec) == 2:
            extended.append(spec + (1,))
        else:
            raise Exception('invalid number of parameters in convolution spec ' + str(spec) + '. expected 2 or 3')
    return tuple(extended)

def Embedding(num_embeddings, embedding_dim, padding_idx):
    m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)
    nn.init.normal_(m.weight, 0, 0.1)
    nn.init.constant_(m.weight[padding_idx], 0)
    return m

def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx):
    m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx)
    nn.init.normal_(m.weight, 0, 0.1)
    nn.init.constant_(m.weight[padding_idx], 0)
    return m

def Linear(in_features, out_features, dropout=0.):
    """Weight-normalized Linear layer (input: N x T x C)"""
    m = nn.Linear(in_features, out_features)
    nn.init.normal_(m.weight, mean=0, std=math.sqrt((1 - dropout) / in_features))
    nn.init.constant_(m.bias, 0)
    return nn.utils.weight_norm(m)

def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0., **kwargs):
    """Weight-normalized Conv1d layer optimized for decoding"""
    m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs)
    std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))
    nn.init.normal_(m.weight, mean=0, std=std)
    nn.init.constant_(m.bias, 0)
    return nn.utils.weight_norm(m, dim=2)

def ConvTBC(in_channels, out_channels, kernel_size, dropout=0., **kwargs):
    """Weight-normalized Conv1d layer"""
    from fairseq.modules import ConvTBC
    m = ConvTBC(in_channels, out_channels, kernel_size, **kwargs)
    std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels))
    nn.init.normal_(m.weight, mean=0, std=std)
    nn.init.constant_(m.bias, 0)
    return nn.utils.weight_norm(m, dim=2)

@register_model_architecture('fconv', 'fconv')
def base_architecture(args):
    args.dropout = getattr(args, 'dropout', 0.1)
    args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)
    args.encoder_embed_path = getattr(args, 'encoder_embed_path', None)
    args.encoder_layers = getattr(args, 'encoder_layers', '[(512, 3)] * 20')
    args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512)
    args.decoder_embed_path = getattr(args, 'decoder_embed_path', None)
    args.decoder_layers = getattr(args, 'decoder_layers', '[(512, 3)] * 20')
    args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256)
    args.decoder_attention = getattr(args, 'decoder_attention', 'True')
    args.share_input_output_embed = getattr(args, 'share_input_output_embed', False)

@register_model_architecture('fconv', 'fconv_iwslt_de_en')
def fconv_iwslt_de_en(args):
    args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 256)
    args.encoder_layers = getattr(args, 'encoder_layers', '[(256, 3)] * 4')
    args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 256)
    args.decoder_layers = getattr(args, 'decoder_layers', '[(256, 3)] * 3')
    args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256)
    base_architecture(args)

@register_model_architecture('fconv', 'fconv_wmt_en_ro')
def fconv_wmt_en_ro(args):
    args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 512)
    base_architecture(args)

@register_model_architecture('fconv', 'fconv_wmt_en_de')
def fconv_wmt_en_de(args):
    convs = '[(512, 3)] * 9'  # first 9 layers have 512 units
    convs += ' + [(1024, 3)] * 4'  # next 4 layers have 1024 units
    convs += ' + [(2048, 1)] * 2'  # final 2 layers use 1x1 convolutions

    args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768)
    args.encoder_layers = getattr(args, 'encoder_layers', convs)
    args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 768)
    args.decoder_layers = getattr(args, 'decoder_layers', convs)
    args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 512)
    base_architecture(args)

@register_model_architecture('fconv', 'fconv_wmt_en_fr')
def fconv_wmt_en_fr(args):
    convs = '[(512, 3)] * 6'  # first 6 layers have 512 units
    convs += ' + [(768, 3)] * 4'  # next 4 layers have 768 units
    convs += ' + [(1024, 3)] * 3'  # next 3 layers have 1024 units
    convs += ' + [(2048, 1)] * 1'  # next 1 layer uses 1x1 convolutions
    convs += ' + [(4096, 1)] * 1'  # final 1 layer uses 1x1 convolutions

    args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768)
    args.encoder_layers = getattr(args, 'encoder_layers', convs)
    args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 768)
    args.decoder_layers = getattr(args, 'decoder_layers', convs)
    args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 512)
    base_architecture(args)


text:
package com.alibaba.dubbo.cache.support;

import com.alibaba.dubbo.cache.Cache;
import com.alibaba.dubbo.cache.CacheFactory;
import com.alibaba.dubbo.common.URL;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * AbstractCacheFactory
 *
 * @author william.liangf
 */
public abstract class AbstractCacheFactory implements CacheFactory {

    private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();

    public Cache getCache(URL url) {
        String key = url.toFullString();
        Cache cache = caches.get(key);
        if (cache == null) {
            caches.put(key, createCache(url));
            cache = caches.get(key);
        }
        return cache;
    }

    protected abstract Cache createCache(URL url);

}


text:
layout: global
title: Spark Hadoop3 Integration Tests
---

# Running the Integration Tests

As mocking of an external systems (like AWS S3) is not always perfect the unit testing should be
extended with integration testing. This is why the build profile `integration-test` has been
introduced here. When it is given (`-Pintegration-test`) for testing then only those tests are
executed where the `org.apache.spark.internal.io.cloud.IntegrationTestSuite` tag is used.

One example is `AwsS3AbortableStreamBasedCheckpointFileManagerSuite`.

Integration tests will have some extra configurations for example selecting the external system to
run the test against. Those configs are passed as environment variables and the existence of these
variables must be checked by the test.
Like for `AwsS3AbortableStreamBasedCheckpointFileManagerSuite` the S3 bucket used for testing
is passed in the `S3A_PATH` and the credetinals to access AWS S3 are AWS_ACCESS_KEY_ID and
AWS_SECRET_ACCESS_KEY (in addition you can define an optional AWS_SESSION_TOKEN too).


text:
module Autocuke
  module Handler

    # Triggered after a file has been modified
    def file_modified
      return if runtime.current_file
      runtime.current_file = path
      local = path.sub(/.*#{runtime.options.root}\/?/, '')
      cmd   = "cd #{runtime.root}; bundle exec cucumber -p autocuke #{local}"
      puts "#{local} modified - re-cuking it."
      run_with_defer cmd
    end

    # Triggered after a file has been moved
    def file_moved
      stop! unless File.exists?(path)
    end

    # Triggered after a file has been deleted.
    # In text editors, the file is deleted and recreated rather than modified.
    # If so, we'll start watching the new file and trigger `file_modified`
    def file_deleted
      if File.exists?(path)
        file_modified
        runtime.watch(path)
      else
        stop!
      end
    end

    # Stop EM if the file doesn't exist
    def unbind
      stop! unless File.exists?(path)
    end

    private

      # Runs the cucumber command and triggers a callback when it's complete
      def run_with_defer(cmd)
        puts cmd if runtime.options.verbose
        operation = proc {
          system(cmd)
        }
        callback = proc {|result|
          runtime.current_file = nil
        }
        EM.defer operation, callback
      end

      # Just an alias to the active runtime
      def runtime
        Autocuke.active_runtime
      end

      # Warns the user and stops the active runtime
      def stop!
        puts "*" * 88
        puts "#{File.basename(path)} is no longer available! Autocuke stopping..."
        runtime.stop!
      end

  end
end


text:
<?php
srcStylesheet(
  '../css/iframe.css'
);
function get_template_codes()
{
  return array(
'',
'architecture',
'artifact',
'book',
'ceramic',
'comic',
'graphic',
'manuscript',
'movie',
'painting',
'photograph',
'sculpture');
}

function get_template_names()
{
  return array(
'',
'Architecture',
'Artifacts',
'Books',
'Ceramics',
'Comics',
'Graphic Art',
'Manuscripts',
'Movie Clip',
'Painting',
'Photography',
'Sculpture');
}

function select_template($val)
{
  $templates = get_template_codes();
  $names     = get_template_names();

  if (!isset($val)) {
    $val = '';
  }
  echo '
<select name="template_code" onchange="template_change()">';
$cnt = count($templates);
for ($i = 0; $i < $cnt; ++$i) {
  $value = $templates[$i];
  echo '
<option value="', $value, '"';
  if ($val == $value) {
    echo ' selected';
  }
  echo '>', $names[$i], '</option>';
}
  echo '
</select>';
}

function insert_template($annotation_id, $template_code, $template)
{
  $query1 = '';
  $seen   = false;

 require_once('../include/template/' . $template_code . '.php');

 $func = 'return_'.$template_code.'_fields';
 $template_fields  = $func();

//  echo ' code is '.$template_code.'
 ';
  foreach ($template_fields as $name) {

    if ($name != 'annotation_id') {
      $query1 .= ',';
 // echo 'Name: '.$name.' -> '. $template[$template_code][$name].'
';

	  if (isset($template[$template_code]) && ($template[$template_code][$name] != ' ')){
	//	    echo 'fields name -> '.$name.'value '. $template[$template_code][$name].' <<<<
 ';
		  $query1 .= DBstring($template[$template_code][$name]);
 	 	  $seen   = true ;
   	  }else {
		$query1 .= 'null';
	 }
    }
 }
/*
  foreach ($template as $name => $value) {

    if ($name != 'annotation_id') {
      $query1 .= ',';
      if (isset($value) && $value != '') {
        $query1 .= DBstring($value);
        $seen   = true;
      } else {
        $query1 .= 'null';
  } } }
*/

  if (!$seen) {
    return;
  }

  $query =
'insert into template_' . $template_code . 's(annotation_id';
  foreach ($template_fields as $name) { // => $value) {
    if ($name != 'annotation_id') {
      $query .= ',' . $name;
  } }

  $query .= ')
values(' . DBnumber($annotation_id) . $query1 . ')';

  $ret = DBquery($query);
  if (!$ret) {
    return $ret;
  }
  return true;
}

function template_form($template_code, $template)
{
  global $dir;

  if (isset($template_code) && $template_code != '') {
    require_once($dir . '/../include/template/' . $template_code . '.php');
    $function = 'template_' . $template_code;
    $function($template);
    return;
  }
}

require_once($dir . '/../include/tables.php');

function echo_template($annotation_id)
{
  $query =
'select template_code
  from annotations
 where annotation_id = ' . DBnumber($annotation_id);

  $ret = DBquery($query);
  if (!$ret) {
    return;
  }

  $row = DBfetch($ret);
  if (!$row) {
    echo 'Annotation ', $annotation_id, ' not found';
    return;
  }
  $template_code = $row['template_code'];
  if (isset($template_code) && $template_code != '') {
    require_once($dir . '/../include/template/' . $template_code . '.php');
    $function = 'echo_template_' . $template_code;
    $function($annotation_id);
  }
}
?>


text:
/*!
 *  1.0.0
 * Author: mosaicpro
 * Licence: http://themeforest.net/licenses
 * Copyright 2015
 */

(function ($) {
    "use strict";

    /**
     * jQuery plugin wrapper for compatibility with Angular UI.Utils: jQuery Passthrough
     */
    $.fn.tkSlickDefault = function () {

        if (! this.length) return;

        if (typeof $.fn.slick == 'undefined') return;

        var c = this;

        c.slick({
            dots: true,
            slidesToShow: c.data('items') || 3,
            responsive: [
                {
                    breakpoint: 1200,
                    settings: {
                        slidesToShow: c.data('itemsLg') || 4
                    }
                },
                {
                    breakpoint: 992,
                    settings: {
                        slidesToShow: c.data('itemsMd') || 3
                    }
                },
                {
                    breakpoint: 768,
                    settings: {
                        slidesToShow: c.data('itemsSm') || 3
                    }
                },
                {
                    breakpoint: 480,
                    settings: {
                        slidesToShow: c.data('itemsXs') || 2
                    }
                },
                {
                    breakpoint: 0,
                    settings: {
                        slidesToShow: 1
                    }
                }
            ],
            rtl: this.data('rtl'),
            onSetPosition: function () {
                $(window).trigger('resize');
            }
        });

        $(document).on('sidebar.shown', function(){
            c.slickSetOption('dots', true, true);
        });

    };

    $(".slick-basic").each(function () {
        $(this).tkSlickDefault();
    });

})(jQuery);
/*!
 *  1.0.0
 * Author: mosaicpro
 * Licence: http://themeforest.net/licenses
 * Copyright 2015
 */

/*!
 *  1.0.0
 * Author: mosaicpro
 * Licence: http://themeforest.net/licenses
 * Copyright 2015
 */

(function ($) {
    "use strict";

    $(window).bind('enterBreakpoint320', function () {
        var img = $('.messages-list .panel ul img');
        $('.messages-list .panel ul').width(img.first().width() * img.length);
    });

    $(window).bind('exitBreakpoint320', function () {
        $('.messages-list .panel ul').width('auto');
    });

})(jQuery);

/*!
 *  1.0.0
 * Author: mosaicpro
 * Licence: http://themeforest.net/licenses
 * Copyright 2015
 */

(function ($) {
    "use strict";

    $.fn.tkFormControlMaterial = function(){
        this
            .blur(function () {
                if (this.val())
                    this.addClass('used');
                else
                    this.removeClass('used');
            })
            .after('');
    };

    $('.form-control-material .form-control').each(function () {
        $(this).tkFormControlMaterial();
    });

    $(document).on('show.bs.dropdown', function (e) {

        if (Modernizr.touch && $(window).width() < 768) return true;

        var dd = $(e.relatedTarget).next('.dropdown-menu');
        var ddHeight = dd.outerHeight();
        dd.css({
            height: 0,
            display: 'block',
            overflow: 'hidden'
        });
        dd.velocity({opacity: 1}, {duration: 650, queue: false, easing: 'easeOutQuad'});
        dd.velocity({
            height: ddHeight,
            top: 0
        }, {
            duration: 650,
            queue: false,
            easing: 'easeOutCubic',
            complete: function () {
                dd.css({overflow: 'visible'});
            }
        });
    });

    $(document).on('hide.bs.dropdown', function (e) {

        if (Modernizr.touch && $(window).width() < 768) return true;

        var dd = $(e.relatedTarget).next('.dropdown-menu');
        dd.velocity({
            opacity: 0,
            top: '100%'
        }, {
            duration: 650, queue: false, easing: 'easeOutQuad', complete: function () {
                dd.css({
                    display: 'none',
                    height: 'auto'
                });
            }
        });
    });

})(jQuery);

(function ($) {
    "use strict";

    var ripple = function (e) {

        var el, ink, d, x, y;

        el = $(this);

        el.addClass('ripple');

        if (el.parents('.sidebar-skin-white').length) {
            el.addClass('ripple-dark-fade');
        }

        if (el.parents('.sidebar-skin-dark').length) {
            el.addClass('ripple-light-fade');
        }

        if (el.is('.btn-white')) {
            el.addClass('ripple-dark-fade');
        }

        if (el.attr('href') && ! el.data('toggle')) {
            e.preventDefault();
            if (el.closest('.dropdown-menu').length) {
                e.stopPropagation();
            }
            setTimeout(function () {
                document.location = el.attr('href');
            }, 400);
        }

        // create .ink element if it doesn't exist
        if (el.find(".ink").length === 0)
            el.prepend("");

        ink = el.find(".ink");
        // in case of quick double clicks stop the previous animation
        ink.removeClass("animate");

        // set size of .ink
        if (! ink.height() && ! ink.width()) {
            // use el's width or height whichever is larger for the diameter to make a circle which can cover the entire element.
            d = Math.max(el.outerWidth(), el.outerHeight());
            ink.css({height: d, width: d});
        }

        // get click coordinates
        // logic = click coordinates relative to page - el's position relative to page - half of self height/width to make it controllable from the center;
        x = e.pageX - el.offset().left - ink.width() / 2;
        y = e.pageY - el.offset().top - ink.height() / 2;

        // set the position and add class .animate
        ink.css({top: y + 'px', left: x + 'px'}).addClass("animate");

    };

    var listGroupMenu = $('.list-group-menu > .list-group-item > a'),
        button = $('.btn'),
        navbarNav = $('.navbar-nav > li > a'),
        dropdownMenu = $('.dropdown-menu > li > a'),
        sidebarMenu = $('.sidebar-menu > li > a');

    var addRipple = $()
        .add(listGroupMenu)
        .add(button)
        .add(navbarNav)
        .add(dropdownMenu)
        .add(sidebarMenu);

    if (addRipple.length) {
        addRipple.click(ripple);
    }

})(jQuery);


text: module.exports = require('@modulus/logger')('mongo-backup')


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_change_transparent"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="change transparent"
            android:textAllCaps="false"/>

        <Button
            android:id="@+id/btn_change_x"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/btn_change_transparent"
            android:text="change translationX"
            android:textAllCaps="false"/>

        <Button
            android:id="@+id/btn_change_y"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/btn_change_x"
            android:text="change translationY"
            android:textAllCaps="false"/>

        <Button
            android:id="@+id/btn_change_rotation_z"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/btn_change_transparent"
            android:layout_toRightOf="@id/btn_change_y"
            android:text="change rotation"
            android:textAllCaps="false"/>

        <Button
            android:id="@+id/btn_change_rotation_x"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/btn_change_rotation_z"
            android:text="change rotation x"
            android:textAllCaps="false"/>
        <Button
            android:id="@+id/btn_change_rotation_y"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/btn_change_rotation_x"
            android:layout_below="@id/btn_change_rotation_z"
            android:text="change rotation y"
            android:textAllCaps="false"/>

    </RelativeLayout>

    <View
        android:id="@+id/view_target"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_gravity="center"
        android:layout_margin="30dp"
        android:background="@android:color/black"/>

</LinearLayout>


text:
package com.graphhopper.gpx;

import com.graphhopper.routing.Dijkstra;
import com.graphhopper.routing.InstructionsFromEdges;
import com.graphhopper.routing.Path;
import com.graphhopper.routing.util.CarFlagEncoder;
import com.graphhopper.routing.util.EncodingManager;
import com.graphhopper.routing.util.FlagEncoder;
import com.graphhopper.routing.util.TraversalMode;
import com.graphhopper.routing.weighting.ShortestWeighting;
import com.graphhopper.storage.Graph;
import com.graphhopper.storage.GraphBuilder;
import com.graphhopper.storage.NodeAccess;
import com.graphhopper.util.*;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;

import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.StringReader;
import java.util.Date;
import java.util.List;
import java.util.Locale;

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

public class GpxConversionsTest {

    private EncodingManager carManager;
    private FlagEncoder carEncoder;
    private TranslationMap trMap;

    @BeforeEach
    public void setUp() {
        carEncoder = new CarFlagEncoder();
        carManager = EncodingManager.create(carEncoder);
        trMap = new TranslationMap().doImport();
    }

    @Test
    public void testInstructionsWithTimeAndPlace() {
        Graph g = new GraphBuilder(carManager).create();
        //   n-4-5   (n: pillar node)
        //   |
        // 7-3-2-6
        //     |
        //     1
        NodeAccess na = g.getNodeAccess();
        na.setNode(1, 15.0, 10);
        na.setNode(2, 15.1, 10);
        na.setNode(3, 15.1, 9.9);
        na.setNode(4, 15.2, 9.9);
        na.setNode(5, 15.2, 10);
        na.setNode(6, 15.1, 10.1);
        na.setNode(7, 15.1, 9.8);

        GHUtility.setSpeed(63, true, true, carEncoder, g.edge(1, 2).setDistance(7000).setName("1-2"));
        GHUtility.setSpeed(72, true, true, carEncoder, g.edge(2, 3).setDistance(8000).setName("2-3"));
        GHUtility.setSpeed(9, true, true, carEncoder, g.edge(2, 6).setDistance(10000).setName("2-6"));
        GHUtility.setSpeed(81, true, true, carEncoder, g.edge(3, 4).setDistance(9000).setName("3-4"));
        GHUtility.setSpeed(9, true, true, carEncoder, g.edge(3, 7).setDistance(10000).setName("3-7"));
        GHUtility.setSpeed(90, true, true, carEncoder, g.edge(4, 5).setDistance(10000).setName("4-5"));

        ShortestWeighting weighting = new ShortestWeighting(carEncoder);
        Path p = new Dijkstra(g, weighting, TraversalMode.NODE_BASED).calcPath(1, 5);
        InstructionList wayList = InstructionsFromEdges.calcInstructions(p, g, weighting, carManager, trMap.getWithFallBack(Locale.US));
        PointList points = p.calcPoints();
        assertEquals(4, wayList.size());

        assertEquals(34000, p.getDistance(), 1e-1);
        assertEquals(34000, sumDistances(wayList), 1e-1);
        assertEquals(5, points.size());
        assertEquals(1604120, p.getTime());

        assertEquals(Instruction.CONTINUE_ON_STREET, wayList.get(0).getSign());
        assertEquals(15, wayList.get(0).getPoints().getLat(0), 1e-3);
        assertEquals(10, wayList.get(0).getPoints().getLon(0), 1e-3);

        assertEquals(Instruction.TURN_LEFT, wayList.get(1).getSign());
        assertEquals(15.1, wayList.get(1).getPoints().getLat(0), 1e-3);
        assertEquals(10, wayList.get(1).getPoints().getLon(0), 1e-3);

        assertEquals(Instruction.TURN_RIGHT, wayList.get(2).getSign());
        assertEquals(15.1, wayList.get(2).getPoints().getLat(0), 1e-3);
        assertEquals(9.9, wayList.get(2).getPoints().getLon(0), 1e-3);

        String gpxStr = GpxConversions.createGPX(wayList, "test", (long) 0, false, true, true, true, Constants.VERSION, trMap.getWithFallBack(Locale.US));
        verifyGPX(gpxStr);
//        System.out.println(gpxStr);

        assertTrue(gpxStr.contains("<trkpt lat=\"15.0\" lon=\"10.0\"><time>1970-01-01T00:00:00Z</time>"), gpxStr);
        assertTrue(gpxStr.contains("<extensions>") && gpxStr.contains("</extensions>"), gpxStr);
        assertTrue(gpxStr.contains("<rtept lat=\"15.1\" lon=\"10.0\">"), gpxStr);
        assertTrue(gpxStr.contains("<gh:distance>8000.0</gh:distance>"), gpxStr);
        assertTrue(gpxStr.contains("<desc>turn left onto 2-3</desc>"), gpxStr);
        assertTrue(gpxStr.contains("<gh:sign>-2</gh:sign>"), gpxStr);

        assertTrue(gpxStr.contains("<gh:direction>N</gh:direction>"), gpxStr);
        assertTrue(gpxStr.contains("<gh:azimuth>0.0</gh:azimuth>"), gpxStr);

        assertFalse(gpxStr.contains("NaN"));
    }

    @Test
    public void testCreateGPX() {
        InstructionList instructions = new InstructionList(trMap.getWithFallBack(Locale.US));
        PointList pl = new PointList();
        pl.add(49.942576, 11.580384);
        pl.add(49.941858, 11.582422);
        instructions.add(new Instruction(Instruction.CONTINUE_ON_STREET, "temp", pl).setDistance(240).setTime(15000));

        pl = new PointList();
        pl.add(49.941575, 11.583501);
        instructions.add(new Instruction(Instruction.TURN_LEFT, "temp2", pl).setDistance(25).setTime(4000));

        pl = new PointList();
        pl.add(49.941389, 11.584311);
        instructions.add(new Instruction(Instruction.TURN_LEFT, "temp2", pl).setDistance(25).setTime(3000));
        instructions.add(new FinishInstruction(49.941029, 11.584514, 0));

        List<GpxConversions.GPXEntry> result = GpxConversions.createGPXList(instructions);
        assertEquals(5, result.size());

        assertEquals(0, result.get(0).getTime().longValue());
        assertNull(result.get(1).getTime());
        assertEquals(15000, result.get(2).getTime().longValue());
        assertEquals(19000, result.get(3).getTime().longValue());
        assertEquals(22000, result.get(4).getTime().longValue());

        verifyGPX(GpxConversions.createGPX(instructions, "GraphHopper", new Date().getTime(), false, true, true, true, Constants.VERSION, trMap.getWithFallBack(Locale.US)));
    }

    @Test
    public void testCreateGPXIncludesRoundaboutExitNumber() {
        InstructionList instructions = new InstructionList(trMap.getWithFallBack(Locale.US));

        PointList pl = new PointList();
        pl.add(52.555423473315, 13.43890086052345);
        pl.add(52.555550691982, 13.43946393816465);
        pl.add(52.555619423589, 13.43886994061328);
        RoundaboutInstruction instr = new RoundaboutInstruction(Instruction.USE_ROUNDABOUT, "streetname", pl)
                .setRadian(2.058006514284998d)
                .setExitNumber(3)
                .setExited();
        instructions.add(instr);
        instructions.add(new FinishInstruction(52.555619423589, 13.43886994061328, 0));

        String gpxStr = GpxConversions.createGPX(instructions, "test", 0, true, true, false, false, Constants.VERSION, trMap.getWithFallBack(Locale.US));

        assertTrue(gpxStr.contains("<gh:exit_number>3</gh:exit_number>"), gpxStr);
        verifyGPX(gpxStr);
    }

    @Test
    public void testCreateGPXCorrectFormattingSmallNumbers() {
        InstructionList instructions = new InstructionList(trMap.getWithFallBack(Locale.US));

        PointList pl = new PointList();
        pl.add(0.000001, 0.000001);
        pl.add(-0.000123, -0.000125);
        Instruction instruction = new Instruction(0, "do it", pl);
        instructions.add(instruction);
        instructions.add(new FinishInstruction(0.000852, 0.000852, 0));

        String gpxStr = GpxConversions.createGPX(instructions, "test", 0, true, true, true, true, Constants.VERSION, trMap.getWithFallBack(Locale.US));

        assertFalse(gpxStr.contains("E-"), gpxStr);
        assertTrue(gpxStr.contains("0.000001"), gpxStr);
        assertTrue(gpxStr.contains("-0.000125"), gpxStr);
        verifyGPX(gpxStr);
    }

    @Test
    public void testXMLEscape_issue572() {
        assertEquals("_", GpxConversions.simpleXMLEscape("<"));
        assertEquals("_blup_", GpxConversions.simpleXMLEscape("<blup>"));
        assertEquals("a&b", GpxConversions.simpleXMLEscape("a&b"));
    }

    private void verifyGPX(String gpx) {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        Schema schema = null;
        try {
            Source schemaFile = new StreamSource(getClass().getResourceAsStream("gpx-schema.xsd"));
            schema = schemaFactory.newSchema(schemaFile);

            // using more schemas: http://stackoverflow.com/q/1094893/194609
        } catch (SAXException e1) {
            throw new IllegalStateException("There was a problem with the schema supplied for validation. Message:" + e1.getMessage());
        }
        Validator validator = schema.newValidator();
        try {
            validator.validate(new StreamSource(new StringReader(gpx)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private double sumDistances(InstructionList il) {
        double val = 0;
        for (Instruction i : il) {
            val += i.getDistance();
        }
        return val;
    }

    @Test
    public void testCalcAzimuthAndGetDirection() {
        PointList pl = new PointList();
        pl.add(49.942, 11.584);

        PointList nextPl = new PointList();
        nextPl.add(49.942, 11.582);
        Instruction currI = new Instruction(Instruction.CONTINUE_ON_STREET, "temp", pl);
        Instruction nextI = new Instruction(Instruction.CONTINUE_ON_STREET, "next", nextPl);

        assertEquals(270, GpxConversions.calcAzimuth(currI, nextI), .1);
        assertEquals("W", GpxConversions.calcDirection(currI, nextI));

        PointList p2 = new PointList();
        p2.add(49.942, 11.580);
        p2.add(49.944, 11.582);
        Instruction i2 = new Instruction(Instruction.CONTINUE_ON_STREET, "temp", p2);

        assertEquals(32.76, GpxConversions.calcAzimuth(i2, null), .1);
        assertEquals("NE", GpxConversions.calcDirection(i2, null));

        PointList p3 = new PointList();
        p3.add(49.942, 11.580);
        p3.add(49.944, 11.580);
        Instruction i3 = new Instruction(Instruction.CONTINUE_ON_STREET, "temp", p3);

        assertEquals(0, GpxConversions.calcAzimuth(i3, null), .1);
        assertEquals("N", GpxConversions.calcDirection(i3, null));

        PointList p4 = new PointList();
        p4.add(49.940, 11.580);
        p4.add(49.920, 11.586);
        Instruction i4 = new Instruction(Instruction.CONTINUE_ON_STREET, "temp", p4);

        assertEquals("S", GpxConversions.calcDirection(i4, null));

        PointList p5 = new PointList();
        p5.add(49.940, 11.580);
        Instruction i5 = new Instruction(Instruction.CONTINUE_ON_STREET, "temp", p5);

        assertTrue(Double.isNaN(GpxConversions.calcAzimuth(i5, null)));
        assertEquals("", GpxConversions.calcDirection(i5, null));
    }

}