text:
package org.apache.flink.table.connector.source;

import org.apache.flink.api.connector.source.SourceReader;
import org.apache.flink.api.connector.source.SourceReaderContext;
import org.apache.flink.api.connector.source.lib.util.IteratorSourceReader;
import org.apache.flink.table.data.RowData;

import java.util.Iterator;

/** Managed {@link SourceReader} for testing. */
public class TestManagedFileSourceReader
        extends IteratorSourceReader<RowData, Iterator<RowData>, TestManagedIterableSourceSplit> {

    public TestManagedFileSourceReader(SourceReaderContext context) {
        super(context);
    }
}

redpajama_set_name: RedPajamaGithub


text:
.. _api:

Developer Interface
===================

.. module:: requests

This part of the documentation covers all the interfaces of Requests.  For
parts where Requests depends on external libraries, we document the most
important right here and provide links to the canonical documentation.

Main Interface
--------------

All of Requests' functionality can be accessed by these 7 methods.
They all return an instance of the :class:`Response <Response>` object.

.. autofunction:: request

.. autofunction:: head
.. autofunction:: get
.. autofunction:: post
.. autofunction:: put
.. autofunction:: patch
.. autofunction:: delete

Lower-Level Classes
~~~~~~~~~~~~~~~~~~~

.. autoclass:: requests.Request
   :inherited-members:

.. autoclass:: Response
   :inherited-members:

Request Sessions
----------------

.. autoclass:: Session
   :inherited-members:

.. autoclass:: requests.adapters.HTTPAdapter
   :inherited-members:

Exceptions
~~~~~~~~~~

.. autoexception:: requests.exceptions.RequestException
.. autoexception:: requests.exceptions.ConnectionError
.. autoexception:: requests.exceptions.HTTPError
.. autoexception:: requests.exceptions.URLRequired
.. autoexception:: requests.exceptions.TooManyRedirects

Status Code Lookup
~~~~~~~~~~~~~~~~~~

.. autofunction:: requests.codes

::

    >>> requests.codes['temporary_redirect']
    307

    >>> requests.codes.teapot
    418

    >>> requests.codes['\o/']
    200

Cookies
~~~~~~~

.. autofunction:: requests.utils.dict_from_cookiejar
.. autofunction:: requests.utils.cookiejar_from_dict
.. autofunction:: requests.utils.add_dict_to_cookiejar

Encodings
~~~~~~~~~

.. autofunction:: requests.utils.get_encodings_from_content
.. autofunction:: requests.utils.get_encoding_from_headers
.. autofunction:: requests.utils.get_unicode_from_response

Classes
~~~~~~~

.. autoclass:: requests.Response
   :inherited-members:

.. autoclass:: requests.Request
   :inherited-members:

.. autoclass:: requests.PreparedRequest
   :inherited-members:

.. _sessionapi:

.. autoclass:: requests.Session
   :inherited-members:

.. autoclass:: requests.adapters.HTTPAdapter
   :inherited-members:

Migrating to 1.x
----------------

This section details the main differences between 0.x and 1.x and is meant
to ease the pain of upgrading.

API Changes
~~~~~~~~~~~

* ``Response.json`` is now a callable and not a property of a response.

  ::

      import requests
      r = requests.get('https://github.com/timeline.json')
      r.json()   # This *call* raises an exception if JSON decoding fails

* The ``Session`` API has changed. Sessions objects no longer take parameters.
  ``Session`` is also now capitalized, but it can still be
  instantiated with a lowercase ``session`` for backwards compatibility.

  ::

      s = requests.Session()    # formerly, session took parameters
      s.auth = auth
      s.headers.update(headers)
      r = s.get('http://httpbin.org/headers')

* All request hooks have been removed except 'response'.

* Authentication helpers have been broken out into separate modules. See
  requests-oauthlib_ and requests-kerberos_.

.. _requests-oauthlib: https://github.com/requests/requests-oauthlib
.. _requests-kerberos: https://github.com/requests/requests-kerberos

* The parameter for streaming requests was changed from ``prefetch`` to
  ``stream`` and the logic was inverted. In addition, ``stream`` is now
  required for raw response reading.

  ::

      # in 0.x, passing prefetch=False would accomplish the same thing
      r = requests.get('https://github.com/timeline.json', stream=True)
      r.raw.read(10)

* The ``config`` parameter to the requests method has been removed. Some of
  these options are now configured on a ``Session`` such as keep-alive and
  maximum number of redirects. The verbosity option should be handled by
  configuring logging.

  ::

      import requests
      import logging

      # these two lines enable debugging at httplib level (requests->urllib3->httplib)
      # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
      # the only thing missing will be the response.body which is not logged.
      import httplib
      httplib.HTTPConnection.debuglevel = 1

      logging.basicConfig() # you need to initialize logging, otherwise you will not see anything from requests
      logging.getLogger().setLevel(logging.DEBUG)
      requests_log = logging.getLogger("requests.packages.urllib3")
      requests_log.setLevel(logging.DEBUG)
      requests_log.propagate = True

      requests.get('http://httpbin.org/headers')

Licensing
~~~~~~~~~

One key difference that has nothing to do with the API is a change in the
license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0
license ensures that contributions to Requests are also covered by the Apache
2.0 license.

.. _ISC: http://opensource.org/licenses/ISC
.. _Apache 2.0: http://opensource.org/licenses/Apache-2.0


text:
package org.zstack.header.image;

import org.springframework.http.HttpMethod;
import org.zstack.header.identity.Action;
import org.zstack.header.message.*;
import org.zstack.header.other.APIAuditor;
import org.zstack.header.rest.RestRequest;
import org.zstack.header.storage.backup.BackupStorageVO;
import org.zstack.header.storage.snapshot.VolumeSnapshotVO;
import org.zstack.header.tag.TagResourceType;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 */
@Action(category = ImageConstant.ACTION_CATEGORY)
@RestRequest(
        path = "/images/data-volume-templates/from/volume-snapshots/{snapshotUuid}",
        responseClass = APICreateDataVolumeTemplateFromVolumeSnapshotEvent.class,
        method = HttpMethod.POST,
        parameterName = "params"
)
@TagResourceType(ImageVO.class)
@DefaultTimeout(timeunit = TimeUnit.HOURS, value = 72)
public class APICreateDataVolumeTemplateFromVolumeSnapshotMsg extends APICreateMessage implements APIAuditor, CreateDataVolumeTemplateMessage {
    @APIParam(resourceType = VolumeSnapshotVO.class, checkAccount = true, operationTarget = true)
    private String snapshotUuid;
    @APIParam(maxLength = 255)
    private String name;
    @APIParam(required = false, maxLength = 2048)
    private String description;
    @APIParam(nonempty = true, resourceType = BackupStorageVO.class)
    private List<String> backupStorageUuids;

    public void setSnapshotUuid(String snapshotUuid) {
        this.snapshotUuid = snapshotUuid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<String> getBackupStorageUuids() {
        return backupStorageUuids;
    }

    public void setBackupStorageUuids(List<String> backupStorageUuids) {
        this.backupStorageUuids = backupStorageUuids;
    }

    public String getSnapshotUuid() {
        return snapshotUuid;
    }

    public static APICreateDataVolumeTemplateFromVolumeSnapshotMsg __example__() {
        APICreateDataVolumeTemplateFromVolumeSnapshotMsg msg = new APICreateDataVolumeTemplateFromVolumeSnapshotMsg();

        msg.setName("My Data Volume Template");
        msg.setBackupStorageUuids(Collections.singletonList(uuid()));
        msg.setSnapshotUuid(uuid());

        return msg;
    }

    @Override
    public Result audit(APIMessage msg, APIEvent rsp) {
        return new Result(rsp.isSuccess() ? ((APICreateDataVolumeTemplateFromVolumeSnapshotEvent)rsp).getInventory().getUuid() : "", ImageVO.class);
    }
}


text:
var app = null;

Ext.define('CustomApp', {
    extend: 'Rally.app.App',
    componentCls: 'app',
    items : [
        {
            layout:'column',
            items : [
                {
                    margin : "5 20 5 20",
                    width : 400,
                    id:'cboFilter',
                    xtype:'combobox',
                    fieldLabel:'Successor',
                    displayField:'name',
                    valueField:'id',
                    queryMode:'local',
                    listeners : {
                        scope : this,
                        select : function(combo,records,eOpts) {
                            app.filterSuccessor(combo,records,eOpts);
                        }
                    }
                },
                { itemId : "exportLink", margin : "5 20 5 20"}
            ]
        }
    ],

    launch: function() {
        app = this;
        app.filterItems = [];
        app.filterStore = Ext.create('Ext.data.Store',{
            // remoteSort : true,
            sorters: [{
                property: 'name',
                direction: 'ASC'
            }],
            fields:['id',{name:'name',type:'string'}],
            data: app.filterItems
        });
        app.down("#cboFilter").bindStore(app.filterStore);

        app.project = app.getContext().getProject();
        // console.log("project",app.project);

        app.showFilter = app.getSetting('showFilter') === true;
        app.hideAccepted = app.getSetting('hideAccepted') === true;
        app.truncateNameTo = app.getSetting('truncateNameTo') > 0 ? parseInt(app.getSetting('truncateNameTo')) : 0;

        if (!app.showFilter) {
            app.down("#cboFilter").hide();
        }

        // console.log("hideAccepted",app.hideAccepted);
        app.myMask = new Ext.LoadMask(Ext.getBody(), {msg:"Please wait..."});
        app.myMask.show();

        async.waterfall([
                          this.getDependencySnapshots,
                          this.findMissingSnapshots,
                          this.addChildStoryInformation,
                          this.getProjectInformation,
                          this.cleanUpSnapshots,
                          this.getIterationInformation,
                          this._createGraph,
                          this._setFilterNodes,
                          this._createNodeList,
                          this._createNodeStatus,
                          this._createDagreGraph,
                          this._createGraphViz
                          ],
            function(err,nodes,links){
                if (err !== undefined && err !== null) {
                    app.myMask.hide();
                    console.log("err",err);
                    Rally.ui.notify.Notifier.show({message: err});
                    app.add(err);
                }

                app.myMask.hide();
                app.nodes = nodes;
                app.links = links;
            }
        );
    },

    config: {
        defaultSettings: {
            showFilter     : true,
            hideAccepted   : false,
            showExportLink : true,
            truncateNameTo : "0"
        }
    },

    getSettingsFields: function() {
        return [
            {
                name: 'showFilter',
                xtype: 'rallycheckboxfield',
                label : "Show Successor Filter"
            },

            {
                name: 'hideAccepted',
                xtype: 'rallycheckboxfield',
                label : "True to hide accepted stories"
            },
            {
                name: 'truncateNameTo',
                xtype: 'rallytextfield',
                label : "Truncate the name to specified number of characters"
            },
            {
                name: 'showExportLink',
                xtype: 'rallycheckboxfield',
                label : "Show Link to Export (dot) file"
            }
        ];
    },

    getProjectInformation : function( snapshots, callback) {

        var projects = _.compact(_.uniq(_.map( snapshots, function(s) { return s.get("Project"); })));
        async.map( projects, app.readProject, function(err,results) {
            app.projects = _.compact(_.map(results,function(r) { return r[0];}));
            callback(null,snapshots);
        });
    },

    cleanUpSnapshots : function( snapshots, callback) {

        // console.log("unfiltered snapshots:",snapshots.length);
        var snaps = _.filter(snapshots,function(snapshot) {
            // make sure the project for the snapshot exists
            var project = _.find(app.projects, function(p) {
                return snapshot.get("Project") === p.get("ObjectID");
            });

            return !(_.isUndefined(project)||_.isNull(project));
        });
        // console.log("filtered snapshots:",snaps.length);

        callback(null,snaps);

    },

    createIterationFilter : function(iterationIds) {

        var filter = null;

        _.each( iterationIds, function( iterationId, i ) {
            var f = Ext.create('Rally.data.wsapi.Filter', {
                    property : 'ObjectID', operator : '=', value : iterationId }
            );
            filter = (i===0) ? f : filter.or(f);
        });
        // console.log("Iteration Filter:",filter.toString());
        return filter;
    },

    getIterationInformation : function( snapshots, callback) {

        // also check for epic iterations
        var epicIterations = _.uniq( _.flatten(_.map(snapshots, function(s) {
            return _.map(s.get("LeafNodes"),function(leaf) {
                return(leaf.get("Iteration"));
            })
        })));

        var iterations = _.map( snapshots, function(s) { return s.get("Iteration"); });
        iterations = _.union(iterations,epicIterations);
        var iterationChunks = app.chunkArray(iterations);
        console.log("Iteration Chunks:",iterations.length,iterationChunks.length);

        var readIteration = function( iids, callback) {
            var config = {
                model : "Iteration",
                fetch : ['Name','ObjectID','StartDate','EndDate'],
                // filters : app.createIterationFilter(iids),
                context : { project : null}
            };
            app.wsapiQuery(config,callback);
        };

        async.map( iterationChunks, readIteration, function(err,results) {
            console.log("iteration results",results);
            app.iterations = _.flatten(results);
            // app.iterations = _.flatten( _.map(results,function(r) { return r[0]; }) );
            // app.iterations = _.reject(app.iterations,function(i) { return (i==="") || _.isUndefined(i);});
            console.log("iterations", app.iterations);
            callback(null,snapshots);
        });
    },

    readProject : function( pid, callback) {

        var config = { model : "Project",
                       fetch : ['Name','ObjectID','State'],
                       filters : [{property : "ObjectID", operator : "=", value : pid}]};
        app.wsapiQuery(config,callback);

    },

    wsapiQuery : function( config , callback ) {

        var storeConfig = {
            autoLoad : true,
            limit : "Infinity",
            model : config.model,
            fetch : config.fetch,
            filters : config.filters,
            listeners : {
                scope : this,
                load : function(store, data) {
                    callback(null,data);
                }
            }
        };
        if (!_.isUndefined(config.context)) {
            storeConfig.context = config.context;
        }

        Ext.create('Rally.data.WsapiDataStore', storeConfig);
    },

    // iterates the snapshots, checks predecessors to see if they are in the list
    // if not returned as an array to be read from rally

    getMissingSnapshots : function(snapshots) {
        var all = _.pluck(snapshots, function(s) { return s.get("ObjectID");});
        var missing = [];
        _.each(snapshots,function(s){
            var pr = s.get("Predecessors");
            var su = s.get("Successors");
            if ( _.isArray(pr)) {
                missing.push(_.difference( pr, all));
            }
            if ( _.isArray(su)) {
                // console.log(_.difference( pr, all));
            }
        });
        return _.uniq(_.flatten(missing));
    },

    chunkArray : function( arr ) {
        var oidsArrays = [];
        var i,j,chunk = 50;
        for (i=0, j=arr.length; i<j; i+=chunk) {
            oidsArrays.push(arr.slice(i,i+chunk));
        }
        // console.log("oidsArrays",oidsArrays);
        return oidsArrays;

    },

    findMissingSnapshots : function( snapshots, callback ) {

        var missing = app.getMissingSnapshots(snapshots);
        console.log("missing:",missing,missing.length);

        var oidsArrays = app.chunkArray(missing);

        var configs = _.map( oidsArrays, function(oArray) {
            return {
                fetch : ['ObjectID','_UnformattedID', '_TypeHierarchy', 'Predecessors','Successors','Blocked','ScheduleState','Name','Project','Iteration','FormattedID','Children'],
                hydrate :  ['_TypeHierarchy','ScheduleState'],
                find : {
                    'ObjectID' : { "$in" : oArray },
                    '__At' : 'current',
                    'Project' : { "$exists" : true},
                    'Project' : { "$ne" : null}
                }
            }
        });

        async.map(configs,app._snapshotQuery,function(err,results) {

            _.each(results,function(result) {
                _.each(result,function(s) {
                    snapshots.push(s);
                });
            });
            // callback(null,snapshots);
            if (app.getMissingSnapshots(snapshots).length>0)
                app.findMissingSnapshots(snapshots,callback);
            else
                callback(null,snapshots);
        });

    },

    // if a snapshot represents a parent story this will add key information, specifically the
    // iteration date of the last child.
    addChildStoryInformation : function( snapshots, callback ) {

        var epicSnapshots = _.filter(snapshots,function(s) {
            return s.get("Children").length > 0
        });

        // console.log("epics",epicSnapshots);

        async.map( epicSnapshots, app.leafNodeSnapshots,function(err,results) {

            // console.log("epic results:",results);
            _.each( results, function( leafNodes,i) {
                epicSnapshots[i].set("LeafNodes",leafNodes);
            });

            callback(null,snapshots);

        });

    },

    leafNodeSnapshots : function( epicSnapshot, callback ) {

        var config = {};

        config.fetch = ['ObjectID','_UnformattedID', '_TypeHierarchy', 'Predecessors','Successors','Blocked','ScheduleState','Name','Project','Iteration','FormattedID','Children'];
        config.hydrate =  ['_TypeHierarchy','ScheduleState'];
        config.find = {
            '_TypeHierarchy' : { "$in" : ["HierarchicalRequirement"]},
            '_ItemHierarchy' : { "$in" : [epicSnapshot.get("ObjectID")]},
            // '_ProjectHierarchy' : { "$in": [app.getContext().getProject().ObjectID]},
            'Children' : null,
            '__At' : 'current',
        };

        async.map([config],app._snapshotQuery,function(error,results) {
            callback(null,results[0]);
        });

    },

    getDependencySnapshots : function( callback ) {

        var that = this;
        var config = {};

        config.fetch = ['ObjectID','_UnformattedID', '_TypeHierarchy', 'Predecessors','Successors','Blocked','ScheduleState','Name','Project','Iteration','FormattedID','Children'];
        config.hydrate =  ['_TypeHierarchy','ScheduleState'];
        config.find = {
            '_TypeHierarchy' : { "$in" : ["HierarchicalRequirement"]} ,
            '_ProjectHierarchy' : { "$in": [app.getContext().getProject().ObjectID] } ,
            '__At' : 'current',
            '$or' : [
                {"Predecessors" : { "$exists" : true }}
                // {"Successors" : { "$exists" : true }},
            ]
        };

        // hide accepted stories
        if (app.hideAccepted)
            config.find['ScheduleState'] = { "$ne" : "Accepted" };

        async.map([config],app._snapshotQuery,function(error,results) {
            // console.log("snapshots:",results[0]);
            if (results[0].length>0)
                callback(null,results[0]);
            else
                callback("No Stories with dependencies in selected project scope",null);
        });

    },

    _snapshotQuery : function( config ,callback) {

        var storeConfig = {
            find    : config.find,
            fetch   : config.fetch,
            hydrate : config.hydrate,
            autoLoad : true,
            pageSize : 10000,
            limit    : 'Infinity',
            listeners : {
                scope : this,
                load  : function(store,snapshots,success) {
                    callback(null,snapshots);
                }
            }
        };
        var snapshotStore = Ext.create('Rally.data.lookback.SnapshotStore', storeConfig);

    },

    _linkFromSnapshot : function(snapshot) {
        var tpl = Ext.create('Ext.Template', "https://rally1.rallydev.com/#/detail/userstory/{objectid}", { compiled : true } );
        return tpl.apply({objectid:snapshot.get("ObjectID")});
    },

    _anchor : function(ref, content) {

        var tpl = Ext.create('Ext.Template',
            "{content}", { compiled : true } );
        return tpl.apply({ref:ref,content:content});

    },

    _renderNodeTemplate : function( node ) {

        var snapshot = node.snapshot;
        var id_style = snapshot.get("ScheduleState")==="Accepted" ? "accepted-story" : "";

        var name = app.truncateNameTo > 0 ? node.snapshot.get("Name").substring(0,app.truncateNameTo) : node.snapshot.get("Name");
        var project = _.find(app.projects, function(p) {
            return node.snapshot.get("Project") === p.get("ObjectID");
        });

        var projectName = project ? project.get("Name") : "Not Found!";
        var state_class = node.snapshot.get("Blocked") === true ? "status-blocked" : "";
        var project_class = project.get("ObjectID") !== app.project.ObjectID ?
            "other-project" : "";

        var date_class = "";
        // var iterationEndDate = app._iterationEndDate(node.snapshot.get("Iteration"));
        var iterationEndDate = app._iterationEndDate(app._getSnapshotIteration(node.snapshot));
        iterationEndDate = iterationEndDate ? moment(iterationEndDate).format("MM/DD/YYYY") : "";
        if (iterationEndDate) {
            if (node.status.length > 0)
                date_class = node.status[0].status;
        }
        // console.log("date:",iterationEndDate);

        var childCount = node.snapshot.get('Children').length > 0 ? " (" + node.snapshot.get('Children').length + ")" : "";

        var tpl = Ext.create('Ext.Template',
        "
" +
            "

{id} : {name} [{state}] {child_count}

" +
            "
Project:{project}
" +
            "
{date}
" +
        "

", { compiled : true } );

        return tpl.apply( {
            id_style : id_style,
            id_ref : app._linkFromSnapshot(snapshot),
            id : snapshot.get("FormattedID"),
            name : name,
            state : node.snapshot.get("ScheduleState").substring(0,1),
            state_class : state_class,
            project_class : project_class,
            project : projectName,
            date_class : date_class,
            date : iterationEndDate,
            child_count : childCount
        });

    },

    _createDagreGraph : function( nodes, links,callback ) {

        app.myMask.hide();
        var g = new dagre.Digraph();

        _.each(nodes, function(node){
            g.addNode(node.id, { label : app._renderNodeTemplate(node)});
        });

        _.each(links, function(link){
            g.addEdge(null, link.source.id, link.target.id, {label:""});
        });

        if (!_.isUndefined(app.x) && !_.isNull(app.x)) {
            app.x.destroy();
        }

        app.x = Ext.widget('container',{
            autoShow: true ,shadow: false,title: "",resizable: false,margin: 10
            ,html: '

'
            ,listeners: {
                resize: function(panel) {
                },
                afterrender : function(panel) {
                    var svg = d3.select("#demo-container").append("div").append("svg")
                    .attr("class","svg")
                    .attr("transform","translate(10,10)");

                    var renderer = new dagreD3.Renderer();
                    renderer.run(g, svg);
                    callback(null,nodes,links);
                }
            }
        });
        app.add(app.x);
        callback(null,nodes,links);

    },

    _formatGraphVizNode : function (node) {

        var name = app.truncateNameTo > 0 ? node.snapshot.get("Name").substring(0,app.truncateNameTo) : node.snapshot.get("Name");

        // replace & with + chars from name as they cause a problem when using the 'dot' command.
        name = name.replace(/\&/g,"+");

        // example : US15036 [label=<

US15036:Create C2P test cases for th
e reviewed + approved claim scenari
os[A]

Project:: CNG End-to-End Test

(9/16/2011)

>]
        var project = _.find(app.projects, function(p) {
            return node.snapshot.get("Project") === p.get("ObjectID");
        });

        if (_.isUndefined(project)||_.isNull(project)) {
            console.log("problem with project for:",node);
        }

        // var iterationEndDate = app._iterationEndDate(node.snapshot.get("Iteration"));
        var iterationEndDate = app._iterationEndDate(app._getSnapshotIteration(node.snapshot));

        var g = node.snapshot.get("FormattedID") + " ";
        g = g + " [label=<";
        g = g + "
";
        // row 1
        g = g + "
";
        g = g + "";
        // g = g + node.snapshot.get("FormattedID") + ":" + node.snapshot.get("Name") + " [" + node.snapshot.get("ScheduleState").substring(0,1) + "] ";
        g = g + node.snapshot.get("FormattedID") + ":" + name + " [" + node.snapshot.get("ScheduleState").substring(0,1) + "] ";
        g = g + "	";
        g = g + "
";
        // row 2
        g = g + "
";
        g = g + "";
        g = g + "Project:" + project.get("Name");
        g = g + "	";
        g = g + "
";
        // row 3
        g = g + "
";
        g = g + "";
        g = g + (iterationEndDate ? moment(iterationEndDate).format("MM/DD/YYYY") : "");
        g = g + "	";
        g = g + "
";

        g = g + "
";
        g = g + " >]\n";

        return g;
    },

    _createGraphViz : function( nodes, links, callback ) {

        var gv = "digraph G {\n     orientation=portrait\n    node [shape=plaintext, fontsize=14]\n";

        _.each(nodes,function(node) {
            gv = gv + app._formatGraphVizNode(node);
        });

        var gvLinks = "";

        _.each(links,function(link) {
            gvLinks = gvLinks + link.source.snapshot.get("FormattedID") +
                " -> " +
                link.target.snapshot.get("FormattedID") +
                ";\n";
        });

        gv = gv + gvLinks + " }";

        app.gv = gv;

        if (app.getSetting('showExportLink') === true) {

            var autoEl = Ext.create('Ext.Component',{
                itemId : 'autoel-export',
                autoEl : {
                    tag : 'a',
                    href : 'data:text/dot;charset=utf8,' + encodeURIComponent(app.gv),
                    download : 'export.dot',
                    html : 'Click to download dot file'
                }
            });

            console.log("adding export link");
            var link = app.down("#exportLink");
            var f;
            while(f = link.items.first()){
                link.remove(f, true);
            }
            link.add(autoEl);
        }

        callback(null,nodes,links);

    },

    _createLink : function(gvString) {
        var l = "Click to download dot file";
        // var l = "Click to download dot file";
        console.log(l);
        console.log(l.length);
        return l;
    },

    _createGraph : function( snapshots, callback ) {
        var that = this;
        var p = _.filter(snapshots,function(rec) { return _.isArray(rec.get("Predecessors"));});
        var s = _.filter(snapshots,function(rec) { return _.isArray(rec.get("Successors"));});

        // create the set of node elements
        var nodes = _.map( snapshots, function(snap) {
            if (_.isArray(snap.get("Predecessors"))||_.isArray(snap.get("Successors"))) {
                return { id : snap.get("ObjectID"), snapshot : snap };
            } else {
                return null;
            }
        });
        nodes = _.compact(nodes);
        var links = [];
        _.each(nodes, function(node) {
            _.each(node.snapshot.get("Predecessors"), function(pred) {
                var target = _.find(nodes,function(node) { return node.id == pred;});
                // may be undefined if pred is out of project scope, need to figure out how to deal with that
                if (!_.isUndefined(target)) {
                    // var dupFound = _.find(links,function(link){
                    //     return link.source.id === node.id && link.target.id === target.id;
                    // });
                    // console.log("dup:",dupFound,node.id,target.id);

                    links.push({ source : node, target : target  });
                } else {
                    console.log("unable to find pred:",pred);
                }
            });
        });
        callback(null,nodes,links);

    },

    _setFilterNodes : function(nodes,links,callback) {

        _.each(links,function(link) {
            // is this link source the target of another link ?
            var targets = _.filter(links,function(targetLink) {
                return link.source.id === targetLink.target.id;
            });
            // if not then we add it to the filter list.
            if (targets.length===0) {
                app.filterItems.push( { id: link.source.id, name: link.source.snapshot.get("FormattedID") + ": "+link.source.snapshot.get("Name") });
            }
        });

        app.filterItems = _.uniq(app.filterItems,"name");
        // app.filterItems = _.sortBy(app.filterItems,"name");
        // console.log("filter store",app.filterItems);
        app.filterStore.sort();
        app.filterStore.reload();

        callback(null,nodes,links);

    },

    // recursive method to walk the list of links
    _createLinkListForNode : function( node, list, nodes, links ) {

        list.push(node);
        // console.log(" walk to node:",node.id);
        var nodeLinks = _.filter(links,function(link) { return link.source.id === node.id; });
        // console.log("\tlinks:", _.map(nodeLinks,function(n){return n.target.id;}));
        _.each(nodeLinks, function(ln) {
            app._createLinkListForNode( ln.target, list, nodes, links);
        });

    },

    _createNodeList : function( nodes, links, callback ) {
        _.each(nodes, function(node) {
            var list = [];
            app._createLinkListForNode( node, list, nodes, links );
            node.list = list;
        });
        callback(null,nodes, links);
    },

    // the status for the node is based on its downstream dependencies in the list
    _createNodeStatus : function( nodes, links, callback ) {

        _.each(nodes, function(node) {
            _.each( node.list, function(listNode,i) {
                if (!node.status) node.status = [];

                if (i > 0) {
                    var status = app._createStatusForNodes( node, listNode );
                    if ( status !== "status-good" )
                        node.status.push({ status : status, target : listNode });
                    console.log("node status:",node);
                }
            });
        });
        callback( null, nodes, links );
    },

    _getIteration : function(iid) {

        var iteration = _.find( app.iterations,
            function(it){
                // console.log("iid",iid,it.get("ObjectID"));
                return (iid === it.get("ObjectID"));
            });

        return iteration;

    },

    _iterationEndDate : function(iid) {
        var iteration = app._getIteration(iid);
        return iteration ?
                    Rally.util.DateTime.fromIsoString(iteration.raw.EndDate)
                    : null;
    },

    // used to get the iteration on the snapshot. if an epic snapshot it will be last iteration
    // of the leafnodes.
    _getSnapshotIteration : function(snapshot) {
        var leafNodes = snapshot.get("LeafNodes");

        // if child snapshot then just return the iteration
        if (_.isUndefined(leafNodes)||_.isNull(leafNodes)||leafNodes.length===0) {
            return snapshot.get("Iteration");
        }
        // otherwise return the last of the leaf nodes based on iteration end date.
        var max = _.max(leafNodes, function(leaf) {
            var i = leaf.get("Iteration");
            return app._iterationEndDate(i);
        });
        // console.log("max",max);
        return max.get("Iteration");
    },

    _createStatusForNodes : function( src, tgt ) {

        // is scheduled ?
        // var srcIteration = src.snapshot.get("Iteration");
        var srcIteration = app._getSnapshotIteration(src.snapshot);
        // var tgtIteration = tgt.snapshot.get("Iteration");
        var tgtIteration = app._getSnapshotIteration(tgt.snapshot);
        if ( _.isUndefined(tgtIteration) || _.isNull(tgtIteration) || tgtIteration === "" )
            // return "yellow";
            return "status-not-scheduled";
        // late ?
        if (!( _.isUndefined(srcIteration) || _.isNull(srcIteration)) &&
            !( _.isUndefined(tgtIteration) || _.isNull(tgtIteration))) {
            if ( app._iterationEndDate(tgtIteration) > app._iterationEndDate(srcIteration) )
                return "status-bad";
        }

        return "status-good";

    },

    filterSuccessor : function(combo,records,eOpts) {

        var selected = records[0];
        var root = _.find(app.nodes,function(node) { return node.id === selected.get("id");});

        var newNodes = [];
        var newLinks = [];

        var walkTheLine = function(root, newNodes, newLinks) {
            if (_.find(newNodes,function(n){return n.id===root.id;})===undefined)
                newNodes.push(root);
            var links = _.filter(app.links,function(link) { return link.source.id === root.id;});
            _.each(links,function(link){
                newLinks.push(link);
                walkTheLine(link.target,newNodes,newLinks);
            });
        }

        walkTheLine( root, newNodes, newLinks);

        app._createDagreGraph(newNodes,newLinks,function(err,nodes,links) {

            console.log("filtering graph viz");
            app._createGraphViz(newNodes,newLinks,function(err,n,l) {

            });

        })
    }

});


text:
var tests = {
    "Should not break ng-click": function (file) {
        return function () {
            browser.get("http://localhost:9000/test/fixtures/click" + file + ".html");
            element(by.css("button#test1")).click();
            expect(element(by.css("#field")).getText()).toBe("Success");
        };
    },

    "Should not break ng-click for translated strings": function (file) {
        return function () {
            browser.get("http://localhost:9000/test/fixtures/click" + file + ".html");
            element(by.css("button#test2")).click();
            expect(element(by.css("#field")).getText()).toBe("Success");
        };
    },

    "Should compile ng-click": function (file) {
        return function () {
            browser.get("http://localhost:9000/test/fixtures/click" + file + ".html");
            element(by.css("#test3 button")).click();
            expect(element(by.css("#field")).getText()).toBe("Success");
        };
    }
};

describe("Click", function () {
    for (var key in tests) {
        it(key, tests[key](""));
    }
});

describe("Click (no jQuery)", function () {
    for (var key in tests) {
        it(key, tests[key]("-nojquery"));
    }
});


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;
use app\module\handbook\models\DisciplineList;
use app\module\handbook\models\Cathedra;
use app\module\handbook\models\LessonsType;
use app\module\handbook\models\Groups;
use app\module\handbook\models\ClassRooms;
use app\module\handbook\models\Housing;
use app\module\handbook\models\Faculty;

/* @var $this yii\web\View */
/* @var $model app\module\handbook\models\Discipline */
/* @var $form yii\widgets\ActiveForm */
    $classes = ClassRooms::find()->orderBy('classrooms_number ASC')->all();
    foreach ($classes as $cl){
        $housing = Housing::findOne(['housing_id' => $cl['id_housing']]);
        $classroomsArray[$cl['classrooms_id']] = $cl['classrooms_number'].' - '.$housing['name'];
    }

    $all_faculty = Faculty::find()->orderBy('faculty_name ASC')->all();

foreach($all_faculty as $af){
    $tmp_cathedra = Cathedra::find()->where(['id_faculty' => $af['faculty_id']])->orderBy('cathedra_name ASC')->all();
    foreach($tmp_cathedra as $tc){
        $all_cathedra[$tc['cathedra_id']] = $tc['cathedra_name']." / ".$af['faculty_name'];
    }
}
?>

    <?php $form = ActiveForm::begin(); ?>

    <?=
        $form->field($model, 'id_discipline')->widget(Select2::classname(), [
            'data' => ArrayHelper::map(DisciplineList::find()->orderBy('discipline_name ASC')->all(), 'discipline_id','discipline_name'),
            'language' => 'uk',
            'pluginOptions' => [
                'allowClear' => true
            ],
        ])->label('Дисципліна');
    ?>

    <?=
        $form->field($model, 'id_cathedra')->widget(Select2::classname(), [
            'data' => $all_cathedra,//ArrayHelper::map(Cathedra::find()->all(), 'cathedra_id','cathedra_name'),
            'language' => 'uk',
            'pluginOptions' => [
                'allowClear' => true
            ],
        ])->label('Кафедра');
    ?>

    <?=
        $form->field($model, 'id_lessons_type')->widget(Select2::classname(), [
            'data' => ArrayHelper::map(LessonsType::find()->all(), 'id','lesson_type_name'),
            'language' => 'uk',
            'pluginOptions' => [
                'allowClear' => true
            ],
        ])->label('Тип заняття');
    ?>

    <?php
        echo Html::label("Групи");
        echo Select2::widget([
            'model' => $model,
            'attribute' => 'mgroups',
            'language' => 'ru',
            'data' => ArrayHelper::map(Groups::find()->all(),'group_id','main_group_name'),
            'options' => ['multiple' => true]
        ]);
    ?>

    <?=
        $form->field($model, 'id_classroom')->widget(Select2::classname(), [
            'data' => $classroomsArray,
            'language' => 'uk',
            'pluginOptions' => [
                'allowClear' => true
            ],
            'options' => ['placeholder' => ' '],
        ])->label('Аудиторія');
    ?>

    <?= $form->field($model, 'course')->textInput() ?>

    <?= $form->field($model, 'hours')->textInput() ?>

    <?= $form->field($model, 'semestr_hours')->textInput() ?>

    <?= $form->field($model, 'id_edbo')->textInput() ?>

    <?= $form->field($model, 'id_deanery')->textInput() ?>

        <?= Html::submitButton($model->isNewRecord ? 'Створити' : 'Оновити', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
#ifndef SVGImage_h
#define SVGImage_h

#include "platform/graphics/Image.h"
#include "platform/heap/Handle.h"
#include "platform/weborigin/KURL.h"

namespace blink {

class FrameView;
class Page;
class RenderBox;
class SVGImageChromeClient;
class SVGImageForContainer;

class SVGImage final : public Image {
public:
    static PassRefPtr<SVGImage> create(ImageObserver* observer)
    {
        return adoptRef(new SVGImage(observer));
    }

    static bool isInSVGImage(const Node*);

    RenderBox* embeddedContentBox() const;

    virtual bool isSVGImage() const override { return true; }
    virtual IntSize size() const override { return m_intrinsicSize; }
    void setURL(const KURL& url) { m_url = url; }

    virtual bool currentFrameHasSingleSecurityOrigin() const override;

    virtual void startAnimation(CatchUpAnimation = CatchUp) override;
    virtual void stopAnimation() override;
    virtual void resetAnimation() override;

    virtual PassRefPtr<NativeImageSkia> nativeImageForCurrentFrame() override;

    // Returns the SVG image document's frame.
    FrameView* frameView() const;

    // Does the SVG image/document contain any animations?
    bool hasAnimations() const;

private:
    friend class AXRenderObject;
    friend class SVGImageChromeClient;
    friend class SVGImageForContainer;

    virtual ~SVGImage();

    virtual String filenameExtension() const override;

    virtual void setContainerSize(const IntSize&) override;
    IntSize containerSize() const;
    virtual bool usesContainerSize() const override { return true; }
    virtual void computeIntrinsicDimensions(Length& intrinsicWidth, Length& intrinsicHeight, FloatSize& intrinsicRatio) override;

    virtual bool dataChanged(bool allDataReceived) override;

    // FIXME: SVGImages are underreporting decoded sizes and will be unable
    // to prune because these functions are not implemented yet.
    virtual void destroyDecodedData(bool) override { }

    // FIXME: Implement this to be less conservative.
    virtual bool currentFrameKnownToBeOpaque() override { return false; }

    SVGImage(ImageObserver*);
    virtual void draw(GraphicsContext*, const FloatRect& fromRect, const FloatRect& toRect, CompositeOperator, blink::WebBlendMode) override;
    void drawForContainer(GraphicsContext*, const FloatSize, float, const FloatRect&, const FloatRect&, CompositeOperator, blink::WebBlendMode);
    void drawPatternForContainer(GraphicsContext*, const FloatSize, float, const FloatRect&, const FloatSize&, const FloatPoint&,
        CompositeOperator, const FloatRect&, blink::WebBlendMode, const IntSize& repeatSpacing);

    OwnPtr<SVGImageChromeClient> m_chromeClient;
    OwnPtrWillBePersistent<Page> m_page;
    IntSize m_intrinsicSize;
    KURL m_url;
};

DEFINE_IMAGE_TYPE_CASTS(SVGImage);

class ImageObserverDisabler {
    WTF_MAKE_NONCOPYABLE(ImageObserverDisabler);
public:
    ImageObserverDisabler(Image* image)
        : m_image(image)
    {
        ASSERT(m_image->imageObserver());
        m_observer = m_image->imageObserver();
        m_image->setImageObserver(0);
    }

    ~ImageObserverDisabler()
    {
        m_image->setImageObserver(m_observer);
    }
private:
    Image* m_image;
    ImageObserver* m_observer;
};

}

#endif // SVGImage_h


text:
let types = ['t500x500', 'crop', 't300x300', 'large', 't67x67', 'badge', 'small', 'tiny', 'mini'];

module.exports = (artwork_url: string, selection: string): string => {
  let replaceThis;
  types.forEach(type => {
    if (artwork_url.indexOf(type) > -1) {
      replaceThis = type;
    }
  });
  return artwork_url.replace(replaceThis, selection);
};


text:
echo -n "Enter the database hostname > "
read database_hostname
echo -n "Enter the database username > "
read database_username

echo "creating database"
createdb -h $database_hostname samples_database -U postgres

echo "creating tables"
psql -h $database_hostname -U $database_username -d samples_database -a -f "script.sql"

echo "you can check database creation using the following command psql -h $database_hostname -U $database_username -d samples_database"
echo " you can check that the table exists using \list and \dt"
echo "you can check that the colomns are correct using : select column_name, data_type, character_maximum_length from INFORMATION_SCHEMA.COLUMNS where table_name = 'samples_dataset';"


text:
package net.achalaggarwal.workerbee.dr.selectfunction;

import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

public class AllStarSFTest {
  @Test
  public void shouldGenerateStar(){
    assertThat(new AllStarSF().generate(), is("*"));
  }
}


text:
<?php

namespace Site\MainBundle\Entity\Repository;

use Doctrine\ORM\EntityRepository;

class PageRepository extends EntityRepository
{
    public function findAll(){
        return $this->findBy(array('hide' => false), array('position' => 'ASC'));
    }
}


text:
import { React, Component, getNode, merge } from 'ive-f';
import { SetPosition, UpdateNode, SetNode } from '../action/node';
import { SetContext } from '../action/context';

import UpdateNodeContext from './node/update';
import NodeEdgeContext from './node/edge';

/**
 * A diagram represents a graph of arbitrary connected
 * edges and nodes. In this case it is used to render
 * UML diagrams.
 */
export default class Diagram extends Component {
	constructor (props) {
		super(props);
		this.state = {
			context: null,
			offset: { x: 0, y: 0 },
			style: {},
			dragging: false,
			mousePos: null,
			selection: []
		};

		this.own('handleMouseDown', 'handleMouseUp', 'handleMouseMove');
	}

	componentDidUpdate () {
		let { context } = this.state;

		if (context) {
			context.clearRect(0, 0, 2000, 2000);
		}

		if (this.props.diagram && context) {
			this.renderTitle(context);
			this.renderNodes(context);
			this.renderEdges(context);
		}
	}

	componentDidMount () {
		let node = getNode(this);
		let { left, top, width, height } =  node.getBoundingClientRect();
		let context = node.getContext('2d');
		let style = { width, height };
		let offset = { x: left, y: top };

		node.addEventListener('mousedown', this.handleMouseDown);
		node.addEventListener('mouseup', this.handleMouseUp);
		this.setState({ context, style, offset });
		SetPosition.trigger(merge(style, offset));
	}

	componentWillUnmount () {
		getNode(this).removeEventListener('mousedown', this.handleMouseDown);
		getNode(this).removeEventListener('mouseup', this.handleMouseUp);
	}

	handleMouseDown (event) {
		let { offset } = this.state;
		let x = event.pageX - offset.x;
		let y = event.pageY - offset.y;

		for (let node of this.props.nodes) {
			if (node.x <= x && node.y <= y && node.x + node.width >= x && node.y + node.width >= y) {
				if (event.ctrlKey && this.props.node) {
					SetContext.trigger({ Component: NodeEdgeContext, data: {
						source: this.props.node, target: node, diagram: this.props.diagram
					} });
				} else {
					getNode(this).addEventListener('mousemove', this.handleMouseMove);
					this.setState({ dragging: true });
					SetContext.trigger({ Component: UpdateNodeContext, data: { node } });
					UpdateNode.trigger(node);
				}
				break;
			}
		}
	}

	handleMouseMove (event) {
		let { dragging, mousePos, offset } = this.state;
		let { node } = this.props;
		let x = event.pageX - offset.x;
		let y = event.pageY - offset.y;

		if (node && dragging && mousePos) {
			node.x -= (mousePos.x - x);
			node.y -= (mousePos.y - y);
			UpdateNode.trigger(node);
		}
		this.setState({ mousePos: { x, y } });
	}

	handleMouseUp () {
		getNode(this).removeEventListener('mousemove', this.handleMouseMove);
		this.setState({ dragging: false, mousePos: null });
	}

	renderTitle (context) {
		let { diagram } = this.props;

		context.save();
		context.font = '24px arial';
		context.fillText(`Diagram: ${diagram.name}`, 20, 35);
		context.restore();
	}

	getNode (nodeId) {
		return this.props.nodes.filter(node => {
			return node.id == nodeId;
		})[0];
	}

	renderNodes (context) {
		let { nodes, node, diagram } = this.props;

		context.save();
		context.font = '15px arial';
		context.lineWidth = 0.5;

		nodes.filter(node => {
			return node.diagramId == diagram.id;
		}).map(current => {
			let { id, name, x, y, width, height, type } = current;

			if (x % 1 == 0) x += 0.5;
			if (y % 1 == 0) y += 0.5;

			if (node && node.id == id) {
				context.strokeStyle = 'black';
				context.fillStyle = 'black';
			} else {
				context.strokeStyle = 'rgb(100, 100, 100)';
				context.fillStyle = 'rgb(100, 100, 100)';
			}

			context.beginPath();
			context.rect(x, y, width, height);
			context.fillText(type, x, y - 5);
			context.moveTo(x, y + 30);
			context.lineTo(x + width, y + 30);
			context.fillText(name || '', x + 5, y + 20);
			context.stroke();
			context.closePath();
		});
		context.restore();
	}

	renderEdges (context) {
		let { edges, diagram } = this.props;

		context.save();
		context.strokeStyle = 'rgb(100, 100, 100)';

		edges.filter(edge => {
			return edge.diagramId == diagram.id;
		}).map(edge => {
			let source = this.getNode(edge.source.id);
			let target = this.getNode(edge.target.id);
			context.beginPath();
			context.moveTo(source.x, source.y);
			context.lineTo(target.x, target.y);
			context.stroke();
			context.closePath();
		});
		context.restore();
	}

	render () {
		let { style } = this.state;

		return <canvas className="diagram"
					   style={style}
					   width={style.width}
					   height={style.height} />
	}
}


text:
<?php

/**
 * @file
 * Contains \Drupal\scheduled_updates\Form\ScheduledUpdateTypeForm.
 */

namespace Drupal\scheduled_updates\Form;

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Drupal\scheduled_updates\ClassUtilsTrait;
use Drupal\scheduled_updates\FieldUtilsTrait;

/**
 * Class ScheduledUpdateTypeForm.
 *
 * @package Drupal\scheduled_updates\Form
 */
class ScheduledUpdateTypeForm extends ScheduledUpdateTypeBaseForm {

  use FieldUtilsTrait;

  use ClassUtilsTrait;

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $form = parent::form($form, $form_state);
    $form['label'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Label'),
      '#maxlength' => 255,
      '#default_value' => $this->entity->label(),
      '#description' => $this->t("Label for the Scheduled update type."),
      '#required' => TRUE,
      '#weight' => -110,
    );

    $form['id'] = array(
      '#type' => 'machine_name',
      '#default_value' => $this->entity->id(),
      '#machine_name' => array(
        'exists' => '\Drupal\scheduled_updates\Entity\ScheduledUpdateType::load',
      ),
      '#disabled' => !$this->entity->isNew(),
      '#weight' => -100,
    );

    $default_type = $this->getCurrentEntityType($form_state);

    $disabled = !$this->entity->isNew();
    $form['update_entity_type'] = [
      '#type' => 'select',
      '#title' => $this->t('Entity Type'),
      '#description' => $this->t('The entity type to update. This cannot be changed after this type is created.'),
      '#options' => $this->entityTypeOptions(),
      '#default_value' => $default_type,
      '#required' => TRUE,
      // @todo why doesn't this work?
      '#disabled' => $disabled,
      '#weight' => -90,
    ];
    // @todo Remove when bug is fixed.
    if (!$form['update_entity_type']['#disabled']) {
      // Just to duplicate issues on d.o for now.
      $form['update_entity_type']['#description'] .= '
**KNOWN BUG** : Ajax error when selecting one entity type and then selecting another: https://www.drupal.org/node/2643934';
    }
    $form['update_entity_type'] += $this->typeDependentAjax();

    $form['field_map'] = $this->createFieldMapElements();
    /* You will need additional form elements for your custom properties. */

    return $form;
  }

  /**
   * Create select element entity type options.
   *
   * @return array
   */
  protected function entityTypeOptions() {
    $options[''] = '';
    foreach ($this->entityTypeManager->getDefinitions() as $entity_id => $entityTypeInterface) {
      if ($entity_id == 'scheduled_update') {
        // Don't allow updating of updates! Inception!
        continue;
      }
      if (is_subclass_of($entityTypeInterface->getClass(), 'Drupal\Core\Entity\ContentEntityInterface')) {
        $options[$entity_id] = $entityTypeInterface->getLabel();
      }
    }
    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $status = parent::doSave($form, $form_state);
    $clone_field = $form_state->getValue('clone_field');

    $multi_field = FALSE;
    if ($clone_field) {
      if ($clone_field != 'multiple-field') {
        $this->cloneSingleField($this->entity->getUpdateEntityType(), $clone_field, $form_state);
      }
      else {
        $multi_field = TRUE;
      }
    }

    switch ($status) {
      case SAVED_NEW:
        if ($multi_field) {
          drupal_set_message($this->t('Select fields to add to these updates'));
          $form_state->setRedirectUrl($this->entity->urlInfo('clone-fields'));
        }
        else {
          $form_state->setRedirectUrl(Url::fromRoute("entity.entity_form_display.scheduled_update.default", array(
            'scheduled_update_type' => $this->entity->id(),
          )));
        }
        break;

      default:
        drupal_set_message($this->t('Saved the %label Scheduled update type.', [
          '%label' => $this->entity->label(),
        ]));
        $form_state->setRedirectUrl($this->entity->urlInfo('collection'));
    }

  }

  /**
   * Create form elements to update field map.
   *
   * @return array
   * @internal param array $form
   * @internal param $scheduled_update_type
   *
   */
  protected function createFieldMapElements() {
    if ($this->entity->isNew()) {
      return [];
    }
    $field_map_help = 'Select the destination fields for this update type.'
      . ' Not all field have to have destinations if you using them for other purposes.';
    $elements = [
      '#type' => 'details',
      '#title' => 'destination fields',
      '#description' => $this->t($field_map_help),
      '#tree' => TRUE,
    ];
    $source_fields = $this->getSourceFields($this->entity);

    $field_map = $this->entity->getFieldMap();

    foreach ($source_fields as $source_field_id => $source_field) {
      $destination_fields_options = $this->getDestinationFieldsOptions($this->entity->getUpdateEntityType(), $source_field);
      $elements[$source_field_id] = [
        '#type' => 'select',
        '#title' => $source_field->label(),
        '#options' => ['' => $this->t("(Not mapped)")] + $destination_fields_options,
        '#default_value' => isset($field_map[$source_field_id]) ? $field_map[$source_field_id] : '',
      ];
    }
    return $elements;
  }

  public function validateForm(array &$form, FormStateInterface $form_state) {
    parent::validateForm($form, $form_state);
    $runner_settings = $form_state->getValue('update_runner');
    $update_runner = $this->createRunnerInstance($runner_settings, $form_state);
    $update_runner->validateConfigurationForm($form, $form_state);
  }

  /**
   * Overridden to provide multi-field choice.
   *
   * This option will route the user to the clone fields page.
   * @todo should this option always be available?
   *
   * {@inheritdoc}
   */
  protected function createCloneFieldSelect(array $form, FormStateInterface $form_state) {
    $elements = parent::createCloneFieldSelect($form, $form_state);
    if (isset($elements['clone_field']['#options'])) {
      $elements['clone_field']['#options']['multiple-field'] = '(' . $this->t('Create a multiple field update') . ')';
    }
    return $elements;
  }

}


text:
def pad!(array, min_size, value = nil) #destructive
  if array.length >= min_size || min_size == 0
    return array
  else
    ans = min_size - array.length
    ans.times{array.push(value)}
  end
  return array
end

# p pad!([1,2,3],2)

 def pad(array, min_size, value = nil) #non-destructive
   final_array = []
   if array.length >= min_size || min_size == 0
     return array
   else
     final_array = Array.new(min_size - array.length, value)
     ans = array + final_array
   end
   return ans
 end

# p pad([1,2,3,4], 6 ,)

# 3. Refactored Solution
 def pad!(array, min_size, value = nil) #destructive
   if array.length >= min_size || min_size == 0
     return array
   else
     array.insert(array.last, *Array.new([ min_size - array.length].max, value))
   end
   return array
 end

 def pad(array, min_size, value = nil) #non-destructive
   final_array = []
   if array.length >= min_size || min_size == 0
     return array.clone
   else
     final_array = array.clone.fill(value, array.length...min_size)
   end
   p array
   return final_array
 end

# 4. Reflection

# Were you successful in breaking the problem down into small steps?

# My partner and I broke the problem down into manageable steps as seen in our pseudocode. This helped us
# break the problem into if/else statements that were easy to solve on their own.

# Once you had written your pseudocode, were you able to easily translate it into code? What difficulties and successes did you have?

#Very easy. The only difficulty we ran into was ensuring the non-descructive method didn't delete the initial code.

# Was your initial solution successful at passing the tests? If so, why do you think that is? If not, what were the errors you encountered and what did you do to resolve them?

# Our first solution didn't pass because we weren't created a copy of the initial array before declaring a new array.

# When you refactored, did you find any existing methods in Ruby to clean up your code?

# Yes. We used .clone, .fill, and .insert

# How readable is your solution? Did you and your pair choose descriptive variable names?

# Yes we did. Our code is very readable and easy to understand

# What is the difference between destructive and non-destructive methods in your own words?

# In my own words, a descructive method destroys the original copy and creates a new copy.
# A non-descrutive method keeps the original copy while creating a new one.


text:
package org.cybergarage.upnp.ssdp;

import java.net.InetAddress;
import java.util.*;

import org.cybergarage.net.*;

import org.cybergarage.upnp.*;

public class SSDPNotifySocketList extends Vector
{
	private static final long serialVersionUID = 1L;

	////////////////////////////////////////////////
	//	Constructor
	////////////////////////////////////////////////

	private InetAddress[] binds = null;

	public SSDPNotifySocketList() {
	}

	/**
	 *
	 * @param binds The host to bind the service <tt>null</tt> means to bind to default.
	 * @since 1.8
	 */
	public SSDPNotifySocketList(InetAddress[] binds){
		this.binds=binds;
	}

	////////////////////////////////////////////////
	//	Methods
	////////////////////////////////////////////////

	public SSDPNotifySocket getSSDPNotifySocket(int n)
	{
		return (SSDPNotifySocket)get(n);
	}

	////////////////////////////////////////////////
	//	ControlPoint
	////////////////////////////////////////////////

	public void setControlPoint(ControlPoint ctrlPoint)
	{
		int nSockets = size();
		for (int n=0; n<nSockets; n++) {
			SSDPNotifySocket sock = getSSDPNotifySocket(n);
			sock.setControlPoint(ctrlPoint);
		}
	}

	////////////////////////////////////////////////
	//	Methods
	////////////////////////////////////////////////

	public boolean open(){
		InetAddress[] binds=this.binds ;
		String[] bindAddresses;
		if(binds!=null){
			bindAddresses = new String[binds.length];
			for (int i = 0; i < binds.length; i++) {
				bindAddresses[i] = binds[i].getHostAddress();
			}
		}else{
			int nHostAddrs = HostInterface.getNHostAddresses();
			bindAddresses = new String[nHostAddrs];
			for (int n=0; n<nHostAddrs; n++) {
				bindAddresses[n] = HostInterface.getHostAddress(n);
			}
		}

		for (int i = 0; i < bindAddresses.length; i++) {
			if(bindAddresses[i]!=null){
				SSDPNotifySocket ssdpNotifySocket = new SSDPNotifySocket(bindAddresses[i]);
				add(ssdpNotifySocket);
			}
		}
		return true;
	}

	public void close()
	{
		int nSockets = size();
		for (int n=0; n<nSockets; n++) {
			SSDPNotifySocket sock = getSSDPNotifySocket(n);
			sock.close();
		}
		clear();
	}

	////////////////////////////////////////////////
	//	Methods
	////////////////////////////////////////////////

	public void start()
	{
		int nSockets = size();
		for (int n=0; n<nSockets; n++) {
			SSDPNotifySocket sock = getSSDPNotifySocket(n);
			sock.start();
		}
	}

	public void stop()
	{
		int nSockets = size();
		for (int n=0; n<nSockets; n++) {
			SSDPNotifySocket sock = getSSDPNotifySocket(n);
			sock.stop();
		}
	}

}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bg" >

    <LinearLayout
        android:id="@+id/llHighliter"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_hover"
        android:orientation="horizontal"
        android:visibility="gone" >
    </LinearLayout>
    <!-- @drawable/bg_hover -->

    <ViewFlipper
        android:id="@+id/view_flipper"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/llFooter" >

        <RelativeLayout
            android:id="@+id/rlViewFlipper1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <include layout="@layout/flipper_set_alarm" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/rlViewFlipper2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <include layout="@layout/flipper_list_alarms" />
        </RelativeLayout>

        <!--
        <RelativeLayout
            android:id="@+id/rlViewFlipper3"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
        </RelativeLayout>

           <RelativeLayout
            android:id="@+id/rlViewFlipper4"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >
        </RelativeLayout>
        -->
    </ViewFlipper>

    <LinearLayout
        android:id="@+id/llFooter"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal"
        android:weightSum="2" >

        <Button
            android:id="@+id/btnSetAlarm"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_margin="2dp"
            android:layout_weight="1"
            android:background="@color/bg_color_btn"
            android:padding="5dp"
            android:text="Set Alarm"
            android:textColor="@color/txt_color_white" />

        <Button
            android:id="@+id/btnViewAlarms"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_margin="2dp"
            android:layout_weight="1"
            android:background="@color/bg_color_btn"
            android:padding="5dp"
            android:text="View Alarms"
            android:textColor="@color/txt_color_white" />
    </LinearLayout>

    <HorizontalScrollView
        android:id="@+id/hzScroll"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_alignParentBottom="true"
        android:visibility="gone" >

        <!--
             <LinearLayout
            android:id="@+id/llFooter"
            android:layout_width="fill_parent"
            android:layout_height="100dp"
            android:weightSum="2"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btnSetAlarm"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="fill_parent"
                android:layout_margin="2dp"
                android:background="@color/bg_color_btn"
                android:padding="5dp"
                android:text="Set Alarm"
                android:textColor="@color/txt_color_white" />

            <Button
                android:id="@+id/btnViewAlarms"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:layout_height="fill_parent"
                android:layout_margin="2dp"
                android:background="@color/bg_color_btn"
                android:padding="5dp"
                android:text="View Alarms"
                android:textColor="@color/txt_color_white" />
        -->

        <!--
            <Button
                android:id="@+id/btnSetEvents"
                android:layout_width="100dp"
                android:layout_height="fill_parent"
                android:layout_margin="2dp"
                android:background="@color/bg_color_btn"
                android:padding="5dp"
                android:text="Set Events"
                android:textColor="@color/txt_color_white"
                android:visibility="gone" />

            <Button
                android:id="@+id/btnViewEvents"
                android:layout_width="100dp"
                android:layout_height="fill_parent"
                android:layout_margin="2dp"
                android:background="@color/bg_color_btn"
                android:padding="5dp"
                android:text="View Events"
                android:visibility="gone"
                android:textColor="@color/txt_color_white" />
        -->
        <!-- </LinearLayout> -->
    </HorizontalScrollView>

    <TextView
        android:id="@+id/tvhighliter2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="#00000000"
        android:gravity="center_horizontal|bottom"
        android:paddingTop="20dp"
        android:text="I"
        android:textColor="@color/txt_color_white"
        android:textSize="50sp"
        android:visibility="gone" />

</RelativeLayout>


text:
title: "Modules"
is_beta: true
nav-parent_id: tableapi
nav-pos: 70
---

Modules allow users to extend Flink's built-in objects, such as defining functions that behave like Flink
built-in functions. They are pluggable, and while Flink provides a few pre-built modules, users can write
their own.

For example, users can define their own geo functions and plug them into Flink as built-in functions to be used in
Flink SQL and Table APIs. Another example is users can load an out-of-shelf Hive module to use Hive built-in
functions as Flink built-in functions.

* This will be replaced by the TOC
{:toc}

## Module Types

### CoreModule

`CoreModule` contains all of Flink's system (built-in) functions and is loaded by default.

### HiveModule

The `HiveModule` provides Hive built-in functions as Flink's system functions to SQL and Table API users.
Flink's [Hive documentation]({% link dev/table/connectors/hive/hive_functions.md %}) provides full details on setting up the module.

### User-Defined Module

Users can develop custom modules by implementing the `Module` interface.
To use custom modules in SQL CLI, users should develop both a module and its corresponding module factory by implementing
the `ModuleFactory` interface.

A module factory defines a set of properties for configuring the module when the SQL CLI bootstraps.
Properties are passed to a discovery service where the service tries to match the properties to
 a `ModuleFactory` and instantiate a corresponding module instance.

## Namespace and Resolution Order

Objects provided by modules are considered part of Flink's system (built-in) objects; thus, they don't have any namespaces.

When there are two objects of the same name residing in two modules, Flink always resolves the object reference to the one in the 1st loaded module.

## Module API

### Loading and unloading a Module

Users can load and unload modules in an existing Flink session.

{% highlight java %}
tableEnv.loadModule("myModule", new CustomModule());
tableEnv.unloadModule("myModule");
{% endhighlight %}

All modules defined using YAML must provide a `type` property that specifies the type.
The following types are supported out of the box.

      Catalog
      Type Value

        CoreModule
        core

        HiveModule
        hive

{% highlight yaml %}
modules:
   - name: core
     type: core
   - name: myhive
     type: hive
{% endhighlight %}

### List Available Modules

{% highlight java %}
tableEnv.listModules();
{% endhighlight %}

{% highlight sql %}
Flink SQL> SHOW MODULES;
{% endhighlight %}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>UltrasonicSensor</title>
<meta name="date" content="2015-07-30">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.qualcomm.robotcore.hardware

Class UltrasonicSensor

java.lang.Object

com.qualcomm.robotcore.hardware.UltrasonicSensor

All Implemented Interfaces:

HardwareDevice

public abstract class UltrasonicSensor
extends java.lang.Object
implements HardwareDevice

Constructor Summary

Constructors

Constructor and Description

UltrasonicSensor()

Method Summary

All Methods Instance Methods Abstract Methods Concrete Methods

Modifier and Type
Method and Description

abstract double
getUltrasonicLevel()

Get the Ultrasonic levels from this sensor

abstract java.lang.String
status()

Status of this sensor, in string form

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Methods inherited from interface com.qualcomm.robotcore.hardware.HardwareDevice

close, getConnectionInfo, getDeviceName, getVersion

Constructor Detail

UltrasonicSensor

public UltrasonicSensor()

Method Detail

getUltrasonicLevel

public abstract double getUltrasonicLevel()

Get the Ultrasonic levels from this sensor

Returns:

ultrasonic levels

status

public abstract java.lang.String status()

Status of this sensor, in string form

Returns:

status

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

namespace Solution10\Data\Tests\Stubs;

use Solution10\Data\HasMapper;
use Solution10\Data\MapperInterface;

class UserWithMapper extends User implements HasMapper
{
    protected $mapper;

    public function setMapper(MapperInterface $mapper)
    {
        $this->mapper = $mapper;
        return $this;
    }

    public function getMapper()
    {
        return $this->mapper;
    }
}


text:
package de.saly.es.example.audit.service;

import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.LockSupport;

import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthStatus;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.action.bulk.BulkProcessor;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.component.AbstractLifecycleComponent;
import org.elasticsearch.common.component.LifecycleListener;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.netty.util.internal.ConcurrentHashMap;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.engine.Engine.Create;
import org.elasticsearch.index.engine.Engine.Delete;
import org.elasticsearch.index.engine.Engine.DeleteByQuery;
import org.elasticsearch.index.engine.Engine.Index;
import org.elasticsearch.index.indexing.IndexingOperationListener;
import org.elasticsearch.index.settings.IndexSettingsService;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.IndicesLifecycle;
import org.elasticsearch.indices.IndicesService;

import de.saly.es.example.audit.action.flush.TransportFlushAction;

public class AuditService extends AbstractLifecycleComponent<AuditService> {

    public static final String SETTING_AUDIT_INDEX_NAME = "audit.index_name";
    public static final String SETTING_AUDIT_CAPTURE_SETTINGS_CHANGES = "audit.capture_settings_changes";

    public static final String DEFAULT_AUDIT_INDEX_NAME = "audit";
    public static final String AUDIT_INDEX_INDEXING_TYPE = "indexevents";
    private final String auditIndexName;
    private final boolean captureSettingsChanges;
    private final IndicesService indicesService;
    private final Client client;
    private final ClusterService clusterService;
    private volatile boolean isMaster = false;
    private final BulkProcessor bulk;
    private final AtomicInteger pendingBulkItemCount = new AtomicInteger();
    private Thread poller;

    private final IndicesLifecycle.Listener auditIndicesLsListener = new IndicesLifecycle.Listener() {

        private final ConcurrentHashMap<ShardId, AuditIndexOpListener> listeners = new ConcurrentHashMap<ShardId, AuditService.AuditIndexOpListener>();

        @Override
        public void afterIndexCreated(final IndexService indexService) {
            if (isMaster && !indexService.index().name().equals(auditIndexName)) {
                recordIndexCreate(indexService);
            }
        }

        @Override
        public void afterIndexDeleted(final org.elasticsearch.index.Index index, final Settings indexSettings) {
            if (isMaster && !index.name().equals(auditIndexName)) {
                recordIndexDelete(index);
            }
        }

        @Override
        public void afterIndexShardStarted(final IndexShard indexShard) {

            if (indexShard.routingEntry().primary() && !indexShard.indexService().index().name().equals(auditIndexName)) {

                final AuditIndexOpListener auditListener = new AuditIndexOpListener(indexShard);

                if (captureSettingsChanges) {
                    indexShard.indexService().settingsService().addListener(auditListener);
                }

                indexShard.indexingService().addListener(auditListener);

                listeners.put(indexShard.shardId(), auditListener);

                logger.info("Listener for shard {} added", indexShard.shardId());
            }
        }

        @Override
        public void beforeIndexShardClosed(final ShardId shardId, final IndexShard indexShard, final Settings indexSettings) {
            final AuditIndexOpListener listener = listeners.remove(shardId);

            if (listener != null) {
                indexShard.indexingService().removeListener(listener);
                logger.info("Listener for shard {} removed", shardId);
            }
        };
    };

    @Inject
    public AuditService(final Settings settings, final IndicesService indicesService, final Client client,
            final ClusterService clusterService, final TransportFlushAction tfa) {
        super(settings);
        auditIndexName = settings.get(SETTING_AUDIT_INDEX_NAME, DEFAULT_AUDIT_INDEX_NAME);
        captureSettingsChanges = settings.getAsBoolean(SETTING_AUDIT_CAPTURE_SETTINGS_CHANGES, false);
        this.indicesService = indicesService;
        this.client = client;
        this.clusterService = clusterService;
        tfa.setAuditService(this);
        bulk = BulkProcessor.builder(client, new BulkProcessor.Listener() {

            @Override
            public void beforeBulk(final long executionId, final BulkRequest request) {
            }

            @Override
            public void afterBulk(final long executionId, final BulkRequest request, final Throwable failure) {
                logger.error("Bulk error", failure);
                pendingBulkItemCount.addAndGet(-request.numberOfActions());
            }

            @Override
            public void afterBulk(final long executionId, final BulkRequest request, final BulkResponse response) {
                pendingBulkItemCount.addAndGet(-response.getItems().length);
            }
        }).setBulkActions(100).setConcurrentRequests(0)
        //.setBulkSize()
        //.setFlushInterval(TimeValue.timeValueSeconds(1))
        .build();

        this.clusterService.addLifecycleListener(new LifecycleListener() {

            @Override
            public void afterStart() {

                client.admin().cluster().prepareHealth().setWaitForYellowStatus().execute(new ActionListener<ClusterHealthResponse>() {
                    @Override
                    public void onResponse(final ClusterHealthResponse response) {
                        if (response.getStatus() == ClusterHealthStatus.RED) {
                            logger.error("The cluster is not available. The status is RED.");
                        } else {
                            logger.info("cluster ok, will check index");
                            checkAuditIndex();

                        }
                    }

                    @Override
                    public void onFailure(final Throwable e) {
                        logger.error("The cluster is not available.", e);
                    }
                });

            }
        });
    }

    private void createAuditIndex() {

        logger.info("will create audit index");

        final Settings auditIndexSettings = ImmutableSettings.builder().put(SETTING_NUMBER_OF_SHARDS, 3).put(SETTING_NUMBER_OF_REPLICAS, 1)
                .build();

        final XContentBuilder auditIndexEventsTypeMapping = Change.getMapping();

        client.admin().indices().prepareCreate(auditIndexName).addMapping(AUDIT_INDEX_INDEXING_TYPE, auditIndexEventsTypeMapping)
        .setSettings(auditIndexSettings).execute(new ActionListener<CreateIndexResponse>() {
            @Override
            public void onResponse(final CreateIndexResponse response) {
                if (!response.isAcknowledged()) {
                    logger.error("Failed to create {}.", auditIndexName);
                    throw new ElasticsearchException("Failed to create index " + auditIndexName);
                }
            }

            @Override
            public void onFailure(final Throwable e) {
                logger.error("Failed to create {}", e, auditIndexName);
            }
        });
    }

    private void checkAuditIndex() {

        client.admin().indices().prepareExists(auditIndexName).execute(new ActionListener<IndicesExistsResponse>() {
            @Override
            public void onResponse(final IndicesExistsResponse response) {
                if (response.isExists()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("{} index exists already.", auditIndexName);
                    }
                } else {
                    createAuditIndex();
                }
            }

            @Override
            public void onFailure(final Throwable e) {
                logger.error("The state of {} index is invalid.", e, auditIndexName);
            }
        });
    }

    @Override
    protected void doStart() throws ElasticsearchException {
        logger.info("doStart()");

        poller = new Thread(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    try {
                        final IndexRequest req = queue.take();
                        if (req == null) {
                            break;
                        }
                        bulk.add(req);
                    } catch (final InterruptedException e) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                }
                logger.info("poller thread died");
            }
        });
        poller.setDaemon(true);
        poller.setName("poller");
        poller.start();

        this.clusterService.add(new ClusterStateListener() {

            @Override
            public void clusterChanged(final ClusterChangedEvent event) {

                if (event.localNodeMaster()) {
                    isMaster = true;
                } else {
                    isMaster = false;
                }

            }
        });

        this.indicesService.indicesLifecycle().addListener(auditIndicesLsListener);

    }

    @Override
    protected void doStop() throws ElasticsearchException {
        logger.info("doStop()");
        shutdown();
    }

    @Override
    protected void doClose() throws ElasticsearchException {
        logger.info("doClose()");
        shutdown();
    }

    private void shutdown() {
        flush();

        this.indicesService.indicesLifecycle().removeListener(auditIndicesLsListener);

        try {
            bulk.awaitClose(5, TimeUnit.SECONDS);
        } catch (final InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        try {
            queue.add(null);

            try {
                poller.join(1000);
            } catch (final InterruptedException e) {
                Thread.currentThread().interrupt();
            }

        } catch (final IllegalStateException ise) {
            logger.warn("Cannot shutdown poller thread", ise);
        }

    }

    public int flush() {

        while (queue.size() > 0) {
            LockSupport.parkNanos(1000 * 50);
        }

        final int count = pendingBulkItemCount.get();
        bulk.flush();

        //if ConcurrentRequests > 0 we ll wait here because close() triggers a flush which is async
        while (pendingBulkItemCount.get() > 0) {
            LockSupport.parkNanos(1000 * 50);
        }

        logger.info("flushing " + count + " ...");
        return count;
    }

    //TODO capture alias changes too
    protected void recordIndexCreate(final IndexService indexService) {
        if (indexService == null) {
            return;
        }

        final String nodeName = indexService.nodeName();
        final String indexName = indexService.index().name();
        final Settings indexSettings = indexService.settingsService().getSettings();
        BytesReference settingsAsBytesReference = null;
        try {
            settingsAsBytesReference = indexSettings
                    .toXContent(XContentBuilder.builder(JsonXContent.jsonXContent), ToXContent.EMPTY_PARAMS).bytes();
        } catch (final IOException e) {
            logger.error("Unable to convert to bytes reference", e);
        }

        final Change change = new Change(nodeName, indexName, null, null, settingsAsBytesReference, -1, Change.ChangeType.INDEX_CREATE);
        storeChange(change);
    }

    protected void recordIndexDelete(final org.elasticsearch.index.Index index) {
        if (index == null) {
            return;
        }

        final String indexName = index.name();

        final Change change = new Change(null, indexName, null, null, null, -1, Change.ChangeType.INDEX_DELETE);
        storeChange(change);
    }

    protected void recordDataChange(final DeleteByQuery operation, final IndexShard indexShard) {
        if (operation == null) {
            return;
        }

        final String nodeName = indexShard.nodeName();
        final String indexName = indexShard.indexService().index().name();

        final Change change = new Change(nodeName, indexName, operation.types(), null, operation.source(), -1,
                Change.ChangeType.DATA_DELETE);
        storeChange(change);
    }

    protected void recordDataChange(final Create operation, final IndexShard indexShard) {
        if (operation == null) {
            return;
        }

        final String nodeName = indexShard.nodeName();
        final String indexName = indexShard.indexService().index().name();

        final Change change = new Change(nodeName, indexName, new String[] { operation.type() }, operation.id(), operation.source(),
                operation.version(), Change.ChangeType.DATA_CREATE);
        storeChange(change);
    }

    protected void recordDataChange(final Delete operation, final IndexShard indexShard) {
        if (operation == null) {
            return;
        }

        final String nodeName = indexShard.nodeName();
        final String indexName = indexShard.indexService().index().name();

        final Change change = new Change(nodeName, indexName, new String[] { operation.type() }, operation.id(), null, operation.version(),
                Change.ChangeType.DATA_DELETE);
        storeChange(change);
    }

    protected void recordDataChange(final Index operation, final IndexShard indexShard) {
        if (operation == null) {
            return;
        }

        final String nodeName = indexShard.nodeName();
        final String indexName = indexShard.indexService().index().name();

        final Change change = new Change(nodeName, indexName, new String[] { operation.type() }, operation.id(), operation.source(),
                operation.version(), Change.ChangeType.DATA_CREATE);
        storeChange(change);
    }

    protected void recordIndexSettingsChange(final Settings settings, final IndexShard indexShard) {
        final String nodeName = indexShard.nodeName();
        final String indexName = indexShard.indexService().index().name();
        BytesReference settingsAsBytesReference = null;
        try {
            settingsAsBytesReference = settings.toXContent(XContentBuilder.builder(JsonXContent.jsonXContent), ToXContent.EMPTY_PARAMS)
                    .bytes();
        } catch (final IOException e) {
            logger.error("Unable to convert to bytes reference", e);
        }

        final Change change = new Change(nodeName, indexName, null, null, settingsAsBytesReference, -1, Change.ChangeType.INDEX_SETTINGS);
        storeChange(change);
    }

    private final LinkedBlockingQueue<IndexRequest> queue = new LinkedBlockingQueue<IndexRequest>();

    protected void storeChange(final Change change) {

        try {
            queue.put(new IndexRequest(auditIndexName).type(AUDIT_INDEX_INDEXING_TYPE).source(change.event));
            pendingBulkItemCount.addAndGet(1);
        } catch (final InterruptedException e) {

            e.printStackTrace();
        }

        //logger.info("{}", change);
    }

    protected static class Change {

        private final Map<String, Object> event = new HashMap<String, Object>();

        public enum ChangeType {
            DATA_CREATE, INDEX_CREATE, DATA_DELETE, INDEX_DELETE, INDEX_SETTINGS;
        };

        public Change(final String nodeName, final String index, final String[] type, final String id, final BytesReference jsonContent,
                final long version, final ChangeType changeType) {
            super();
            event.put("@timestamp", new Date());
            event.put("node_name", nodeName);
            event.put("index", index);
            event.put("type", type == null ? null : Arrays.asList(type));
            event.put("id", id);
            try {
                event.put("content", jsonContent == null ? null : XContentHelper.convertToJson(jsonContent, false));
            } catch (final IOException e) {
                event.put("content", e.toString());
            }
            event.put("version", version);
            event.put("change_type", changeType.toString());
        }

        public static XContentBuilder getMapping() {
            try {
                return XContentBuilder.builder(JsonXContent.jsonXContent).startObject().startObject(AUDIT_INDEX_INDEXING_TYPE)
                        .startObject("properties")

                        // @timestamp
                        .startObject("@timestamp").field("type", "date").field("format", "dateOptionalTime").endObject()

                        // node_name
                        .startObject("node_name").field("type", "string").field("index", "not_analyzed").endObject()

                        // index
                        .startObject("index").field("type", "string").field("index", "not_analyzed").endObject()

                        // type
                        .startObject("type").field("type", "string").field("index", "not_analyzed").endObject()

                        // id
                        .startObject("id").field("type", "string").field("index", "not_analyzed").endObject()

                        // content
                        .startObject("content").field("type", "string").endObject()

                        // version
                        .startObject("version").field("type", "long").endObject()

                        // change_type
                        .startObject("change_type").field("type", "string").field("index", "not_analyzed").endObject()

                        .endObject().endObject().endObject()

                        ;
            } catch (final IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        public String toString() {
            return "Change [event=" + event + "]";
        }
    }

    private class AuditIndexOpListener extends IndexingOperationListener implements IndexSettingsService.Listener {

        private final IndexShard indexShard;

        public AuditIndexOpListener(final IndexShard indexShard) {
            super();
            this.indexShard = indexShard;
        }

        @Override
        public void postIndex(final Index index) {
            recordDataChange(index, indexShard);
        }

        @Override
        public void postDelete(final Delete delete) {
            recordDataChange(delete, indexShard);
        }

        @Override
        public void postDeleteByQuery(final DeleteByQuery deleteByQuery) {
            recordDataChange(deleteByQuery, indexShard);
        }

        @Override
        public void postCreate(final Create create) {
            recordDataChange(create, indexShard);
        }

        @Override
        public void onRefreshSettings(final Settings settings) {
            recordIndexSettingsChange(settings, indexShard);

        }
    }
}


text:
/**
 * Auto-configuration for JDBC.
 */
package org.springframework.boot.autoconfigure.jdbc;


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Vila</tipo><logradouro>Barros</logradouro><bairro>Brás</bairro><cidade>São Paulo</cidade><uf>SP</uf><cep>03050003</cep></feed>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Moq;
using Newtonsoft.Json;
using Ploeh.AutoFixture.Xunit2;
using RedArrow.Argo.Client.Cache;
using RedArrow.Argo.Client.Collections.Generic;
using RedArrow.Argo.Client.Config.Model;
using RedArrow.Argo.Client.Http;
using RedArrow.Argo.Client.Http.Handlers.Response;
using RedArrow.Argo.Client.Model;
using RedArrow.Argo.Client.Session.Registry;
using RedArrow.Argo.Client.Tests.Extensions;
using WovenByFody;
using Xunit;

namespace RedArrow.Argo.Client.Tests.Collections.Generic
{
    public class RemoteGenericBagTests
    {
        [Theory, AutoData]
        public void Ctor__Given_Items__When__Then_SetItemIds()
        {
            var uri = "http://www.test.com/";

            var items = Enumerable.Range(0, 3)
                .Select(i => new BasicModel())
                .ToArray();

            var modelRegistry = CreateModelRegistry(typeof(ComplexModel), typeof(BasicModel));

            var mockRequestBuilder = new Mock<IHttpRequestBuilder>();

            var cachedItems = new List<object>();
            var mockCacheProvider = new Mock<ICacheProvider>();
            mockCacheProvider
                .Setup(x => x.Update(It.IsAny<Guid>(), It.IsAny<BasicModel>()))
                .Callback<Guid, object>((id, m) =>
                {
                    cachedItems.Add(m);
                    mockCacheProvider
                        .Setup(y => y.Retrieve<BasicModel>(id))
                        .Returns((BasicModel) m);
                });
            mockCacheProvider
                .SetupGet(x => x.Items)
                .Returns(() => cachedItems);

            var expectedRequest = new HttpRequestMessage(HttpMethod.Get, new Uri(uri));
            var mockHandler = new MockRequestHandler();
            mockHandler.Setup(
                new Uri(uri),
                request =>
                {
                    Assert.Same(expectedRequest, request);
                    return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(JsonConvert.SerializeObject(new ResourceRootCollection
                        {
                            Data = Enumerable.Empty<Resource>()
                        }))
                    });
                });

            var session = CreateSession(
                mockHandler,
                mockRequestBuilder.Object,
                mockCacheProvider.Object,
                modelRegistry);

            var parent = session.ManageModel(new ComplexModel());

            mockRequestBuilder
                .Setup(x => x.GetRelated(parent.Id, modelRegistry.GetResourceType<ComplexModel>(), "test"))
                .Returns(expectedRequest);

            var subject = new RemoteGenericBag<BasicModel>(session, parent, "test", items);

            Assert.True(subject.Any());
            Assert.Equal(3, subject.Count());

            Assert.All(items, item =>
            {
                Assert.NotEqual(Guid.Empty, item.Id);
                Assert.Contains(item, subject);
            });
        }

        private static IModelRegistry CreateModelRegistry(params Type[] types)
        {
            return new ModelRegistry(types.Select(x => new ModelConfiguration(x)), new JsonSerializerSettings());
        }

        private static Client.Session.Session CreateSession(
            HttpMessageHandler mockHandler = null,
            IHttpRequestBuilder requestBuilder = null,
            ICacheProvider cacheProvider = null,
            IModelRegistry modelRegistry = null,
            JsonSerializerSettings jsonSettings = null)
        {
            if (mockHandler == null)
            {
                mockHandler = new HttpClientHandler();
            }

            return new Client.Session.Session(
                () => new HttpClient(mockHandler),
                requestBuilder ?? Mock.Of<IHttpRequestBuilder>(),
                cacheProvider ?? Mock.Of<ICacheProvider>(),
                modelRegistry ?? Mock.Of<IModelRegistry>(),
                jsonSettings ?? new JsonSerializerSettings(),
                Mock.Of<BundledHttpResponseListener>());
        }
    }
}